Skip to content

Instantly share code, notes, and snippets.

@Sklavit

Sklavit/mock.methods.py

Last active Dec 18, 2018
Embed
What would you like to do?
Mock examples
# @ https://cheat.readthedocs.io/en/latest/python/mock.html
obj.call_count # number of times it was called
obj.called == obj.call_count > 0
obj.call_args_list # a list of (args,kwargs), one for each call
obj.call_args # obj.call_args_list[-1] (args,kwargs from last call)
obj.return_value # set to what it should return
obj.side_effect # set to an exception class or instance that should be raised when its called
obj.assert_called() # doesn't work with autospec=True? just assert obj.called
obj.assert_called_with(*args, **kwargs) # last call was with (*args, **kwargs)
# @ https://medium.com/@yeraydiazdiaz/what-the-mock-cheatsheet-mocking-in-python-6a71db997832
assert m.call_args == mock.call(1, foo='bar')
m.reset_mock()
assert m.call_args is None
# @ https://cheat.readthedocs.io/en/latest/python/mock.html
with mock.patch.object(obj, ‘attrname’) as foo:
...
# To mock an entire class to test interactions with that class use @patch.
# @ https://myadventuresincoding.wordpress.com/2011/02/26/python-python-mock-cheat-sheet/
@patch('my_module.MyClass')
def test_my_method_shouldCallMyClassMethodMyMethod_whenSomeOtherClassMethodIsCalled(self, mock_my_class):
some_other_class = SomeOtherClassThatUsesMyClass()
some_other_class.method_under_test()
self.assertTrue(mock_my_class.called)
# To mock an entire class with @patch and still set the return value of a method in that class, grab the instance of the mock object’s return value and set the method’s return value on the instance. There is a section on the patch page explaining how to do this.
# @ https://myadventuresincoding.wordpress.com/2011/02/26/python-python-mock-cheat-sheet/
@patch('my_module.MyClass')
def test_my_method_shouldReturnTrue_whenSomeOtherClassMethodIsCalledAndAReturnValueIsSet(self, mock_my_class):
mc = mock_my_class.return_value
mc.my_method.return_value = True
some_other_class = SomeOtherClassThatUsesMyClass()
result = some_other_class
def size_of():
with open('text.txt') as f:
contents = f.read()
return len(contents)
with mock.patch('worker.open') as mock_open:
mock_open.return_value.__enter__.return_value = StringIO('testing')
self.assertEqual(size_of(), 7)
@mock.patch.dict('os.environ', {'MY_VAR': 'testing'})
# @ https://medium.com/@yeraydiazdiaz/what-the-mock-cheatsheet-mocking-in-python-6a71db997832
m = mock.Mock()
m.side_effect = RuntimeError('Boom')
try:
m()
except RuntimeError:
assert True
else:
assert False
with mock.patch('medley.photos.tasks.galleryimport.urlopen') as urlopen:
urlopen.side_effect = ValueError("Deliberate exception for testing")
# To mock a method in a class to return a specific value use @patch.object.
# @ https://myadventuresincoding.wordpress.com/2011/02/26/python-python-mock-cheat-sheet/
@patch.object(my_module.MyClass, 'my_method')
def test_my_method_shouldReturnTrue_whenMyMethodReturnsSomeValue(self, mock_my_method):
mock_my_method.return_value=True
some_other_class = SomeOtherClassThatUsesMyClass()
result = some_other_class.method_under_test()
self.assertTrue(result)
# @ https://cheat.readthedocs.io/en/latest/python/mock.html
with mock.patch('medley.photos.models.MedleyPhotoManager.build_from_url') as build_from_url:
build_from_url.return_value = None
# To mock a method in a class with @patch.object but return a different value each time it is called, use side_effect. Side effect allows you to define a custom method and have that method called each time your mock method is called. The value returned from this method will be used as the return value your mock method.
# @ https://myadventuresincoding.wordpress.com/2011/02/26/python-python-mock-cheat-sheet/
@patch.object(my_module.MyClass, 'my_method')
def test_my_method_shouldReturnMultipleValues_whenMyMethodReturnsSomeValue(self, mock_my_method):
list_of_return_values= [True,False,False]
def side_effect():
return list_of_return_values.pop()
mock_my_method.side_effect = side_effect
some_other_class = SomeOtherClassThatUsesMyClass()
self.assertFalse(some_other_class.method_under_test())
self.assertFalse(some_other_class.method_under_test())
self.assertTrue(some_other_class.method_under_test())
m.return_value = 42
assert m() == 42
m.side_effect = ['foo', 'bar', 'baz']
assert m() == 'foo'
assert m() == 'bar'
assert m() == 'baz'
try:
m()
except StopIteration:
assert True
else:
assert False
# @ https://cheat.readthedocs.io/en/latest/python/mock.html
with mock.patch("medley.photos.tasks.galleryimport.cache", new=get_cache('locmem://')):
...
with mock.patch(target='medley.photos.tasks.galleryimport.MAX_IMPORTS', new=2):
...
import mock
from zzz import x_urandom
def simple_urandom(length):
return 'f' * length
@mock.patch('zzz.urandom', side_effect=simple_urandom)
def test_abc_urandom(self, x_urandom_function):
assert x_urandom(5) == 'xfffff'
from os import urandom
def x_urandom(length):
return 'x' + urandom(length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment