【发布时间】:2020-06-26 11:34:56
【问题描述】:
我有一个 python 应用程序,它使用 Flask 来公开一些端点。另外,我使用fixture 来捕获未处理的异常并返回自定义响应。这是一个示例代码:
from flask import make_response, Blueprint
root = Blueprint("main", __name__)
@root.errorhandler(Exception)
def custom_error_handler(error):
#do other things here
return make_response({"status": "failure", "error": str(error)}), 500
@root.route("/my_url", methods=["POST"])
def my_url_method():
#do other thins
return make_response(...), 200
我想进行测试以确保它有效。因此,为了模拟发生了未处理的异常,我尝试使用一个简单地引发异常的函数来模拟 my_url method:
from unittest.mock import patch
from flask import Flask
@pytest.fixture
def client(monkeypatch):
app = Flask(__name__, instance_relative_config=True)
app.register_blueprint(root)
app.config["TESTING"] = True
return app.test_client()
def test_exception(client):
with patch("[file_link].my_url_method", side_effect=Exception("an error")):
response = client.post("my_url")
assert response.status_code == 500
但是断言失败。该方法正确执行,没有引发任何异常,返回200作为状态码。
我认为问题在于调用方法 throw flask 时未应用 mock。但我不知道如何解决它。
【问题讨论】:
标签: python flask mocking pytest