This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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