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()

Django

Passionate Django developer with 10 years of experience on sites and apps for e-commerce, chat, picture sharing, CMS and blogs.

Bike

What else? Trains and yacht are also a great transportation way but don't fit well with cities.

Weed

How can a plant be illegal?