*编辑*
我想返回什么样的外部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,
)
^{pr2}$
我试过用这个代码,但感觉自己像个无头鸡:
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个状态码的信息?在
第一个问题是,要获得
HTTPError
异常,需要告诉requests
用raise_for_status()
引发它:第二个问题是,要模拟它,您只需要模拟请求(设置条件以及避免对API进行实际调用),因为否则您确实希望调用
^{pr2}$some_func()
。毕竟,这是测试它的想法。您可以按照您尝试的方式修补对象,但我建议您安装requests-mock:相关问题 更多 >
编程相关推荐