Skip to content

Instantly share code, notes, and snippets.

Created March 8, 2016 15:02
What would you like to do?
"""A simple example of using unittest.mock to patch a function in a test"""
import unittest
from unittest.mock import patch
def f(x):
return 2**x
def g(y):
retrun f(y % 15)
class SimpleTest(unittest.TestCase):
@patch('__main__.f') # Only works if running directly; __main__ should be package name
def test_f_and_g(self, mock_f):
mock_f.return_value = 4 # When f() runs during the test, it will always return 4
self.assertEqual(4, g(50))
if __name__ == '__main__':
"""A less trivial example of using patching for HTTP requests"""
import unittest, requests
from unittest.mock import patch
def connect(url):
response = requests.get(url)
if response.ok:
return 'Connection successful'
return 'There was an error connecting'
class ConnectionTest(unittest.TestCase):
def test_good_connection(self, mock_response):
mock_respone = MockRespone(ok=True)
assertTrue('success' in connect('myawesomesi.te').lower())
def test_bad_connection(self, mock_response):
mock_response = MockResponse(ok=False)
assertTrue('error' in connect('').lower())
class MockRepsone(object):
def __init__(self, *args, **kwargs):
self.ok = kwargs.get('ok', True)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment