You can use the requests method defined in the code section below. To use it, you 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)
Usage (in 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 from requests is that instead of entering requests.get(...) you will need to enter self.request('get', ...) .
If you really need requests behavior, you will need to define your own get , put , post , delete wrappers around requests
Note:
The best way to do this could be to subclass FlaskClient , as described in the Flags API documentation
source share