对使用请求库的python应用程序进行单元测试 [英] Unit testing a python app that uses the requests library

查看:61
本文介绍了对使用请求库的python应用程序进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

这篇关于对使用请求库的python应用程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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