pytest fixture 无法正常处理请求 input/output

pytest fixture not working properly with requests input/output

我正在测试我构建的网络抓取工具是否仍然 returns 来自网站最新 HTML 结构的正确数据。这需要发出出站 HTTP 请求(我不想模拟它),并抓取响应。

当我固定化抓取的 HTML 数据(转换为 JSON),并尝试访问它时,pytest 抛出一个错误说

AttributeError: 'TestGoogleSearch' 对象没有属性 'keys' 当我尝试访问来自夹具的响应时。有:

obj = 目标 = {'google_query_url': 'https://www.google.com/search?q=GUSTAV%27S+BARGARTEN+97303+google+maps&oq=%7B%27q%27%3A+%22GUSTAV%27S+BARGARTEN+97303+google+maps%22%7D&sourceid=chrome&ie=UTF-8', ...}

代码如下:

url_1 = 'https://www.google.com/search?q=GUSTAV%27S+BARGARTEN+97303+google+maps&oq=%7B%27q%27%3A+%22GUSTAV%27S+BARGARTEN+97303+google+maps%22%7D&sourceid=chrome&ie=UTF-8'

google_search_json = make_google_search_request(url_1)

url_1_target = {
    'google_query_url': 'https://www.google.com/search?q=GUSTAV%27S+BARGARTEN+97303+google+maps&oq=%7B%27q%27%3A+%22GUSTAV%27S+BARGARTEN+97303+google+maps%22%7D&sourceid=chrome&ie=UTF-8'
     # ...
}

@pytest.fixture
def obj():
    yield google_search_json['google_search_results']


@pytest.fixture
def target():
    yield url_1_target


class TestGoogleSearch:

    def test_keys(obj, target):
        assert sorted(obj.keys()) == sorted(target.keys())

    # ...other tests


test_keys 方法中的 obj 参数是 TestGoogleSearch 的实例,又名 self。尝试添加 self::

def test_keys(self, obj, target):
    assert sorted(obj.keys()) == sorted(target.keys())

或者,只需缩进方法并删除 class。