两个测试单独工作但不能一起工作

Two tests works individually but not together

我有两个单独的测试 类 测试相似的行为 :

  1. 正在使用 Client() 在书签中添加产品。
  2. 正在使用 ORM 将产品添加到书签中。

就个人而言,它正在工作:

./manage.py test compare.test.CompareBookmarkTests

./manage.py test compare.test.CompareAccountTests

它们一起启动时失败:

./manage.py test

我试过:

目前我还没有在 Whosebug 上找到相关答案。在 django 文档中都没有。


from django.contrib.auth.models import User
from django.test import TestCase
from .models import Bookmark, Categorie, Product


class CompareBookmarkTests(TestCase):
    def setUp(self):
        Categorie.objects.create(id_categorie='someid', name='somename')
        p = Categorie.objects.get(pk='someid')
        p.product_set.create(id_product='1', product_name='orange', categorie='someid')
        User.objects.create_user('john@sign.in', 'john@sign.in', 'smith')

    def tearDown(self):
        User.objects.all().delete()
        Categorie.objects.all().delete()
        Bookmark.objects.all().delete()

    def test_redirect_logged(self):
        self.client.login(username='john@sign.in', password='smith')

        # Adding product with id 1 in bookmark
        response = self.client.get('/compare/1/bookmark/')

        # Get added product form bookmark
        bookmark = Bookmark.objects.get(pk=1)
        self.assertEqual(str(bookmark), 'Bookmark object (1)')
        self.assertEqual(response.status_code, 302)


class CompareAccountTests(TestCase):
    def setUp/tearDown: [same as previous class]

    def test_get_product(self):
        self.client.login(username='john@sign.in', password='smith')

        user = User.objects.get(pk=1)
        product = Product.objects.get(pk='1')

        # Adding product with id 1 in bookmark
        add_bookmark = Bookmark.objects.create(id_result=product, user=user)

        bookmark = Bookmark.objects.get(pk=1)
        response = self.client.get('/compare/account/')
        self.assertEqual(str(bookmark), 'Bookmark object (1)')
        self.assertEqual(response.status_code, 200)

我希望我的两个测试一起启动时都能成功,但我得到:

compare.models.Bookmark.DoesNotExist: Bookmark matching query does not exist.

使用 --reverse :

django.contrib.auth.models.User.DoesNotExist

可能是初学者的错误,但是我看不到,谢谢帮助!

我找到了可能导致问题的原因:

我使用了psql,我发现测试数据库没有被删除:

test_myprojet_1
test_myprojet_2
test_myprojet_3
test_myprojet_4
...and so on...

除了一个很奇怪的:

test_test_test_test_test_test_test_test_test_test_test_myprojec[truncated name]

我在psql中使用:

DROP DATABASE [name];

现在,我的测试按预期进行!

感谢awesoon,你的建议让我走上了这条路。