好吧,一开始我认为这是不可能的,因为pytest-django已经在模块级别导入了很多django的东西,而且通过钩子插入你自己是不可能的——它们都是在通过入口点加载插件之后执行的,所以django届时就已经导入了。在
但是,看看pytest help,注意一个很少使用的选项,它在这种情况下非常有用:$ pytest help
...
test session debugging and configuration:
-p name early-load given plugin (multi-allowed). To avoid
loading of plugins, use the `no:` prefix, e.g.
`no:doctest`.
通过插件早期加载运行pymysql配置
因此,通过-parg传递的自定义插件将比通过入口点加载的插件更早导入。解决方案现在很简单:编写一个导入和配置pymysql并通过-parg传递它的小模块:
^{pr2}$
测试调用:$ PYTHONPATH=. pytest -p pymysql_hack -rapP server tests/server
我分叉了rematch项目来测试这一点,the jobs are looking good(第一个作业失败了,因为我懒得在所有需求文件中添加pymysql)。在
放弃pytest,使用manage.py test
或者(这是我的第一个解决方案建议),您可以通过manage.py运行测试,这样您就可以在manage.py之上添加{}配置行,实现一个自定义的测试运行器,如^{}'s FAQ所述:pytest-django is designed to work with the pytest command, but if you really need integration with manage.py test, you can create a simple test runner like this:class PytestTestRunner(object):
"""Runs pytest to discover and run tests."""
def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs):
self.verbosity = verbosity
self.failfast = failfast
self.keepdb = keepdb
def run_tests(self, test_labels):
"""Run pytest and return the exitcode.
It translates some of Django's test command option to pytest's.
"""
import pytest
argv = []
if self.verbosity == 0:
argv.append(' quiet')
if self.verbosity == 2:
argv.append(' verbose')
if self.verbosity == 3:
argv.append('-vv')
if self.failfast:
argv.append(' exitfirst')
if self.keepdb:
argv.append(' reuse-db')
argv.extend(test_labels)
return pytest.main(argv)
Add the path to this class in your Django settings:TEST_RUNNER = 'my_project.runner.PytestTestRunner'
并通过$ python manage.py test
但是,使用这个解决方案,您将无法通过直接调用pytest来运行测试。在