django - 如何从 python manage.py test 调用 pytest-django?
问题描述
我制作了名为 pytest_wrp 的自定义管理命令
所以当我打电话时
python manage.py test
这段代码称为:
class Command(test.Command):
def handle(self, *args, **options):
super(Command, self).handle(*args, **options) # this calls the python manage.py test
self.stdout.write("My code starts from here.")
management.call_command(pytest_wrp.Command(), '--pact-files="{argument}"'.format(argument=path_to_file), '--pact-provider-name="MyService"', verbosity=0)
pytest_wrp
基本上有这个代码:
class Command(BaseCommand):
help = "Runs tests with Pytest"
def add_arguments(self, parser):
parser.add_argument("args", nargs=argparse.REMAINDER)
def handle(self, *args, **options):
pytest.main(list(args)) # This doesn't accept the pact args, even if you specify a "--" separator
但这调用pytest
不是pytest-django
因此,我传递的额外参数没有得到识别,pytest 无法启动测试套件。
我想为一些测试用例传递额外的参数。如果有某种方法可以直接调用 pytest-django 并在代码中传递额外的参数,那将是最佳的。
解决方案
我在这里找到了我的解决方案:
切换到 django-pytest 后,我还能使用 `manage.py test` 吗?
对于完整而全面的文档,您需要查看此内容。简而言之,您需要覆盖config/test.py
或config.py
取决于您的应用程序的设置方式
TEST_RUNNER = "your_project.your_app.runner"
你runner.py
会看起来像这样
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')
# NOTE: You don't need to quote the argument value here, they do some weird string pattern matching internally
argv.append('--pact-files={argument}'.format(argument=path_to_file))
argv.append('--pact-provider-name=MyService')
argv.extend(test_labels)
return pytest.main(argv)
请确保您有pytest-django
包裹
pip install pytest-django
推荐阅读
- angular - 如何以角度对窗口对象进行单元测试
- python - 向量化 for 循环,它结合了两个不同的数据帧
- apache - 多个网站无限 index.php 循环
- arrays - 在聚合函数中循环遍历数组
- e-signature - 无法通过 adobesign 中的 Rest API 更新协议中的表单字段
- c++ - 添加两个变量以创建目录路径
- r - if 函数中的语句未执行
- flutter - Flutter:如何从 api 获取数据一次并用于不同的屏幕
- ios - Flutter Web 应用程序 - 音频播放器在 ios 移动站点上崩溃,但在桌面站点上运行
- android - 如何将相同的跨度应用于android中的多个字符串?