I'm trying to use the unittest.mock
library to patch a function inside a Flask Blueprint. Specifically, I'm trying to patch the os
module inside the blueprint. Simplified code (cannot provide all/actual code):
test_route.py (the test I am trying to run)
import unittest
from unittest import mock
from server.index import create_app as Server
class TestRoute(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = Server()
cls.server.config['TESTING'] = True
cls.client = cls.server.test_client()
#
# more code...
#
@mock.patch('server.routes.blueprint.os')
def test_route(self, mockOS):
mockOS.listdir.return_value = ['/mockedvalue']
res = client.post('/some/url')
#
# more code...
#
server/index.py (the module to create the Flask server)
from flask import Flask
from routes.blueprint import bp
def create_app():
app = Flask(__name__)
app.register_blueprint(bp)
#
# more code...
#
server/routes/blueprint.py (the Blueprint logic used by the Flask server)
import os
from flask import Flask, Blueprint
bp = Blueprint('bp', __name__)
@bp.route('/some/url')
def run():
#
# code...
#
dirs = os.listdir('/some/path')
#
# more code...
#
When I run this, os.listdir() is not getting patched. I get the actual contents of '/some/path' when what I really want is the mocked value:
Actual : ['/something1', '/some/other/thing', ...]
Expected : ['/mockedvalue']
I've read https://docs.python.org/3/library/unittest.mock.html#where-to-patch , but maybe I am still making a mistake. It seems appropriate to patch at the blueprint module, but if this is incorrect, any guidance or corrections would be appreciated.