【问题标题】:Preserve data across LiveServerTestCase test methods?跨 LiveServerTestCase 测试方法保留数据?
【发布时间】: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 末尾没有删除数据库记录,则两者都会通过。

【问题讨论】:

标签: python django unit-testing


【解决方案1】:

摘自: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
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 2015-08-10
    • 2013-03-13
    • 2018-04-04
    • 2019-10-04
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多