我requests_mock用作库来测试我编写的消耗端点的代码。
这是我的download_file功能
def download_as_file(url: str, auth=(), file_path="", attempts=2):
"""Downloads a URL content into a file (with large file support by streaming)
:param url: URL to download
:param auth: tuple containing credentials to access the url
:param file_path: Local file name to contain the data downloaded
:param attempts: Number of attempts
:return: New file path. Empty string if the download failed
"""
if not file_path:
file_path = os.path.realpath(os.path.basename(url))
logger.info(f"Downloading {url} content to {file_path}")
url_sections = urlparse(url)
if not url_sections.scheme:
logger.debug("The given url is missing a scheme. Adding http scheme")
url = f"https://{url}"
logger.debug(f"New url: {url}")
for attempt in range(1, attempts + 1):
try:
if attempt > 1:
time.sleep(10) # 10 seconds wait time between downloads
with requests.get(url, auth=auth, stream=True) as response:
response.raise_for_status()
with open(file_path, "wb") as out_file:
for chunk in response.iter_content(chunk_size=1024 * 1024): # 1MB chunks
out_file.write(chunk)
logger.info("Download finished successfully")
return (response, file_path)
except Exception as ex:
logger.error(f"Attempt #{attempt} failed with error: {ex}")
return None
我该如何测试requests_mock呢?
我知道https://requests-mock.readthedocs.io/en/latest/response.html#registering-responsesrequests_mock的文档涵盖以下内容
要指定响应的正文,有许多选项取决于您希望返回的格式。
- json:将转换为 JSON 字符串的 python 对象。
- 文本:一个 unicode 字符串。这通常是您希望用于常规文本内容的内容。
- 内容:一个字节串。这应该用于在响应中包含二进制数据。
- body:一个类似文件的对象,包含一个 .read() 函数。
- raw:要返回的预填充 urllib3.response.HTTPResponse。
- exc:将引发而不是返回响应的异常。
是正文还是内容?我该怎么写?
大多数端点都给我 json,但我有这个下载文件的特殊用例.xlsx,所以我想编写一个测试用例来使用它。