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 完整性,似乎有一个选项可以尝试:
在 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/