Writing Python unit tests for HTTP Clients

I have a nagios / icinga HTTP monitor based on PyCurl: check_pycurl3.

Writing tests for this is difficult because:

  • It needs to make HTTP requests and get a consistent response (so can’t rely on random internet websites).
  • You cannot mock the HTTP requests as the modules for doing this rely on using more “standard” Python HTTP packages (like urllib or requests).
  • Just spawning Flask or similar won’t work as it goes into its request loop and won’t process any tests.

So with a little StackExchange googling, you can start Flask in a thread (remember to set daemon=True) like below:

flask = threading.Thread(target=lambda: self.app.run(host=self.host,
    port=self.port, debug=False, use_reloader=False),
    daemon=True)
flask.start()

You also need to give it some time to start up before tests commence, I’ve used the hacky approach of a 1 second sleep.

To see how I set up routes & inhibit flask startup messages, check the code!

Leave a Reply

Your email address will not be published. Required fields are marked *