Here on the AppNexus Optimization team, we write code to optimize algorithms for our customers. We want to write good great code, so of course we test our code. We write and unit test our code in Python and run continuous integration using Jenkins. We have one Jenkins instance up that covers many of the different engineering teams. Our check-ins automatically trigger tests to run in Jenkins, and if we break pre-existing unit tests, we should know right away.
The actual test command called by Jenkins makes use of the Python nose module. Nose picks up any appropriate test looking modules, classes, and functions that correspond to the running code while looking at the directory structure. It is mostly smart and very useful. We can also import nose into individual test modules and just run the files. This is by far the preferred use for us because it makes debugging a whole lot easier.
Whenever we write tests in Python, we have choices on what to use for mocks and stubs. For development, we usually use the mock module. Mocking allows for “fake” objects upon which we can impose certain behaviors. This allows us to separate the function we are testing from the functionality called by the function we are testing.
Our team also runs a few internal websites using Django. In this entry I will go over the basics of Python test-writing using the nose and mock classes. Check back later this week for my post on how we run our tests using the Django framework.
Before I dive in to how to test your code, let’s quickly discuss nose, a module we use for Python testing. Nose is a pretty clever test module, and it will look for all the test like files when you run it and call the matching functions in the code base, calculate their coverage, etc. You can install it using pip: https://nose.readthedocs.org/en/latest/
Run the following (from a root directory):