我有一个测试(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 结束时没有回滚事务。