【问题标题】:Django test data persisting across multiple tests despite being TestCase尽管是 TestCase,Django 测试数据仍然存在于多个测试中
【发布时间】:2019-02-22 20:24:21
【问题描述】:

我有一个使用setUp 的测试用例,看起来像这样:

from django.test import TestCase, Client, TransactionTestCase
...
class TestPancakeView(TestCase):

    def setUp(self):
        self.client = Client()

        # The Year objects are empty (none here - expected)
        print(Year.objects.all())

        # When I run these Test by itself, these are empty (expected)
        # When I run the whole file, this prints out a number of
        # Pancake objects causing these tests to fail - these objects appear
        # to be persisting from previous tests
        print(Pancake.objects.all())

        # This sets up my mock/test data
        data_setup.basic_setup(self)

        # This now prints out the expected years that data_setup creates
        print(Year.objects.all())

        # This prints all the objects that I should have 
        # But if the whole file is ran - it's printing objects
        # That were created in other tests
        print(Pancake.objects.all())

        [...tests and such...]

data_setup.py 是一个文件,它只在需要时为我的测试创建所有适当的测试数据。我正在使用 Factory Boy 创建测试数据。

当我自己运行 TestPancakeView 时 - 我的测试按预期通过。

当我运行整个 test_views.py 文件时,我的 TestPancakeView 测试失败。

如果我将其更改为 TransactionTestCase - 当我运行整个文件时它仍然会失败。

我正在创建这样的 Pancake 测试数据:

        f.PancakeFactory.create_batch(
            2,
            flavor=blueberry,
            intensity='high'
        )

没有其他测试表现出这种行为,当我单独运行它们或将它们作为整个文件的一部分运行时,它们的行为方式都相同。

【问题讨论】:

    标签: django unit-testing testing django-testing pytest-django


    【解决方案1】:

    所以我发现这是因为我的 Pancake 类来自 Django 项目中的不同应用程序(它绑定到不同的数据库表);正因为如此——当我最初创建这些对象时——因为它们存在于不同的测试数据库中,所以它们一直存在。

    解决方案:

    对每个测试使用tearDown 功能。

    现在每个测试都有以下内容:

    def tearDown(self):
        food.Pancake.objects.all().delete()
    

    这可确保在每次测试后删除我的 Pancake 对象 - 因此我针对 Pancake 的测试特别通过,无论是单独运行还是与文件的其余部分一起运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-04
      • 2012-10-19
      • 1970-01-01
      • 2018-09-16
      • 2014-10-15
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多