我正在尝试使用pytest的json
将一些命令行参数从argparse.ArgumentParser
实例移植到等效的pytest conftest.py
文件中
查看pytest帮助功能,我发现有12个使用的单字符短选项,即pytest_addoption
k, m, x, c, s, v, q, r, l, h, p, o
但是,如果我尝试在该设置之外定义选项,则会出现以下异常
MacBook-Pro:~ user$ pytest --help | grep " -[a-z]"
-k EXPRESSION only run tests which match the given substring
-k 'test_method or test_other' matches all test
'test_method' or 'test_other', while -k 'not
-m MARKEXPR only run tests matching given mark expression.
example: -m 'mark1 and not mark2'.
-x, --exitfirst exit instantly on first error or failed test.
-c file load configuration from `file` instead of trying to
-s shortcut for --capture=no.
-v, --verbose increase verbosity.
-q, --quiet decrease verbosity.
-r chars show extra test summary info as specified by chars
-l, --showlocals show locals in tracebacks (disabled by default).
-h, --help show help message and configuration info
-p name early-load given plugin (multi-allowed). To avoid
-o [OVERRIDE_INI [OVERRIDE_INI ...]], --override-ini=[OVERRIDE_INI [OVERRIDE_INI ...]]
无论我选择哪个角色,这似乎都是事实,这让我认为这只是行为受限期。
问题:pytest是否限制短选项的所有使用?
我有点困惑,因为当您查看相关的pytest source
def pytest_addoption(parser):
parser.addoption('-b', '--build_special' )
File "/Library/Python/2.7/site-packages/_pytest/config/argparsing.py", line 72, in addoption
self._anonymous.addoption(*opts, **attrs)
File "/Library/Python/2.7/site-packages/_pytest/config/argparsing.py", line 305, in addoption
self._addoption_instance(option, shortupper=False)
File "/Library/Python/2.7/site-packages/_pytest/config/argparsing.py", line 315, in _addoption_instance
raise ValueError("lowercase shortoptions reserved")
ValueError: lowercase shortoptions reserved
似乎建议我可以使用与argparse的add_option完全相同的语法,有趣的是在argparse documentation中提到了
将所有
def addoption(self, *opts, **attrs): """ register a command line option. :opts: option names, can be short or long options. :attrs: same attributes which the ``add_option()`` function of the `argparse library <http://docs.python.org/2/library/argparse.html>`_ accepts. After command line parsing options are available on the pytest config object via ``config.option.NAME`` where ``NAME`` is usually set by passing a ``dest`` attribute, for example ``addoption("--long", dest="NAME", ...)``. """ self._anonymous.addoption(*opts, **attrs)
呼叫替换为optparse.OptionParser.add_option()
个呼叫。
和add_argument documentation明确列出了允许的单个标志选项:
ArgumentParser.add_argument()
方法必须知道是否有可选参数, 如add_argument()
或-f
,或位置参数,如列表 文件名。传递给add_argument()的第一个参数 因此,必须是一系列标志或简单的参数名称。 例如,可以创建一个可选参数,例如:
--foo
答案 0 :(得分:1)
从pytest源代码...
def _addoption_instance(self, option: "Argument", shortupper: bool = False) -> None:
if not shortupper:
for opt in option._short_opts:
if opt[0] == "-" and opt[1].islower():
raise ValueError("lowercase shortoptions reserved")
if self.parser:
self.parser.processoption(option)
self.options.append(option)
是的,它们限制所有小写的短选项