paint-brush
3 new ways to mock out APIs in Pythonby@anthonypjshaw
8,758 reads
8,758 reads

3 new ways to mock out APIs in Python

by Anthony ShawJanuary 27th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In my <a href="https://medium.com/@anthonypjshaw/python-requests-deep-dive-a0a5c5c1e093#.f17oeryy0" target="_blank">last blog on the topic</a>, I talked about how <code class="markup--code markup--p-code">requests_mock</code> can be used to mock out quick and simple responses to REST APIs.

Company Mentioned

Mention Thumbnail
featured image - 3 new ways to mock out APIs in Python
Anthony Shaw HackerNoon profile picture

Getting your tests right can be crucial

In my last blog on the topic, I talked about how requests_mock can be used to mock out quick and simple responses to REST APIs.

  • Returning large responses, like CSV reports
  • Returning binary files, like images
  • Dynamically responding via callbacks

What I’ve put together is a new (beta) package for creating a simple bridge between your unit tests and the Python requests adapter API.

The package is called requests-staticmock and you can find the code at GitHub and PyPi.

It provides 3 new ways to mock out API responses.

Pattern 1 : Mocking out an API to a set of files

Consider this scenario, you want to test a class that you developed, which

In it’s simplest form, you can use a context manager to inject a static asset adapter into your requests session.

If the method does not exist, it will generate a 404 response.

Here is a more detailed example of how this could be used.

Pattern 2 : Mocking out a specific URL, but using a live instance also

In this example, you might want to mock out a particular API, but keep access to another. The Adapter injector (and the context manager pattern) support specific URLs within a session, keeping the default HTTP behaviour for URLs that do not match the pattern.

Pattern 3 : Having a test class generate the responses

This pattern gives you access to creating a shared class that has callbacks for all of the URLs you might want to test

If the method does not exist, it will generate a 404 response.

Summary

The goal of this library was to make it dead-simple to mock out HTTP APIs for a given API client in Python.

I’m looking for feedback as this is an early beta, please raise issues on GitHub with any pointers or feature ideas.