Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active January 12, 2024 21:45
Show Gist options
  • Save tomschr/d644d924793e0588fb04f1ea74dabbc1 to your computer and use it in GitHub Desktop.
Save tomschr/d644d924793e0588fb04f1ea74dabbc1 to your computer and use it in GitHub Desktop.
Example of mocking os.path.isfile
#!/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