MW *_*ost 7 python django unit-testing
因为LiveServerTestCase继承自TransactionTestCase,默认行为是在每个测试方法结束时删除测试数据。我想使用LiveServerTestCase该类,但保留方法与方法之间的测试数据。在本例中,test2失败是因为数据库在test1.
我的理解是,如果我使用TestCase,它会在每次测试结束时回滚事务并将数据库返回到其起始条件。我可以在使用 时模仿这种行为LiveServerTestCase吗?
class TestTheTests(LiveServerTestCase):
@classmethod
def setUpTestData(cls):
print('running setUpTestData')
call_command('loaddata', 'datasources.yaml' )
@classmethod
def setUpClass(cls):
print('starting setUpClass')
cls.setUpTestData() # load the data for the entire test class
super().setUpClass()
@classmethod
def tearDownClass(cls):
print('finished tearDownClass')
super().tearDownClass()
def setUp(self):
self.browser = webdriver.Chrome()
def tearDown(self):
self.browser.quit()
Run Code Online (Sandbox Code Playgroud)
当我同时运行这两个测试时,此测试通过:
def test1(self):
print('test 1 running')
self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test1')
Run Code Online (Sandbox Code Playgroud)
此测试失败:
def test2(self):
print('test 2 running')
self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test2')
Run Code Online (Sandbox Code Playgroud)
如果数据库记录在test1.
摘自: https: //docs.djangoproject.com/en/3.1/topics/testing/overview/#rollback-emulation
Django 可以通过在 TestCase 或 TransactionTestCase 主体中将 serialized_rollback 选项设置为 True 来为每个测试用例重新加载该数据,但请注意,这将使该测试套件的速度降低大约 3 倍。
这将解决您的问题:
class TestTheTests(LiveServerTestCase):
serialized_rollback = True
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |