gpt4 book ai didi

python - 跨 LiveServerTestCase 测试方法保留数据?

转载 作者:行者123 更新时间:2023-12-03 14:57:15 28 4
gpt4 key购买 nike

因为 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 末尾没有删除数据库记录,两者都会通过。 .

最佳答案

摘自:https://docs.djangoproject.com/en/3.1/topics/testing/overview/#rollback-emulation

Django can reload that data for you on a per-testcase basis by setting the serialized_rollback option to True in the body of the TestCase or TransactionTestCase, but note that this will slow down that test suite by approximately 3x.


这将解决您的问题:
class TestTheTests(LiveServerTestCase):
serialized_rollback = True
...

关于python - 跨 LiveServerTestCase 测试方法保留数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49884112/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com