Mocker.patch a function when unit testing a Flask blueprint

149 views Asked by At

I've got a blueprint file /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())

This is initialized fine from /main.py:

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

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

How can I mock the auth() function in my blueprint to return an override like "cat"?

1

There are 1 answers

0
penitent_tangent On

Use the following /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

Navigate into the /tests/ dir, run pytest and this test will pass.