【问题标题】:How to call pytest-django from python manage.py test?如何从 python manage.py test 调用 pytest-django?
【发布时间】:2020-05-12 13:41:08
【问题描述】:

我已经创建了名为 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 django-admin pytest pytest-django django-management-command


    【解决方案1】:

    我在这里找到了我的解决方案: 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
    

    【讨论】:

    • 对我来说它不起作用 TEST_RUNNER = "your_project.your_app.runner"。相反, TEST_RUNNER = "your_app.runner.PytestTestRunner" 起作用了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2016-08-01
    • 1970-01-01
    • 2011-06-20
    • 2011-06-18
    • 2018-07-01
    相关资源
    最近更新 更多