Stub out with lambda

Lambda functions are a great tool to stub out functions. They turn out to be much more clear and easy than using a stub from a isolation/test-double framework. Lambda in Python are used like this in interaction-based tests:

  2. class MyTests(unittest.TestCase):
  3. def test_find_users():
  4. stub = MyDAO()
  5. stub.get_users = lambda: ['carlos', 'juan']
  6. sut = UserFinder(stub)
  7. self.assertEquals(
  8. sut.get_users_with_name_like('ca'),
  9. ['carlos'])

The method get_users in the class MyDAO is stubbed out as we assign a new function to it. The test gets a much more clear code than using PyMox or other test-doubles framework for stubs.

Moreover Python let us stub out functions from classes that haven't been instantiated yet, which makes it perfect for interception too. The next example is the way I am using the Google App Engine bulkloader to write integration tests:

  2. from appengine_django import InstallAppengineHelperForDjango
  3. InstallAppengineHelperForDjango()
  4. from import bulkloader
  6. def load_data():
  7. args_dict = {'all the values': 'the bulk loader needs',
  8. 'etc': 'etc'}
  9. bulkloader.RequestManager.AuthFunction = lambda x : ('x', 'y')
  10. bulkloader.Run(args_dict)

This way the bulkloader runs avoiding the need to manually type in the username and password. RequestManager is a class and AuthFunction is one of its instance members.

  • Kasper

    How much of an fascinating article, preserve producing significant other

  • laptop repair sydney

    Nice post!