模拟响应,在Flask和pytes中有500个状态代码

2024-04-25 01:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

*编辑*

我想返回什么样的外部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个状态码的信息?在


Tags: fromimportinfoappreturnresponsedeferror
1条回答
网友
1楼 · 发布于 2024-04-25 01:28:57

第一个问题是,要获得HTTPError异常,需要告诉requestsraise_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

^{pr2}$

相关问题 更多 >