python - 为什么对象主键在 Django 中的测试之间递增?

标签 python django unit-testing factory-boy

class MyClassTest(TestCase):
    def setUp(self):
        Someclass.objects.create()

    def test_first_test(self):
        # Here, Someclass.objects.all()[0].pk -> returns 1

    def test_second_test(self):
       # Here, Someclass.objects.all()[0].pk -> returns 2 !!! (bad !)

使用SetUp() 方法,应该在每次测试之间清除并重新创建数据。 那么,为什么 id 从一个测试递增到另一个?这对我来说并不明显。

这样我就无法根据 id 进行测试(因为它们依赖于其他测试)。 这就是为什么我希望始终得到 1 作为结果。

请注意,我对数据本身没有问题,旧数据从一个测试到另一个测试都很好地清除了。问题只是关于 ID。

我在这里阅读django object ids increment between unit tests问题与数据库有关,与 Django 无关,但是 Django 中有什么技巧可以改变它吗?

最佳答案

测试文档中有一个警告:

https://docs.djangoproject.com/en/dev/topics/testing/overview/

Warning If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.

Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.

您使用的是 django.test.TestCase 还是 unittest.TestCase

如果您需要保持 PK 完整性,似乎有一个选项可以尝试:

https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.TransactionTestCase.reset_sequences

在 TransactionTestCase 上设置 reset_sequences = True 将确保在测试运行之前始终重置序列:

class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
    reset_sequences = True

    def test_animal_pk(self):
        lion = Animal.objects.create(name="lion", sound="roar")
        # lion.pk is guaranteed to always be 1
        self.assertEqual(lion.pk, 1)

因为 django.test.LiveServerTestCase 似乎是 TransactionTestCase 的子类,这可能适合您。

关于python - 为什么对象主键在 Django 中的测试之间递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665629/

相关文章:

python - 添加到常规 numpy ndarray 时调用 scipy.sparse __add__ 方法?

Python 匹配贪婪短语搜索。

python - 我应该确保我的所有 Web 应用程序代码都是 UTF-8 编码吗?

unit-testing - 使用 ActiveSupport::TestCase 进行事件管理 Controller 测试

java - 单元测试同步

python - 程序未返回正确答案(计算最小周长)

html - 组合上下文和表单时,模板显示标记而不是页面

django - 更改 User 模型的用户名以使用 PhoneNumberField 而不是 CharField 会导致错误

python - python如何评估模块执行?

python - 由于 PySide2 和 Matplotlib,Travis-CI 无法构建