我正在使用 Pytest 并配置我的
conftest.py
来接受一些参数:
def pytest_addoption(parser):
parser.addoption(
'--vm-name',
required=True,
metavar='vm-name',
help='Name of the virtual machine the tests executes on',
type=str,
dest='vm-name'
)
parser.addoption(
'--vm-ip',
required=True,
metavar='vm-ip',
help='IP address of the virtual machine the tests executes on',
type=str,
dest='vm-ip'
)
parser.addoption(
'--credentials',
required=True,
metavar='file',
help='Path of the JSON file containing credentials',
type=load_credentials,
dest='credentials'
)
load_credentials
是一个接受 JSON 字符串并使用给定字符串初始化 JSON 数据类的函数。
我正在使用
Pyvmomi
在虚拟机中执行以下命令:
/bin/bash -c "echo user_password | sudo -S /usr/bin/python3 -m pytest /usr/local/auto/tests/shared/test_shared.py --vm-name my_vm --vm-ip 10.10.10.10 --credentials \'{\\"vcenter\\": {\\"username\\": \\"username\\", \\"password\\": \\"password\\"}, \\"vm\\": {\\"username\\": \\"Administrator\\", \\"password\\": \\"password\\"}}\' -rA --capture=tee-sys --show-capture=no --disable-pytest-warnings --junit-xml=/tmp/test_shared.xml"
但是,我不确定为什么它不起作用。我得到:
zsh: event not found: \\
。我认为这是因为 JSON 字符串没有正确转义或其他原因。这就是我在代码中传递它的方式:
creds = Credentials(...)
creds_escaped = creds.replace('"','\\"')
f'-m pytest {test_path} --vm-name {vm.name} --vm-ip {vm.ip_address} --credentials \'{creds_escaped}\' {pytest_flags}'
我有一种感觉,
creds
是一个JSON对象,如果是这样的话,并且如果你使用subprocess
来启动pytest。这是一个简化的解决方案:
import json
import subprocess
cred = {
"vcenter": {"username": "username", "password": "password"},
"vm": {"username": "Administrator", "password": "password"},
}
cmd = [
"python3",
"script.py", # An example, in place of pytest
"--credentials",
json.dumps(cred),
]
print("cmd:", cmd)
subprocess.run(cmd)
请注意,我使用
json.dumps()
进行引用。