Skip to content

Instantly share code, notes, and snippets.

@BrandonLMorris
Created March 8, 2016 15:02
Show Gist options
  • Save BrandonLMorris/1488c75a97ee1ef2f3ae to your computer and use it in GitHub Desktop.
Save BrandonLMorris/1488c75a97ee1ef2f3ae to your computer and use it in GitHub Desktop.
"""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__':
unittest.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'
else:
return 'There was an error connecting'
class ConnectionTest(unittest.TestCase):
@patch('requests.get')
def test_good_connection(self, mock_response):
mock_respone = MockRespone(ok=True)
assertTrue('success' in connect('myawesomesi.te').lower())
@patch('requests.get')
def test_bad_connection(self, mock_response):
mock_response = MockResponse(ok=False)
assertTrue('error' in connect('notaweso.me').lower())
class MockRepsone(object):
def __init__(self, *args, **kwargs):
self.ok = kwargs.get('ok', True)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment