簡體   English   中英

如何在測試中修補用`flask - route`裝飾的方法?

[英]How to patch a method decorated with `flask - route` in testing?

我有一個 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

我想進行測試以確保它有效。 因此,為了模擬發生了未處理的異常,我嘗試使用僅引發異常的 function 模擬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 時,沒有應用模擬。 但我不知道如何解決它。

我找到了解決方案。 它不是最優雅的,但它確實有效。 使用裝飾器修補測試是有效的,因為它在創建 flask 上下文之前應用的補丁:

@patch("[file_link].my_url_method", side_effect=Exception("an error")
def test_exception(client):
    #some code here

注意到這一點,給了我線索,問題依賴於 flask 初始化和 pytest 夾具創建。

但是,這樣做會干擾 flask 上下文的創建,並且在每個模擬方法上應用的裝飾器都沒有正確應用。

因此,我沒有做一個“傳統的模擬”,而是簡單地更新了 function 的 flask 參考,它必須調用請求:

def mocked_function(**args):
    raise Exception(MOCKED_EXCEPTION_MESSAGE)

def test_exception(client):
     client.application.view_functions["main.my_url_method"] = mocked_function

它為每個測試創建的client夾具,因此它不會干擾套件中測試的 rest。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM