[英]how to get return value from pytest fixture in a function so I don't need to call this function with additional parameter?
I have the following fixture in conftest.py that returns an environment settings dictionary like user, password etc: 我在conftest.py中具有以下固定装置,该固定装置返回环境设置字典,例如用户,密码等:
@pytest.fixture
def envparams(request):
env = request.config.getoption("--env")
return env_params[env]
Then I have module like: 然后我有像这样的模块:
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
and a test that uses this module like: 以及使用此模块的测试,例如:
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)
Can I get rid of the envparams parameter from module function somehow so I can call it without additional parameter? 我可以以某种方式摆脱模块函数中的envparams参数,以便在没有附加参数的情况下调用它吗? like:
喜欢:
security.request_master_url(envparams)
I only need to setup this fixture once in a session. 我只需要在一次会话中设置一次这个灯具。 I tried to use:
我尝试使用:
@pytest.mark.usefixtures('envparams')
def request_master_url():
But, I am not sure how to get values returned from this fixture. 但是,我不确定如何获取此固定装置返回的值。
Well, I've done as hoefling suggested. 好吧,我已经按照建议的方式做了。
Created small function in conftest.py: 在conftest.py中创建了一个小函数:
def get_env_params():
env_name = pytest.config.getoption("--env")
return env_params[env_name]
and call it from my module functions where needed. 并在需要时从我的模块函数中调用它。 Example function looks like below:
示例函数如下所示:
def request_master_url(team_id):
envparams = get_env_params()
cje_master_url = envparams['url']+'/'+team_id
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
removed unnecessary fixture from many more functions and was able to clean my code a lot. 从许多其他功能中删除了不必要的固定装置,并能够大量清理我的代码。 Thanks!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.