相关疑难解决方法(0)

一个mock/stub python模块如何像urllib一样

我需要测试一个需要使用urllib.urlopen在外部服务器上查询页面的函数(它还使用urllib.urlencode).服务器可能已关闭,页面可能会更改; 我不能依靠它进行测试.

控制urllib.urlopen返回的最佳方法是什么?

python testing unit-testing mocking

66
推荐指数
6
解决办法
5万
查看次数

How to mock raise urllib errors

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 urllib pytest python-3.x pytest-mock

6
推荐指数
1
解决办法
162
查看次数