How can I fake request.POST and GET params for unit testing in Flask?
Solution 1:
Did you read Flask docs about testing?
You can use following:
self.app.post('/path-to-request', data=dict(var1='data1', var2='data2', ...))
self.app.get('/path-to-request', query_string=dict(arg1='data1', arg2='data2', ...))
Current development version of Flask also includes support for testing JSON APIs:
from flask import request, jsonify
@app.route('/jsonapi')
def auth():
json_data = request.get_json()
attribute = json_data['attr']
return jsonify(resp=generate_response(attribute))
with app.test_client() as c:
rv = c.post('/jsonapi', json={
'attr': 'value', 'other': 'data'
})
json_data = rv.get_json()
assert generate_response(email, json_data['resp'])
Solution 2:
POST:
self.app.post('/endpoint', data=params)
GET:
self.app.get('/endpoint', query_string=params)
Solution 3:
If you prefer to use test_request_context
:
import unittest
from myapp import extract_query_params
testapp = flask.Flask(__name__)
class TestFoo(unittest.TestCase):
def test_happy(self):
with testapp.test_request_context('?limit=1&offset=2'):
limit, offset = extract_query_params(['limit', 'offset'])
self.assertEquals(limit, 1)
self.assertEquals(offset, 2)
Solution 4:
I still had issue with this when testing post form data for logging in this worked for me.
def login(self, username, password):
return self.app.post('/', data='Client_id=' + username +'&Password=' + password,
follow_redirects=True,content_type='application/x-www-form-urlencoded')
I found this is out this way.
Chrome: Developer mode --> Doc --> HTML doc that was requested --> Headers Tab --> Form data --> view source