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_get_foo_settings(self):
client = MyCustomClient(token, account)
results = client.get_foo_settings()
assert_is(type(results), list)
I’d like to stop making actual API calls against my test account.
How should I tackle this? Should I be using Mock to mock the calls to the client and response?
Also, I’m confused on the philosophy of what to test with this client library. I’m not interested in testing the actual API, but when there are different factors involved like the method being invoked, the permutations of possible return results, etc – I’m not sure what I should test and/or when it is safe to make assumptions (such as a mocked response).
Any direction and/or samples of how to use Mock in my type of scenario would be appreciated.
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:
I would first write a small wrapper around requests:
Then, for tests, I would mock out the relevant functions:
And use it in tests like this:
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.