如何在使用 argparse 的文件上使用指定的测试目录运行 pytest? [英] How to run pytest with a specified test directory on a file that uses argparse?

查看:28
本文介绍了如何在使用 argparse 的文件上使用指定的测试目录运行 pytest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我正在使用 pytest
  • 为 Python 库编写单元测试
  • 我需要为测试文件指定一个目录以避免自动发现测试文件,因为有一个很大的子目录结构,包括库中包含_test"或test_"的许多文件在名称中,但不适用于 pytest
  • 库中的某些文件使用 argparse 来指定命令行选项
  • 问题是将 pytest 的目录指定为命令行参数似乎会干扰使用 argparse 的命令行选项
  • I am writing unit tests for a Python library using pytest
  • I need to specify a directory for test files to avoid automatic test file discovery, because there is a large sub-directory structure, including many files in the library containing "_test" or "test_" in the name but are not intended for pytest
  • Some files in the library use argparse for specifying command-line options
  • The problem is that specifying the directory for pytest as a command-line argument seems to interfere with using command line options for argparse

举个例子,我在根目录中有一个名为script_with_args.py的文件,如下:

To give an example, I have a file in the root directory called script_with_args.py as follows:

import argparse

def parse_args():
    parser = argparse.ArgumentParser(description="description")

    parser.add_argument("--a", type=int, default=3)
    parser.add_argument("--b", type=int, default=5)

    return parser.parse_args()

我在根目录中还有一个名为 tests 的文件夹,其中包含一个名为 test_file.py 的测试文件:

I also have a folder called tests in the root directory, containing a test-file called test_file.py:

import script_with_args

def test_script_func():
    args = script_with_args.parse_args()
    assert args.a == 3

如果我从命令行调用 python -m pytest,测试通过.如果我使用 python -m pytest tests 从命令行指定测试目录,则会返回以下错误:

If I call python -m pytest from the command line, the test passes fine. If I specify the test directory from the command line with python -m pytest tests, the following error is returned:

============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
rootdir: C:\Users\Jake\CBAS\pytest-tests, inifile:
plugins: remotedata-0.2.1, openfiles-0.3.0, doctestplus-0.1.3, arraydiff-0.2
collected 1 item

tests\test_file.py F                                                     [100%]

================================== FAILURES ===================================
______________________________ test_script_func _______________________________

    def test_script_func():
        # a = 1
        # b = 2
>       args = script_with_args.parse_args()

tests\test_file.py:13:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
script_with_args.py:9: in parse_args
    return parser.parse_args()
..\..\Anaconda3\lib\argparse.py:1733: in parse_args
    self.error(msg % ' '.join(argv))
..\..\Anaconda3\lib\argparse.py:2389: in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = ArgumentParser(prog='pytest.py', usage=None, description='description', f
ormatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_h
elp=True)
status = 2, message = 'pytest.py: error: unrecognized arguments: tests\n'

    def exit(self, status=0, message=None):
        if message:
            self._print_message(message, _sys.stderr)
>       _sys.exit(status)
E       SystemExit: 2

..\..\Anaconda3\lib\argparse.py:2376: SystemExit
---------------------------- Captured stderr call -----------------------------
usage: pytest.py [-h] [--a A] [--b B]
pytest.py: error: unrecognized arguments: tests
========================== 1 failed in 0.19 seconds ===========================

我的问题是,如何在不干扰 argparse 的命令行选项的情况下为 pytest 指定测试文件目录?

My question is, how do I specify the test file directory for pytest, without interfering with the command line options for argparse?

推荐答案

parse_args() 不带参数读取 sys.argv[1:] 列表.这将包括测试"字符串.

parse_args() without argument reads the sys.argv[1:] list. That will include the 'tests' string.

pytests 还使用带有自己的解析器的 sys.argv[1:].

pytests also uses that sys.argv[1:] with its own parser.

使您的解析器可测试的一种方法是提供一个可选的argv:

One way to make your parser testable is provide an optional argv:

def parse_args(argv=None):
    parser = argparse.ArgumentParser(description="description")

    parser.add_argument("--a", type=int, default=3)
    parser.add_argument("--b", type=int, default=5)

    return parser.parse_args(argv)

然后你可以用:

parse_args(['-a', '4'])

并与

parse_args()

更改sys.argv 也是一个好方法.但是,如果您打算将解析器放入这样的函数中,您不妨为它提供这种额外的灵活性.

Changing the sys.argv is also good way. But if you are going to the work of putting the parser in a function like this, you might as well give it this added flexibility.

这篇关于如何在使用 argparse 的文件上使用指定的测试目录运行 pytest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆