How to Mock Logging in Python

As you become familiar with software testing and unit testing it can be necessary to assure yourself that information will be logged when your software platform raises an exception or behaves unexpectedly.

In other words, you've developed a new feature and you want to make sure that certain calls to Python's logging module are performed in certain cirumstances.

That's where the mock module comes in: it allows us to mock the Python logging module and assert that certain calls are made. If you're using Python 3.3 (or higher) than you can import from the unittest.mock (documentation) module rather than installing mock from PyPI.

Example of mocking in unit tests

Let's say our code looks like this:

import logging

def check_value(data_dict, value):
    try:
        return data_dict[value] > 10
    except KeyError:
        logging.warn("Data does not contain '%s'", value)
    return False

What we wish to test is that logging.warn is called when the KeyError is raised. So in our unit test we call check_value with parameters in such a way that the KeyError is indeed raised. For example:

import unittest
from my_module import check_value

class MyUnitTest(unittest.TestCase):

    def test_check_value_logs_warning(self):
        check_value({}, 'key')

The idea behind mocking is as follows: instead of calling the real warn function of the logging module we call a fake mocked version and that allows us to keep track of how many times the function is called (if at all).

We can do that using the patch function of the mock library: this specifies what we wish to mock and what the name of the mocked object should be.

We can now update our test by writing:

import unittest
from mock import patch
from my_module import check_value

class MyUnitTest(unittest.TestCase):

    @patch('my_module.logging')
    def test_check_value_logs_warning(self, mock_logging):
        check_value({}, 'key')
        self.assertTrue(mock_logging.warn.called)

if __name__ == '__main__':
    unittest.main()

This unit test passes as the assertion is indeed true. If you modify the code in a way that it no longer logs a warning then you'll find that the assertion in the unit test fails.

Participating in the International Four Days Marches Nijmegen

After not making the cut last year I was quite pleased to receive an email today that I'm among the debutants allowed to participate in the 97th edition of the International Four Days Marches Nijmegen - more colloquially known as the "Vierdaagse".

Given my age and my gender I'll be walking the 50km routes each day which means it sums up nicely to 200km in four days.

I'll have to prepare properly as the longest walk I've done so far on one day is the Tongariro Alpine Crossing in New Zealand which is a little less than 20km. To be fair, that's a different challenge altogether as it is across vulcanic terrain with steep climbs, descents and changing weather conditions.

In contrast the Vierdaagse is an event in and around the city of Nijmegen across the typically Dutch flat landscape with a backdrop of little towns and distant green panoramas. The distance and the possibly hot or rainy weather mean it is still not wise to participate without training (although some do try every year).

The event is as popular as ever with over fifty thousand people signing up this year and forty-six thousand allowed to participate. This easily makes it among the biggest events in the Netherlands and also one of the events that you always hear about when growing up.

With about three months to go I'm going to look into some walking routes around London. The distance from east to west in Greater London is about 50km so that gives you an idea of the task ahead.

Photos of London in Spring 2013

Today was one of the first sunny days of spring in London and after several months of cold weather a change was much welcomed. I decided to carry my digital camera with me to take some sunny photos of London's diverse architecture. It doesn't take long to realise that hundreds of years of history have given London a unique mixture of historical and modern buildings.

A stroll through various neighbourhoods and towns in London brings you to busy streets, quiet mews and narrow passageways that are sometimes no more than a pedestrian wide.

Below is a selection of the photos taken today:

Red Place, London by Simeon Visser (simeonvisser)) on 500px.com
Red Place, London by Simeon Visser

Phonebooth in London by Simeon Visser (simeonvisser)) on 500px.com
Phonebooth in London by Simeon Visser

Life and Art in London by Simeon Visser (simeonvisser)) on 500px.com
Life and Art in London by Simeon Visser

On Photography and Travel

About a month ago I uploaded a selection of my better travel photos to 500px.com (see my profile there). It's far from my entire photo collection but I thought it would be nice to put some online rather than letting them collect digital dust on my hard drives.

It's also quite clear that a basic digital camera, some sunshine, decent composition and nice scenery are no longer sufficient to produce a work of art. My uploaded photos are indeed what they are: carefully selected holiday photos but not masterfully edited works of art made with the finest equipment. I don't have a trained eye for this but I do feel the ratio of edited versus unedited photos is skewed towards the former.

My previous camera was the Samsung L370 and my current camera is the somewhat better Coolpix S8200. I have to say I barely know more than the automatic feature of the camera but I'm planning to remedy that in the future.

Fresh New Look

Although it's late March and London hasn't quite shown what spring should look like I thought it would be good to do some spring "cleaning" of my website. That means saying goodbye to my homebuilt combination of PHP and Markdown and saying hello to Nikola, a static site generator written in Python.

As Nikola supports Markdown it was fairly easy to convert my old website to this new setup. I can now focus on writing the content and generate the whole website with a single command. Some new features are the posts archive and the ability to tag posts.

The new theme is still quite Bootstrap-y but at least it's one of the themes (Readable) from Bootswatch rather than the default Bootstrap theme.

I have configured the .htaccess file of the website so old links should still work. If you have come across a link that doesn't work anymore please let me know on Twitter.

Contents © 2014 Simeon Visser