You can use the requests method defined in the code section below.
To use it you'll also need to define the get_auth_headers method shown in the code below.
Features:
Code:
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
Usage (in a test case):
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'))
...
The only difference with requests is that instead of typing requests.get(...) you'll have to type self.request('get', ...).
If you really want requests behaviour, you'll need to define your own get, put, post, delete wrappers around requests
Note:
An optimal way to do this might be to subclass FlaskClient as described in Flask API documentation