【问题标题】:how to get return value from pytest fixture in a function so I don't need to call this function with additional parameter?如何从函数中的 pytest 夹具获取返回值,因此我不需要使用附加参数调用此函数?
【发布时间】: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参数。这适合您的需求吗?
  • 是的,这实际上很有帮助。今天实施。

标签: python pytest fixtures


【解决方案1】:

嗯,我已经按照 hoefling 的建议做了。

在 conftest.py 中创建了小函数:

def get_env_params():
    env_name = pytest.config.getoption("--env")
    return env_params[env_name]

并在需要时从我的模块函数中调用它。示例函数如下所示:

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

从更多功能中删除了不必要的固定装置,并且能够大量清理我的代码。谢谢!

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多