Code Vigorous

Dustin J. Mitchell


17 Apr 2015

In writing unit tests for all of the various Python projects I hack on in my personal and professional life, I have found the need on several occasions to create a web server against which my code could make requests during test runs. Sure, in the vast majority of cases this isn’t necessary – it’s easy enough to mock out the Requests library or otherwise isolate your tests from HTTP and sockets But in many cases you want the assurance that your code is interfacing correctly with the external service – a particular header is present, for example. It’s easy to mis-mock something like Requests and allow your test to lie to you.

To scratch this common itch, I wrote a little tool called “webmock”. This tool provides an in-process WSGI server on an ephemeral port.

It really is little. It takes care of cleanly starting and stopping the web server for each test, but otherwise leaves it to you to define the web server, using the WSGI protocol. WSGI is simple enough to implement a server in a few lines of Python, if that’s your bent. If you want something more complex, all of the popular Python frameworks support WSGI, too. You could construct an entire Django app to run your test against, if you were so inclined! (I might recommend Flask instead)