1

*已编辑*

我想测试如果外部 API 返回 500 状态码会发生什么。

main.py

@app.route("/<a>/<b>", methods=["GET"])
def repo_info(a: str, b: str) -> Union[Response, str]:
    info = some_func(a, b)
    result = create_result_dict(some_func)
    return Response(
        response=json.dumps(result, ensure_ascii=False),
        status=200,
        mimetype="application/json",

@app.errorhandler(500)
def server_error(e):
    logging.exception(f"An error occurred during a request: {e}.")
    return Response(
        response="An internal error occurred. See logs for full stacktrace.",
        status=500,
    )
my_module.py

def some_func(a: str, b: str) -> Dict[str, str]:
    return json.loads(
        (requests.get(f"https://api.github.com/repos/{a}/{b}")).text
    )

我尝试了这段代码,但感觉像无头鸡:

from flask import Response
import pytest
import requests

from unittest.mock import patch
from requests.exceptions import HTTPError

@patch.object(my_module, "some_func")
def test_some_func(mocked):
    mocked.return_value = HTTPError()
    result = my_module.some_func()
    with pytest.raises(HTTPError):
        result == mocked 

也不HTTPError接受参数,我如何传递我想要 500 状态码的信息?

4

1 回答 1

1

第一个问题是,要获得HTTPError异常,您需要通过requests以下方式提出异常raise_for_status()

# my_module.py

import json
import requests
from typing import Dict

def some_func(a: str, b: str) -> Dict[str, str]:
    result = requests.get(f"https://api.github.com/repos/{a}/{b}")
    result.raise_for_status()

    return json.loads(result.text)

第二个问题是,要模拟它,您只想模拟请求(设置条件以及避免对 API 进行实际调用),否则您确实想调用some_func(). 毕竟,这是测试它的想法。您可以按照您尝试的方式修补对象,但我建议您安装requests-mock

# test.py

import pytest
import requests_mock
from requests.exceptions import HTTPError
from my_module import some_func

def test_some_func():
    with requests_mock.mock() as m:
        m.get(requests_mock.ANY, status_code=500, text='some error')

        with pytest.raises(HTTPError):
            # You cannot make any assertion on the result
            # because some_func raises an exception and
            # wouldn't return anything
            some_func(a="a", b="b")
于 2019-10-23T10:12:50.770 回答