- 我编写单元测试使用pytest一个Python库
- 我需要指定测试文件的目录 ,以避免自动测试文件发现,因为有一个大的子目录结构,包括在名称含“_test”或“TEST_”库许多文件,但不得用于pytest
- 在图书馆使用argparse某些文件指定命令行选项
- 的问题是,指定目录pytest作为命令行参数似乎使用命令行选项argparse干涉
举个例子,我有所谓的根目录下的文件script_with_args.py
如下:
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
:
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
,返回以下错误:
============================= 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 ===========================
我的问题是,我怎么指定pytest测试文件目录,以不符合argparse命令行选项的干扰?