如何从 python manage.py 测试中调用 pytest-django?

How to call pytest-django from python manage.py test?

我已经创建了名为 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 并在最佳代码中传递额外参数。

我在这里找到了我的解决方案: Can I still use `manage.py test` after switching to django-pytest? 要获得完整全面的文档,您需要查看 this。简而言之,您需要覆盖 config/test.pyconfig.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