आप requests
विधि नीचे कोड अनुभाग में परिभाषित कर सकते हैं। इसका उपयोग करने के लिए आपको नीचे दिए गए कोड में दिखाए गए get_auth_headers
विधि को भी परिभाषित करने की आवश्यकता होगी।
विशेषताएं:
कोड में प्रतिक्रिया लपेटें:
class MyTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.client = self.app.test_client()
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def get_auth_headers(self, username, password):
return {
'Authorization':
'Basic ' + base64.b64encode(
(username + ':' + password).encode('utf-8')).decode('utf-8'),
'Accept': 'application/json',
'Content-Type': 'application/json'
}
def requests(self, method, url, json={}, auth=(), **kwargs):
"""Wrapper around Flask test client to automatically set headers if JSON
data is passed + dump JSON data as string."""
if not hasattr(self.client, method):
print("Method %s not supported" % method)
return
fun = getattr(self.client, method)
# Set headers
headers = {}
if auth:
username, password = auth
headers = self.get_auth_headers(username, password)
# Prepare JSON if needed
if json:
import json as _json
headers.update({'Content-Type': 'application/json'})
response = fun(url,
data=_json.dumps(json),
headers=headers,
**kwargs)
else:
response = fun(url, **kwargs)
self.assertTrue(response.headers['Content-Type'] == 'application/json')
return response
उपयोग (एक परीक्षण मामले में):
def test_requests(self):
url = 'http://localhost:5001'
response = self.requests('get', url)
response = self.requests('post', url, json={'a': 1, 'b': 2}, auth=('username', 'password'))
...
फर्क सिर्फ इतना है requests
के साथ टाइपिंग के बजाय है requests.get(...)
आपको self.request('get', ...)
टाइप करना होगा।
तुम सच में requests
व्यवहार चाहते हैं, आप के चारों ओर अपने स्वयं के get
, put
, post
, delete
रैपर निर्धारित करने होंगे requests
नोट: इस के लिए हो सकता है ऐसा करने के लिए
सबसे अनुकूल तरीके उपclass FlaskClient
जैसा कि Flask API documentation
धन्यवाद में वर्णित है, लेकिन मैं एडाप्टर चाहता हूं, नकली नहीं। एक मिडलवेयर बनाना जो 'flask.test_client' से' request_mock' का अनुवाद करता है, केवल 'अनुरोधों को डाउनलोड करने के ऊपर ओवरहेड लगता है। एडाप्टर' – eplaut