【问题标题】:Django: All subsequent tests fail after one test failsDjango:一个测试失败后所有后续测试都失败
【发布时间】:2020-09-13 11:14:47
【问题描述】:

我最近从 Python 2.7 迁移到了 Python 3.8。运行测试时出现了一个奇怪的新现象,可以通过这个简单的示例重现:

from django.test import TestCase
from users.models import User


class TestWTF(TestCase):
    def setUp(self):
        self.user = User.objects.create(email='admin@project.com')

    def test_failure(self):
        self.assertTrue(False)

    def test_success(self):
        pass

test_failure() 失败时,self.user 对象不会从数据库中删除。似乎承诺的回滚功能没有发生。当setUp() 尝试再次创建对象时,test_success() 和同一类中的所有后续测试都将失败,并违反 UNIQUE 约束。

这在 Python 2 中不会发生。

我正在使用的pytest 的部分输出:

$ pytest -W ignore -s
================================================= test session starts ==================================================
platform linux -- Python 3.8.2, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
django: settings: project_sites.settings.tests (from ini)
rootdir: /home/emes/devel/project/project, inifile: pytest.ini
plugins: django-3.8.0, env-0.6.2, case-1.5.3, cov-2.8.1
collected 2 items
[...]
=============================================== short test summary info ================================================
FAILED deals/tests/test_wtf.py::TestWTF::test_failure - AssertionError: False is not true
FAILED deals/tests/test_wtf.py::TestWTF::test_success - django.db.utils.IntegrityError: UNIQUE constraint failed: use...
================================================== 2 failed in 22.76s ==================================================

编辑:我正在使用 Django-1.11.26

【问题讨论】:

  • 你应该删除tearDown中的用户:docs.python.org/3/library/…
  • 你有完整的代码示例我们可以试试吗?
  • 我的预感是你项目中的某些东西正在干扰 Django 的测试隔离。
  • 我无法使用 Python 3.8 和 Django 3.0.6 重现您的错误。
  • 你正在运行什么命令以及如何运行?

标签: python django python-unittest pytest-django


【解决方案1】:

我在 Python 3.6 上使用 Django 2.2 时遇到了同样的问题。

我使用的是 pytest 5.4.1 和 pytest-django 3.8.0。

将 pytest-django 更新到 3.9.0 版本解决了这个问题,所以我认为这是 3.8.0 中的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2018-12-18
    相关资源
    最近更新 更多