对使用 requests 库的 python 应用程序进行单元测试

问题描述

我正在编写一个使用 Kenneth Reitz 的 requests library 执行 REST 操作的应用程序,我正在努力寻找对这些应用程序进行单元测试的好方法,因为 requests 通过模块级方法提供其方法.

I am writing an application that performs REST operations using Kenneth Reitz's requests library and I'm struggling to find a nice way to unit test these applications, because requests provides its methods via module-level methods.

我想要的是合成双方对话的能力;提供一系列请求断言和响应.

What I want is the ability to synthesize the conversation between the two sides; provide a series of request assertions and responses.


解决方案

实际上有点奇怪的是,这个库有一个关于最终用户单元测试的空白页面,同时目标是用户友好性和易用性.然而,Dropbox 有一个易于使用的库,不出所料地称为 responses.这是它的介绍帖.它说他们没有使用 httpretty,同时声明没有失败的原因,写了一个类似API的库.

It is in fact a little strange that the library has a blank page about end-user unit testing, while targeting user-friendliness and ease of use. There's however an easy-to-use library by Dropbox, unsurprisingly called responses. Here is its intro post. It says they've failed to employ httpretty, while stating no reason of the fail, and written a library with similar API.

import unittest

import requests
import responses


class TestCase(unittest.TestCase):

  @responses.activate  
  def testExample(self):
    responses.add(**{
      'method'         : responses.GET,
      'url'            : 'http://example.com/api/123',
      'body'           : '{"error": "reason"}',
      'status'         : 404,
      'content_type'   : 'application/json',
      'adding_headers' : {'X-Foo': 'Bar'}
    })

    response = requests.get('http://example.com/api/123')

    self.assertEqual({'error': 'reason'}, response.json())
    self.assertEqual(404, response.status_code)

相关文章