没有db的django单元测试 [英] django unit tests without a db
问题描述
是否有可能在不设置db的情况下编写django unittests?我想测试不需要db来设置的业务逻辑。虽然设置数据库的速度很快,但在某些情况下我真的不需要它。
您可以将DjangoTestSuiteRunner并覆盖setup_databases和teardown_databases方法传递。
创建一个新的设置文件,并将TEST_RUNNER设置为刚创建的新类。然后,当您运行测试时,请使用--settings标志指定新的设置文件。
这是我所做的:
创建一个类似于这样的自定义测试套件:
从django.test.simple import DjangoTestSuiteRunner
class NoDbTestRunner(DjangoTestSuiteRunner):
没有数据库创建测试的测试运行器
def setup_databases(self,** kwargs):
覆盖父类中定义的数据库创建
pass
def teardown_databases(self,old_config,** kwargs):
覆盖数据库拆卸在父类中定义
pass
创建自定义设置:来自mysite.settings import的
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$'''''''''''
TEST_RUNNER = mysite.scripts.testrunner.NoDbTestRunner'
当你运行测试时,像以下的--settings标志设置为您的新设置文件:
python manage.py test myapp --settings ='no_db_settings'
Is there a possibility to write django unittests without setting up a db? I want to test business logic which doesn't require the db to set up. And while it is fast to setup a db, I really don't need it in some situations.
You can subclass DjangoTestSuiteRunner and override setup_databases and teardown_databases methods to pass.
Create a new settings file and set TEST_RUNNER to the new class you just created. Then when you're running your test, specify your new settings file with --settings flag.
Here is what I did:
Create a custom test suit runner similar to this:
from django.test.simple import DjangoTestSuiteRunner
class NoDbTestRunner(DjangoTestSuiteRunner):
""" A test runner to test without database creation """
def setup_databases(self, **kwargs):
""" Override the database creation defined in parent class """
pass
def teardown_databases(self, old_config, **kwargs):
""" Override the database teardown defined in parent class """
pass
Create a custom settings:
from mysite.settings import *
# Test runner with no database creation
TEST_RUNNER = 'mysite.scripts.testrunner.NoDbTestRunner'
When you're running your tests, run it like the following with --settings flag set to your new settings file:
python manage.py test myapp --settings='no_db_settings'
这篇关于没有db的django单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!