我需要测试一个需要使用urllib.urlopen在外部服务器上查询页面的函数(它还使用urllib.urlencode).服务器可能已关闭,页面可能会更改; 我不能依靠它进行测试.
控制urllib.urlopen返回的最佳方法是什么?
After reading this in the python docs, I am catching the HTTPError and URLError exceptions in get_response_from_external_api that the make_request_and_get_response (via urllib's urlopen call) can raise:
foo.main.py
from urllib.request import urlopen
import contextlib
from urllib.error import HTTPError, URLError
def make_request_and_get_response(q):
with contextlib.closing(urlopen(q)) as response:
return response.read()
def get_response_from_external_api(q):
try:
resp = make_request_and_get_response(q)
return resp
except URLError as e:
print('Got a URLError: ', e)
except HTTPError as e:
print('Got a HTTPError: ', e)
if __name__ == "__main__":
query = …Run Code Online (Sandbox Code Playgroud) mocking ×2
pytest ×1
pytest-mock ×1
python ×1
python-3.x ×1
testing ×1
unit-testing ×1
urllib ×1