0

I have a Flask web app written and writing testcases for the same using unittest. Below is how it handles the signup route

server.py

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    if current_user.__dict__.get('id', None):
        return render_template('login.html')

    if request.method == 'GET':
        return render_template('signup.html')

    else:
        data = request.get_json()
        username = data.get('username', '').lower()
        password = data.get('password', '')
        client = data.get('client', '')['name']
        confirm_password = data.get('confirm_password', '')

Inside the test file, there are helper methods to signup

test_unittesting.py

def signup(self, username, password, confirm, client):
    return self.app.post(
        '/signup',
        data=json.dumps(dict(username=username, password=password, confirm=confirm, client=client)),
        follow_redirects=True
    )

But it does not seem to be working. request.get_json() returns empty. The parameters are present in request.get_data() and not in request.get_json(). I am unable to change the helper method to support the method defined for the route. What must I change in the test file to get it working as request.get_json()?

Sushant Kumar
  • 435
  • 7
  • 24

3 Answers3

1

The docs describe the attributes available on the request. In most common cases request.data will be empty because it's used as a fallback:

request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

request.args: the key/value pairs in the URL query string
request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded
request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.
request.values: combined args and form, preferring args if keys overlap

All of these are MultiDict instances. You can access values using:

request.form['name']: use indexing if you know the key exists
request.form.get('name'): use get if the key might not exist
request.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value.
Ashwin Golani
  • 498
  • 3
  • 10
0

The mimetype must be set to mimetype='application/json' as an additional parameter inside the post call.

def signup(self, username, password, confirm, client):
    return self.app.post(
        '/signup',
        data=json.dumps(dict(username=username, password=password, confirm=confirm, client=client)),
        follow_redirects=True, mimetype='application/json'
    )
Sushant Kumar
  • 435
  • 7
  • 24
0
def signup(self, username, password, confirm, client):
    return self.app.post(
        '/signup',
        data=json.dumps(dict(username=username, password=password, confirm=confirm, client=client)), content_type='application/json')