How Do I Test An Api Client With Python?
I'm working on a client library for a popular API. Currently, all of my unit tests of said client are making actual API calls against a test account. Here's an example: def test_ge
Solution 1:
I would personally do it by first creating a single interface or function call which your library uses to actually contact the service, then write a custom mock for that during tests.
For example, if the service uses HTTP and you're using Requests to contact the service:
classMyClient(…):defdo_stuff(self):
result = requests.get(self.service_url + "/stuff")
return result.json()
I would first write a small wrapper around requests:
classMyClient(…):def_do_get(self, suffix):
return requests.get(self.service_url + "/" + suffix).json()
defdo_stuff(self):
returnself._do_get("stuff")
Then, for tests, I would mock out the relevant functions:
classMyClientWithMocks(MyClient):def_do_get(self, suffix):
self.request_log.append(suffix)
returnself.send_result
And use it in tests like this:
def test_stuff(self):
client = MyClientWithMocks(send_result="bar")
assert_equal(client.do_stuff(), "bar")
assert_contains(client.request_log, "stuff")
Additionally, it would likely be advantageous to write your tests so that you can run them both against your mock and against the real service, so that if things start failing, you can quickly figure out who's fault it is.
Solution 2:
I'm using HTTmock and I'm pretty happy with it : https://github.com/patrys/httmock
Post a Comment for "How Do I Test An Api Client With Python?"