当我通过键入运行测试用例时
python manage.py test myapp
测试用例完成后,测试数据库默认被 django test runner 删除。我不希望它被删除。
我可以使用任何数据库!
我想保留我的数据库,因为我想在创建的数据库中看到数据库中的错误。这样我就可以查明他们!
test --keepdb
您可以使用该选项防止测试数据库被破坏。
https://docs.djangoproject.com/en/dev/topics/testing/overview/#the-test-database
虽然传递-k
到manage.py test
将保留测试数据库,但它仍会删除在测试用例中创建的记录。这是因为 Django 的TestCase
类仍然会在每个测试用例之后重置您的数据库(django.test.TransactionTestCase
将执行flush
, 而django.test.TestCase
将每个测试用例包装在事务中,并在测试用例完成时进行回滚)。
让 Django 保留测试数据的唯一真正解决方案是扩展TestCase
类并覆盖重置数据库的代码。
However, if you do not have the time to do this, you can also make your test case pause execution before it finishes, giving you the time to inspect your database before it gets reset. There are several ways of achieving this, but, now, THIS IS A HACK, asking for user input
in your Python code will make Python pause execution and wait for user input.
from django.test import TestCase
class MyTestCase(TestCase):
def test_something_does_something(self):
result = do_something_with_the_database()
self.assertTrue(result)
# Ask for `input` so execution will pause and wait for input.
input(
'Execution is paused and you can now inspect the database.\n'
'Press return/enter key to continue:')
Alternatively, you can also use pdb
's set_trace
function, which will also make the execution pause and wait for input, and at the same time lets you debug the environment in that point of code execution.
Just make sure that you remove the input()
(or pdb.set_trace()
) call before you send your code to your automated build system or else it will wait for user input and time out.
To preserve whole database state after test execution (not only tables structure)
django.test.SimpleTestCase
(not TestCase or TransactionTestCase) def tearDown(self) -> None:
pass
@classmethod
def tearDownClass(cls):
pass
--keepdb
parameter, like ./manage.py test app.test --keepdb
- to prevent whole DB cleaning after test executiontest_
to your default database name]Example of command for test test_copy
./manage.py test --noinput --keepdb api.tests.SomeTests.test_copy
class SomeTests(SimpleTestCase):
allow_database_queries = True
def setUp(self):
super(SomeTests, self).setUp()
self.huge_set_up_operations()
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.huge_init_database()
def tearDown(self):
pass
@classmethod
def tearDownClass(cls):
pass
def test_copy(self):
SubscriptionFactory()
For anyone in a Pytest environment I use the following pytest.ini for testing
[pytest]
DJANGO_SETTINGS_MODULE=myapp.settings.test
python_files = tests.py test_*.py *_tests.py
addopts =
--ds=myapp.settings.test
--reuse-db
--nomigrations
note the "--resuse-db" command argument/addpots