Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a function within a Python Flask Blueprint

I have a Python Flask Blueprint called api, and within it, it has a file called utils that has a function I am trying to Mock. The path to that utils file is app/api/utils.py, and the function I'm trying to mock is is_file_writeable().

I am running a test for a route in the Blueprint located at app/api/configs.py. Within configs.py, I import the function as so:

from app.api.utils import is_file_writeable

I have tried the following patch decorators:

@patch('app.api.configs.is_file_writeable', return_value=False)

and

@patch('app.api.utils.is_file_writeable', return_value=False)

Both return the following errors respectively:

AttributeError: 'Blueprint' object has no attribute 'configs'

and

AttributeError: 'Blueprint' object has no attribute 'utils'

Any ideas as to why I am getting an import error?

like image 746
Cosmo-Kramer Avatar asked Nov 09 '22 19:11

Cosmo-Kramer


1 Answers

When I ran into this problem it was because api was a blueprint. Instead of looking for the configs.py under the folder api the mocker was looking for something called utils in the blueprint api.

To get around this I imported the py file and patched the object directly:

from app.api import utils

@patch.object(utils, 'is_file_writeable', lambda x: False)
like image 64
Daniel Treiber Avatar answered Nov 14 '22 22:11

Daniel Treiber