我可以在运行时传递命令行参数
python <filename>.py arg1
Run Code Online (Sandbox Code Playgroud)
但是当我尝试传递运行 pytest 的命令行参数时,它失败并给出如下错误。你能给些建议么。
pytest <filename>.py arg1
ERROR: file not found: arg1
Run Code Online (Sandbox Code Playgroud)
编辑:
例如,我正在考虑以这种方式使用它,假设我已经传递了一个参数并且正在通过 sys.argv 读取它:
import sys
arg = sys.argv[3]
def f():
return 3
def test_function():
assert f() == arg
Run Code Online (Sandbox Code Playgroud)
您的pytest <filename>.py arg1
命令试图在两个模块上调用 pytest<filename>.py
和arg1
,但是没有模块 arg1。
如果您想在运行 pytest 之前传递一些参数,请在提取变量后从 python 脚本运行 pytest。
正如其他人所建议的,尽管您可能希望以其他方式参数化您的测试,请尝试:参数化 pytest。
# run.py
import pytest
import sys
def main():
# extract your arg here
print('Extracted arg is ==> %s' % sys.argv[2])
pytest.main([sys.argv[1]])
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
调用这个使用 python run.py filename.py arg1
这是我刚刚通过阅读参数化 pytest 文档和黑客攻击一段时间而编写的方法......我不知道它的整体稳定性或好坏,因为我刚刚让它工作。不过,我确实检查了 HTML 覆盖率生成是否可以使用此方法。
tests\conftest.py
# this is just so we can pass --server and --port from the pytest command-line
def pytest_addoption(parser):
''' attaches optional cmd-line args to the pytest machinery '''
parser.addoption("--server", action="append", default=[], help="real server hostname/IP")
parser.addoption("--port", action="append", default=[], help="real server port number")
Run Code Online (Sandbox Code Playgroud)
pytest_generate_tests
特殊函数
tests\test_junk.py
def pytest_generate_tests(metafunc):
''' just to attach the cmd-line args to a test-class that needs them '''
server_from_cmd_line = metafunc.config.getoption("server")
port_from_cmd_line = metafunc.config.getoption("port")
print('command line passed for --server ({})'.format(server_from_cmd_line))
print('command line passed for --port ({})'.format(port_from_cmd_line))
# check if this function is in a test-class that needs the cmd-line args
if server_from_cmd_line and port_from_cmd_line and hasattr(metafunc.cls, 'real_server'):
# now set the cmd-line args to the test class
metafunc.cls.real_server = server_from_cmd_line[0]
metafunc.cls.real_port = int(port_from_cmd_line[0])
class TestServerCode(object):
''' test-class that might benefit from optional cmd-line args '''
real_server=None
real_port = None
def test_valid_string(self):
assert self.real_server!=None
assert self.real_port!=None
def test_other(self):
from mypackage import my_server_code
if self.real_server != None:
assert "couldn\'t find host" not in my_server_code.version(self.real_server, self.real_port)
Run Code Online (Sandbox Code Playgroud)
然后运行(例如,使用 HTML 覆盖):
pytest tests\test_junk.py --server="abc" --port=123 --cov-report html --cov=mypackage
归档时间: |
|
查看次数: |
10618 次 |
最近记录: |