Skip to content

Instantly share code, notes, and snippets.

@fisher6
Created July 24, 2017 14:18
Show Gist options
  • Save fisher6/7128e061a36545b1e54ed9945a6884d5 to your computer and use it in GitHub Desktop.
Save fisher6/7128e061a36545b1e54ed9945a6884d5 to your computer and use it in GitHub Desktop.
Python mocking example
from mock import Mock, MagicMock
mock = Mock(return_value=1)
mock(1, 5, animal='dog') # returns 1 always
m = MagicMock(side_effect=ValueError)
m(1, 2, 3, 4) # raises valueError
m = Mock()
attrs = {'mocked_method.return_value': 3,
'mocked_method_raises_exception.side_effect': ZeroDivisionError, }
m.configure_mock(**attrs)
m.mocked_method('Whats up function') # returns 3 always
m.mocked_method_raises_exception(True, False, 42) # raises ZeroDivisionError
import requests
m = Mock(spec=requests) # m is now a mocked request object.
# Every Mock object can run any method, even if you didn't configure it's spec
# we can still go m = Mock() and m.get() for example (get is requests' method).
# But when you do spec=requests, m.method_not_in_requests() will throw error
# "Mock object has no attribute '...'"
## Testing functions
# Function to test
def get_data():
response = requests.get('http://httpbin.org/get')
return response.status_code
# Inside the test patch requests.get to return object with status_code 200
with patch.object(requests, 'get') as get_mock:
get_mock.return_value.status_code = 200
assert get_data() == 200 # will call mocked get_data with return value of status_code 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment