Issue
Suppose we have the following Flask view function to test. Specifically, we want to mock create_foo()
as it writes to the filesystem.
# proj_root/some_project/views.py
from some_project import APP
from some_project.libraries.foo import create_foo
@APP.route('/run', methods=['POST']
def run():
bar = create_foo()
return 'Running'
Now we want to write a unit test for run()
with the call to create_foo()
mocked to avoid creating unnecessary files.
# proj_root/tests/test_views.py
from some_project import some_project
@pytest.fixture
def client():
some_project.APP.config['TESTING'] = True
with some_project.APP.test_client() as client:
yield client
def test_run(client, monkeypatch):
monkeypatch.setattr('some_project.libraries.foo.create_foo', lambda: None)
response = client.post('/run')
assert b'Running' in response.data
It seems that this approach should work even with the named create_foo
import. The tests all pass, however the original code of create_foo
is clearly being executed as a new file in the filesystem is created each time the test suite is run. What am I missing? I suspect it has something to do with the named imports based on some related questions but I'm not sure.
Solution
The correct monkeypatch is:
monkeypatch.setattr('some_project.views.create_foo', lambda: None)
The reason for this is pretty well explained here.
Answered By - Alex Waibel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.