【问题标题】:How to write mock for file download for unit tests如何为单元测试的文件下载编写模拟
【发布时间】:2020-11-03 09:29:21
【问题描述】:

我使用 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 进行测试?

我知道requests_mock 的文档涵盖https://requests-mock.readthedocs.io/en/latest/response.html#registering-responses 的以下内容

要指定响应的正文,有许多选项取决于您希望返回的格式。

  • json:将转换为 JSON 字符串的 python 对象。
  • 文本:Unicode 字符串。这通常是您希望用于常规文本内容的内容。
  • 内容:一个字节串。这应该用于在响应中包含二进制数据。
  • body:包含 .read() 函数的文件类对象。
  • raw:要返回的预填充 urllib3.response.HTTPResponse。
  • exc:将引发异常而不是返回响应。

是正文还是内容?又该如何写呢?

大多数端点都给我 json,但我有一个下载 .xlsx 文件的特殊用例,所以我想编写一个测试用例来使用它。

【问题讨论】:

    标签: python python-requests mocking


    【解决方案1】:

    简答:选择身体

    长答案:

    with requests_mock.mock() as m:
        current_folder = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(
            current_folder, filename
        )
        with open(path, "rb") as the_file:
            m.get(url_to_mock, body=the_file)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多