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 应用程序进行单元测试
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
