問題描述
我正在編寫一個使用 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 應用程序進行單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!