【发布时间】:2018-09-27 18:36:19
【问题描述】:
因为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()
当我同时运行这两个测试时,此测试通过:
def test1(self):
print('test 1 running')
self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test1')
此测试失败:
def test2(self):
print('test 2 running')
self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test2')
如果在test1 末尾没有删除数据库记录,则两者都会通过。
【问题讨论】:
-
这条评论建议创建一个继承
TestCase的事务行为的新类:stackoverflow.com/questions/29378328/…
标签: python django unit-testing