Testing your REST client in Python
When you start to write a client for a REST API in Python at beginning it's easy to test it using a Python interactive session, but at some point you'll have to write tests, at that moment you'll see that it's not easy to test your code against live data from the RESTful web API. You may encounter various problems, for example, you can have network problems when tests run, the web server may be temporarily down or tests become slow due to network latency.
A solution to this problem is to use Mock objects, they simulate the behavior of your real objects in a controlled way,
so in this case a mock object may simulate the behavior of the
urlopen function (from the
urllib2 module) and return something like an HTTP response (a file-like object) without hit the real REST API. The file-like object returned may map a RESTful resource to a file which contains a pre-saved response from the real web server.
To show the idea I wrote a simple REST client for the Github API. Here's what the directory structure looks like
$ tree project project ├── client.py └── tests/ ├── test_client.py └── resources/ └── users/ └── test_user 3 directories, 3 files
$ pip install nose mock
Here's the content of the
import json from urllib2 import urlopen class ClientAPI(object): def request(self, user): url = "https://api.github.com/users/%s" % user response = urlopen(url) raw_data = response.read().decode('utf-8') return json.loads(raw_data)
As you can see, it calls
urlopen, parse the JSON data from the HTTP response and return a Python dictionary.