gpt4 book ai didi

Python "responses"模拟 - 无法多次调用一个 URL

转载 作者:行者123 更新时间:2023-12-03 08:39:09 26 4
gpt4 key购买 nike

我在测试中使用 python responses 模块来模拟 API 响应。问题是,url 注册后 responses.add() 只能用 requests.get() 调用仅一次,后续调用对于相同的 URL 会引发异常。

import requests
import responses

URL = 'http://localhost/abcd'

# Test method
@responses.activate
def get_url(url):
return requests.get(url)

# Set up URL mock
responses.add(responses.GET, URL, body="A B C D")

现在第一个调用有效:

>>> print(get_url(URL))   # <Response [200]>

但是同样的调用再次失败:

>>> print(get_url(URL))

Traceback (most recent call last):
File "test-responses.py", line 19, in <module>
print(get_url(URL))
File "<string>", line 3, in wrapper
File "test-responses.py", line 10, in get_url
return requests.get(url)
File ".../site-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File ".../site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File ".../site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File ".../site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File ".../site-packages/responses.py", line 674, in unbound_on_send
return self._on_request(adapter, request, *a, **kwargs)
File ".../site-packages/responses.py", line 654, in _on_request
raise response
requests.exceptions.ConnectionError: Connection refused by Responses - the call doesn't match any registered mock.

Request:
- GET http://localhost/abcd

Available matches:

>>>

有没有办法让模拟 URL 永久存在并根据测试需要多次调用它们?

最佳答案

原始代码的问题是 get_url 用装饰器包裹,每次调用 get_url 时都会创建一个新的响应上下文,但是 response.add 注册 url 模拟仅注册一次 - 对于第一个响应上下文。

@response.activate 装饰器旨在用于测试用例。这是使用装饰器的正确方法,它允许向相同的 url 发出请求。

@responses.activate
def test_function():
responses.add(responses.GET, URL, body="A B C D")
print(get_url(URL))
print(get_url(URL))

test_function()

使用 responses.start()/responses.stop() 允许对同一 URL 发出多个请求。


import requests
import responses

URL = 'http://localhost/abcd'

def get_url(url):
return requests.get(url)

# Test method
responses.start()
# Set up URL mock
responses.add(responses.GET, URL, body="A B C D")
print(get_url(URL))
print(get_url(URL))
responses.stop()

对于单元测试,我使用 this混合代码。

顺便说一句,最新responses版本(0.12.0)具有功能assert_calls_count允许检查 url 的请求数量,无一异常(exception)。

assert responses.assert_call_count(URL, 1) is True

关于Python "responses"模拟 - 无法多次调用一个 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63064651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com