[英]Pytest: How to access command line arguments outside of a test
I would like to access command line arguments passed to pytest from within a non-test class.我想访问从非测试类中传递给 pytest 的命令行参数。
I have added the following to my conftest.py file我已将以下内容添加到我的 conftest.py 文件中
def pytest_addoption(parser): # pragma: no cover
"""Pytest hook to add custom command line option(s)."""
group = parser.getgroup("Test", "My test option")
group.addoption(
"--stack",
help="stack", metavar="stack", dest='stack', default=None)
But I can not work out how to access the value passed on the command line.但是我不知道如何访问在命令行上传递的值。 I have found code on how to access it from a fixture, but I would like to access it from a method or class that is not part of the test case.
我找到了关于如何从夹具访问它的代码,但我想从不属于测试用例的方法或类访问它。
You can access the parameters with sys.argv
.您可以使用
sys.argv
访问参数。 It will return a list of all the arguemnts you sent wrote when you called using the command line.当您使用命令行调用时,它将返回您发送的所有参数的列表。
For example例如
def pytest_addoption(parser): # pragma: no cover
"""Pytest hook to add custom command line option(s)."""
params = sys.argv[1:]
group = parser.getgroup("Test", "My test option")
group.addoption(
"--stack",
help="stack", metavar="stack", dest='stack', default=None)
Yes you could add one more pytest hook pytest_configure
to your conftest.py as follows:是的,您可以在
pytest_configure
再添加一个 pytest 钩子pytest_configure
,如下所示:
stack = None
def pytest_configure(config):
global stack
stack = config.getoption('--stack')
Now your argument stack is available at global level.现在您的参数堆栈在全局级别可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.