在主Django数据库上运行Unittest [英] Run Unittest On Main Django Database
问题描述
我正在寻找一种在django测试期间运行完整芹菜设置的方法,在这个其他SO问题
I'm looking for a way to run a full celery setup during django tests, asked in this other SO question
在考虑之后,我想我可以安排运行单元测试它是更多的一个集成测试),其中我运行测试脚本对主Django(开发)数据库。有没有办法编写单元测试,使用Nose运行它们,并对主数据库执行?我想象这是一个关于django设置的Nose(或任何其他框架)的问题。
After thinking about it, I think I could settle for running a unittest (it's more of an integration test) in which I run the test script against the main Django (development) database. Is there a way to write unittests, run them with Nose and do so against the main database? I imagine it would be a matter of telling Nose (or whatever other framework) about the django settings.
我看过 django-nose
,但无法找到一种方法来告诉它使用主数据库,而不是测试。
I've looked at django-nose
but wasn't able to find a way to tell it to use the main DB and not a test one.
推荐答案
我不知道有关鼻子,但是这里是如何使用django(1.6)单元测试来反对现有的数据库。
I don't know about nose, but here is how to run against and existing db with django (1.6) unit tests.
from django.test.runner import DiscoverRunner
from django.db import transaction
class ExistingDBTestRunner(DiscoverRunner):
def run_tests(self, test_labels, extra_tests=None, **kwargs):
self.setup_test_environment()
suite = self.build_suite(test_labels, extra_tests)
#old_config = self.setup_databases()
result = self.run_suite(suite)
#self.teardown_databases(old_config)
self.teardown_test_environment()
return self.suite_result(suite, result)
然后在settings.py
Then in settings.py
if 'test' in sys.argv:
TEST_RUNNER = '<?>.ExistingDBTestRunner'
# alternative db settings?
在旧版本的django中会有所不同。此外,您可能需要在您的测试用例中覆盖_fixture_setup和_fixture_teard才能传递。
It will be a little different in older versions of django. Also, you may need to override _fixture_setup and _fixture_teardown in your test cases to pass.
上述代码将连接到预先存在的数据库,但由于每个测试都包含在一个事务中其他连接(如芹菜工作者)将无法使用更改。禁用交易的最简单的方法是从 unittest.TestCase
而不是 django.test.TestCase
。
The above code will connect to a preexisting database but since each test is wrapped in a transaction the changes won't be available to other connections (like the celery worker). The easiest way to disable transactions is to subclass from unittest.TestCase
instead of django.test.TestCase
.
这篇关于在主Django数据库上运行Unittest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!