Last active
January 12, 2024 21:45
-
-
Save tomschr/d644d924793e0588fb04f1ea74dabbc1 to your computer and use it in GitHub Desktop.
Example of mocking os.path.isfile
This file contains 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: | |
# $ pytest 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