With py.test, database is not reset after LiveServerTestCase

非 Y 不嫁゛ 提交于 2019-12-05 05:54:43

A LiveServerTestCase and it's subclass StaticLiveServerTestCase both inherit from TransactionTestCase which differs from TestCase in the manner it resets the DB on test case tearDown. Here is the quote from the aforementioned documentation:

Django’s TestCase class (described below) makes use of database transaction facilities to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that some database behaviors cannot be tested within a Django TestCase class. For instance, you cannot test that a block of code is executing within a transaction, as is required when using select_for_update(). In those cases, you should use TransactionTestCase.

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback:

  • A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

  • A TestCase, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. This guarantees that the rollback at the end of the test restores the database to its initial state.

As you mentioned, you see the PK counter retained. This is because truncating tables, means dropping all rows, but this generally does not mean the PK counter is reset.

I assume you care about this because you are using asserting objects by specifying a PK (e.g assert YourModel.objects.filter(pk=1).exists().

Instead, I suggest that in your tests, you assert the existence of X objects (e.g assert YourModel.objects.count() == 1, or even assert the specific objects you expect to exist) and then use these objects in your test as you would usually.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!