Django数据泄漏2次分开的测试

时间:2018-01-18 19:01:52

标签: python django unit-testing

在我的整个测试基础中,我经历了两次测试的奇怪行为。他们是完全孤立的。但是,我可以在第二个测试中找到第一个测试的数据。以下是测试:

file1(services.tests)

class ServiceTestCase(TestCase):
    @patch('categories.models.ArticlesByCategory.objects.has_dish_type')
    def test_build_dishtype_conflicts(self, mock_has_dish_type):
        # WARN: create interference in tests
        restaurant = RestaurantFactory()
        dt_1 = DishTypeFactory(restaurant=restaurant)
        cat_1 = CategoryFactory(restaurant=restaurant)
        art_1 = ArticleFactory(name='fooA1', restaurant=restaurant)
        art_2 = ArticleFactory(name='fooA2', restaurant=restaurant)
        abc_1 = ArticlesByCategory.objects.create(category=cat_1, article=art_1, is_permanent=True,
                                              dish_type=dt_1)
        abc_2 = ArticlesByCategory.objects.create(category=cat_1, article=art_2, is_permanent=True,
                                              dish_type=dt_1)

        mock_has_dish_type.return_value = [abc_1, abc_2]
        abcs_to_check = ArticlesByCategory.objects.filter(pk__in=[abc_1.pk, abc_2.pk])
        conflicts = ServiceFactory()._build_dishtype_conflicts(abcs_to_check)
        self.assertDictEqual(conflicts, {dt_1.pk: 2})

file2(products.tests)

class ArticleQuerySetTestCase(TestCase):
def test_queryset_usable_for_category(self):
    restaurant = RestaurantFactory()
    category_1 = CategoryFactory(name='fooB1', restaurant=restaurant)
    category_2 = CategoryFactory(name='fooB2', restaurant=restaurant)
    article_1 = ArticleFactory(restaurant=restaurant)
    article_2 = ArticleFactory(restaurant=restaurant)

    ArticlesByCategory.objects.create(article=article_1, category=category_1, is_permanent=True)
    queryset_1 = Article.objects.usable_for_category(category_1)

    # This line is used for debug
    for art in Article.objects.all():
        print(art.name)

在同一命令中运行test_build_dishtype_conflicts THEN test_queryset_usable_for_category时,以下是第二次测试中print的结果:

fooA1
fooA2
fooB1
fooB2

我怀疑我做错了什么但找不到。

1 个答案:

答案 0 :(得分:0)

Ok从Django文档中找到了问题。

如果您的测试依赖于数据库访问,例如创建或查询模型,请确保将测试类创建为django.test.TestCase的子类,而不是unittest.TestCase。

使用unittest.TestCase可以避免在事务中运行每个测试并刷新数据库的成本,但如果测试与数据库交互,则其行为将根据测试运行器执行它们的顺序而有所不同。这可能导致单独测试在隔离运行时通过,但在套件中运行时会失败。