gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:22:15 24 4
gpt4 key购买 nike

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

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

最佳答案

实际上有点奇怪的是,该库有一个关于最终用户单元测试的空白页面,同时以用户友好性和易用性为目标。然而,Dropbox 有一个易于使用的库,不出所料地称为 responses。 .这是它的intro post .它说他们没有雇用httpretty ,同时说明没有失败的原因,并编写了一个具有类似 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 - 对使用 requests 库的 python 应用程序进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9559963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com