繁体   English   中英

Django pytest:在运行测试用例后清除数据库

[英]Django pytest: Clear DB after a running a test case

我有一个测试(django pytest),需要测试数据库中的对象。 问题是在测试之后,数据库“脏了”,其他测试失败了。 我看到了一些有关TransactionTestCase的信息,但我不明白它如何与Django测试一起使用。

这是我当前代码的一个简单示例:

@pytest.mark.django_db
def test_something(mock_my_obj):
    mock_my_obj.save()
    # test test test
    ...
    # I don't want to delete the obj here...

更新:第二次尝试:我读到TestCase应该使用事务并将其回滚到每个测试。 不为我工作:

from django.test import TestCase

class MyTests(TestCase):
    def test_yair_a(self):
        print 'AAAAAAA'
        print Account.objects.all()
        Account.objects.create(account_id=1,account_name='1')
        print Account.objects.all()

    def test_yair_b(self):
        print 'BBBBBBBB'
        print Account.objects.all()
        Account.objects.create(account_id=2,account_name='2')
        print Account.objects.all()

结果(有趣的部分):

> py.test -s -v -k test_yair
AAAAAAA
[]
[<Account: 1>]
PASSED

BBBBBBBB
[<Account: 1>]
[<Account: 1>, <Account: 2>]
PASSED

这意味着在test_a的末尾没有事务回滚。

问题在于,默认情况下,django在默认数据库上创建一个事务。 我需要另一个数据库上的事务。 这是我的设置文件:

ROOT_PASS = 'ohnoyoudidnt'
ROOT_USER = 'root'
ROOT_HOST = 'localhost'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'default_db',
        'USER': ROOT_USER,
        'PASSWORD': ROOT_PASS,
        'HOST': ROOT_HOST,
        'PORT': '3306',
    },
    'my_app': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'my_app_db',
        'USER': ROOT_USER,
        'PASSWORD': ROOT_PASS,
        'HOST': ROOT_HOST,
        'PORT': '3306'
    },

为了解决这个问题,需要使用transaction.atomic(using='my_app')块,并向其中抛出错误以进行回滚。 自然,我想为此编写一个装饰器,但是与pytest一起使用它并没有我最初想到的那么简单,因为pytest本身会在代码之前(使用模拟和补丁时)操纵该方法。

花了几个小时后,我得到了这个可以使用的装饰器!

from decorator import decorator
import pytest
from django.db import transaction


class TestTempException(Exception):
    pass


def testing_w_transaction(using):
    def testing_w_transaction_inner(function):
        def func_wrapper(f, *args, **kwargs):
            try:
                with transaction.atomic(using=using):
                    f(*args, **kwargs)
                    raise TestTempException()
            except TestTempException:
                pass
        return decorator(func_wrapper, pytest.mark.django_db(function))
    return testing_w_transaction_inner

用法:

@testing_w_transaction(using='my_app')
def test_my_method(mock_object, ...):
     # test test test

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM