-
-
Save jdvala/ea3dcf9349ba2f82b17dc3296ba2f33a to your computer and use it in GitHub Desktop.
Example of mocking os.path.isfile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Use py.test: | |
# $ py.test test_mock.py | |
from unittest.mock import patch | |
import os.path | |
def my_isfile(filename): | |
"""Test function which calls os.path.isfile | |
""" | |
if os.path.isfile(filename): | |
return "Yes" | |
else: | |
return "Wrong" | |
@patch('os.path.isfile') | |
def test_isfile_with_return_value(mock_isfile): | |
"""Mocking os.path.isfile and using return_value | |
""" | |
mock_isfile.return_value = True | |
assert my_isfile('bla') == 'Yes' | |
@patch('os.path.isfile') | |
def test_isfile_with_side_effects(mock_isfile): | |
"""Mocking os.path.isfile with using side_effect | |
""" | |
def side_effect(filename): | |
if filename == 'foo': | |
return True | |
else: | |
return False | |
mock_isfile.side_effect = side_effect | |
assert my_isfile('foo') == 'Yes' | |
assert my_isfile('bla') == 'Wrong' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment