繁体   English   中英

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

[英]Accessing values from inner function in pytest fixture

我正在尝试从我的 pytest 夹具中的内部 function 访问响应。 我不确定这是 python 问题还是 pytest 构建方式特有的问题。 下面的代码片段是一个愚蠢的例子,但它演示了这个问题。 我遇到了问题: TypeError: 'function' object is not subscriptable 不知道如何解决这个问题,希望得到一些帮助。

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

问题是内部 function 直到yield才被调用,因此您无法在此之前保存结果(并且您无法知道它,因为您不知道 URL 参数)。 您可以做的是在内部 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