Created
December 5, 2012 19:17
-
-
Save dnozay/4218642 to your computer and use it in GitHub Desktop.
Unit testing code using 'requests' with the 'fudge' library.
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
# this is the example code with the what we need to test. | |
import requests | |
def function_under_test(): | |
'''return True if www.example.com is accessible''' | |
alive = False | |
try: | |
response = requests.get('http://www.example.com') | |
response.raise_for_status() | |
alive = True | |
finally: | |
return alive |
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
# this is all the test code | |
# fudge docs: http://farmdev.com/projects/fudge/ | |
# from example import function_under_test | |
try: | |
# python < 2.7 | |
import unittest2 as unittest | |
except ImportError: | |
import unittest | |
import requests | |
import fudge | |
class HttpRequestsTests(unittest.TestCase): | |
@fudge.patch('requests.get') | |
def test_website_up(self, fake_get): | |
# pre-can a successful response | |
(fake_get.expects_call() | |
.returns_fake() | |
.has_attr(status_code=200, text='ok') | |
.provides('raise_for_status') | |
.returns(None) | |
) | |
# the contract is that it should return True. | |
self.assertTrue(function_under_test()) | |
@fudge.patch('requests.get') | |
def test_website_down(self, fake_get): | |
# pre-can an error as a response | |
(fake_get.expects_call() | |
.returns_fake() | |
.has_attr(status_code=500, text='down') | |
.provides('raise_for_status') | |
.raises(requests.HTTPError('website down.')) | |
) | |
# the contract is that is should return False. | |
self.assertFalse(function_under_test()) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment