【问题标题】:Accessing values from inner function in pytest fixture从 pytest 夹具中的内部函数访问值
【发布时间】:2020-08-01 20:51:21
【问题描述】:

我正在尝试从我的 pytest 夹具中的内部函数访问响应。我不确定这是 python 问题还是 pytest 构建方式独有的问题。下面的 sn-p 是一个愚蠢的例子,但它演示了这个问题。我遇到了问题: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

【问题讨论】:

    标签: python python-3.x unit-testing pytest python-unittest


    【解决方案1】:

    问题是内部函数直到yield 才被调用,所以你不能在此之前保存结果(你也不知道它,因为你不知道 URL 参数)。您可以做的是在内部函数中设置变量后保存它:

    @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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多