Python Django Test Mock Happines
(To my beloved brother Tatico who showed me Python)
In a galaxy...
Recently I needed to test a signal in Django that involved calling a Python sdk that depends on the facebook Open Graph API. To avoid calling the API from my test, because you don't want to test if the API works, I searched and found the "path" to write tests in this case.
Here comes mock to save our lives. This is an extremely simple example on how to write a test:
import unittest from mock import patch # This is the code we want to test def my_function_that_uses_request_get(): import requests r = requests.get('http://alejandrovaras.me/') print r class TestMyScript(unittest.TestCase): # Here we do the magic. We replace the "real" requests.get function, with a Mock object, to avoid using it. @patch('requests.get') def test(self, get): # Normaly here you call the "real" requests.get function but we patched it, so you can run this example without internet access and it's going to work my_function_that_uses_request_get() # Here we test that get was called inside our function instead of checking for the return value we get from the "real" call self.assertTrue(get.called) # We can also check the parameters used to call our function, again, we test what our code does instead of looking the results or side efects get.assert_called_with('http://alejandrovaras.me/') if __name__ == '__main__': unittest.main()
Passionate Django developer with 10 years of experience on web sites and API's.
What else? Yachts are also a great but they don't fit well in cities.
Code is knowled. Knowled should be shared.