Skip to content

Instantly share code, notes, and snippets.

@sprytnyk
Created April 11, 2020 15:47
Show Gist options
  • Save sprytnyk/5b9de868606dede42b01695c80c51c76 to your computer and use it in GitHub Desktop.
Save sprytnyk/5b9de868606dede42b01695c80c51c76 to your computer and use it in GitHub Desktop.
How to mock an instance method.
from unittest.mock import patch
from core import utils
# specify what should be patched
patcher = patch('core.utils.PythonFilesLookUp')
# attach the original class to the variable because it will be modified
# when the patcher will start
original = utils.PythonFilesLookUp
# start the patcher and mock the class, this will produce a mock
mock = patcher.start()
# mocks instance.list_python_files() and on invokation returns ['python.py']
mock.return_value.list_python_files.return_value = ['python.py']
print(utils.PythonFilesLookUp)
print(mock)
# the mock should be eaqul to the mocked class by a provided path
assert utils.PythonFilesLookUp == mock
# check if PythonFilesLookUp was mocked properly
pfl = utils.PythonFilesLookUp('.')
assert pfl.list_python_files() == ['python.py']
# stop the patcher and unmock the function
patcher.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment