简体   繁体   English

从 pytest 夹具中的内部 function 访问值

[英]Accessing values from inner function in pytest fixture

I am trying to access the response from an inner function inside my pytest fixture.我正在尝试从我的 pytest 夹具中的内部 function 访问响应。 I'm not sure if this is a python issue or something unique to how pytest is built.我不确定这是 python 问题还是 pytest 构建方式特有的问题。 The snippet below is a dumb example, but it demonstrates the issue.下面的代码片段是一个愚蠢的例子,但它演示了这个问题。 I am getting the issue: TypeError: 'function' object is not subscriptable .我遇到了问题: TypeError: 'function' object is not subscriptable Not sure how to solve this and would like some help please.不知道如何解决这个问题,希望得到一些帮助。

import pytest
import requests


@pytest.fixture
def my_fixture():
    def make_request(url):
        response = requests.get(url)
        return {'code': response.status_code, 'content': response.content}

    response = make_request
    save_for_after_yield = response['content']
    yield response

    # print simulates doing something with the content as part of the clean-up
    print(save_for_after_yield)


def test_making_requests(my_fixture):
    response = my_fixture('http://httpbin.org')
    assert 200 == response

The problem is that the inner function is not called until the yield , so you cannot save the result before that (and you can't know it, as you don't know the URL parameter).问题是内部 function 直到yield才被调用,因此您无法在此之前保存结果(并且您无法知道它,因为您不知道 URL 参数)。 What you can do is saving the variable after it has been set inside the inner function:您可以做的是在内部 function 中设置变量后保存该变量:

@pytest.fixture
def my_fixture():
    def make_request(url):
        nonlocal response_content  # needed to access the variable in the outer function
        response = requests.get(url)
        response_content = response.content
        return {'code': response.status_code, 'content': response.content}

    response_content = None  # will be set when the fixture is used
    yield make_request
    print(response_content)


def test_making_requests(my_fixture):
    response = my_fixture('http://httpbin.org')
    assert 200 == response['code']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM