如何使用Python测试API客户端? [英] How do I test an API Client with Python?

查看:169
本文介绍了如何使用Python测试API客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为流行的API开发客户端库.目前,我对该客户的所有单元测试都针对测试帐户进行了实际的API调用.

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.

这是一个例子:

def test_get_foo_settings(self):
    client = MyCustomClient(token, account)
    results = client.get_foo_settings()

    assert_is(type(results), list)

我想停止对我的测试帐户进行实际的API调用.

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?

此外,我对使用此客户端库进行测试的哲学感到困惑.我对测试实际的API并不感兴趣,但是当涉及不同的因素(例如,所调用的方法,可能的返回结果的排列等)时-我不确定应该测试什么和/或何时可以安全使用做出假设(例如模拟的回应).

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).

在我的这种情况下,如何使用Mock的任何方向和/或示例都将不胜感激.

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.

例如,如果该服务使用HTTP,而您正在使用请求"来联系该服务:

For example, if the service uses HTTP and you're using Requests to contact the service:

class MyClient(…):
    def do_stuff(self):
         result = requests.get(self.service_url + "/stuff")
         return result.json()

我首先会在请求周围写一个小的包装:

I would first write a small wrapper around requests:

class MyClient(…):
    def _do_get(self, suffix):
         return requests.get(self.service_url + "/" + suffix).json()

    def do_stuff(self):
         return self._do_get("stuff")

然后,为了进行测试,我将模拟相关的功能:

Then, for tests, I would mock out the relevant functions:

 class MyClientWithMocks(MyClient):
     def _do_get(self, suffix):
          self.request_log.append(suffix)
          return self.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.

这篇关于如何使用Python测试API客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆