【发布时间】:2018-11-15 17:54:25
【问题描述】:
我在 conftest.py 中有以下夹具,它返回一个环境设置字典,如用户、密码等:
@pytest.fixture
def envparams(request):
env = request.config.getoption("--env")
return env_params[env]
然后我有这样的模块:
def request_master_url(envparams):
cje_master_url = envparams['url']+'/'+test_master
cje_user = envparams['user']
cje_pass = envparams['password']
local = testinfra.get_host("ssh://localhost")
results = local.command(
'curl -L -I --user '+cje_user+':'
+ cje_pass+' '+cje_master_url+'| grep HTTP\
|tail -1').stdout
if '200 OK' in results:
return True
else:
return False
以及使用此模块的测试,例如:
def test_cje_high_availability(envparams, env_option, script_loc):
workstation = testinfra.get_host('ssh://'+testinfra_hosts[0])
if not security.request_master_url(envparams):
print(test_master+' - is not available\n')
create_team_master(test_master, envparams, script_loc)
我能否以某种方式从模块函数中删除 envparams 参数,这样我就可以在没有附加参数的情况下调用它? 喜欢:
security.request_master_url(envparams)
我只需要在会话中设置一次这个装置。我尝试使用:
@pytest.mark.usefixtures('envparams')
def request_master_url():
但是,我不知道如何从这个夹具返回值。
【问题讨论】:
-
为什么不用
request_master_url做一个固定装置? -
这是一些解决方案,但我还有更多类似这个的功能,它们也使用 envparams 夹具。我认为在 conftest.py 中创建一个全局参数并将其设置为会话的 envparams 固定装置可能会更好。我只是从我的模块函数中读取它,不需要额外的参数来从测试函数调用。
-
问题是,您不能将
pytest机器应用于正常功能本身。如果request_master_url应该是一个函数并且只在测试中使用,你可以直接在函数中通过pytest.config.getoption('--env')获取env,所以你不需要传递envparams参数。这适合您的需求吗? -
是的,这实际上很有帮助。今天实施。