【问题标题】:Mocker.patch a function when unit testing a Flask blueprintMocker.patch 单元测试 Flask 蓝图时的函数
【发布时间】:2023-02-12 21:57:06
【问题描述】:

我有一个蓝图文件/views/index.py

from flask import Blueprint, render_template
index = Blueprint('index', __name__)

def auth():
    return "dog"

@index.route('/')
def index_view():
    return render_template(
        'index.html', user=auth())

这是从 /main.py 初始化的:

from flask import Flask
from views.index import index
from views.login import login

app = Flask(__name__)
app.register_blueprint(index)

我如何在我的蓝图中模拟 auth() 函数以返回像“cat”这样的覆盖?

【问题讨论】:

    标签: python unit-testing flask pytest pytest-mock


    【解决方案1】:

    使用以下/tests/test_root.py

    import sys
    from pathlib import Path
    sys.path.append(str(Path('.').absolute().parent))
    
    from main import app
    
    def test_index_route(mocker):
        mocker.patch("views.index.auth", return_value="cat")
        response = app.test_client().get('/')
        assert response.status_code == 200
        assert b"cat" in response.data
        assert not b"dog" in response.data
    

    导航到 /tests/ 目录,运行 pytest 并且此测试将通过。

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多