Unit testing a python app that uses the requests library(对使用 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)
这篇关于对使用 requests 库的 python 应用程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对使用 requests 库的 python 应用程序进行单元测试
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
