Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Unittest for Post Method

I am writing a Flask unit test for a function that would return a render template. I tried few ways but it seems not working. Here is the function:

@app.route('/', methods=['POST'])
@lti(request='initial', error=error, app=app)
def chooser(lti=lti):
   return_url = request.form.get('launch_presentation_return_url', '#')
   return render_template(
       'chooser.html'
   )

Few ways that I have been trying:

# 1st way    
rv = self.app.post('/')
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
# Error
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
AssertionError: False is not true


# 2nd way    
rv = self.app.post('/chooser.html')
assert '<h1>Choose an Icon to Insert</h1>' in rv.data
# Error
assert 'Choose an Icon to Insert' in rv.data
AssertionError

chooser.html

 <body>
    <h1>Choose an Icon to Insert</h1>
 </body>

Thanks for all your helps.

like image 915
Tuan Pham Avatar asked Jul 03 '17 18:07

Tuan Pham


1 Answers

Here an example which can help you to understand. Our application - app.py:

import httplib
import json

from flask import Flask, request, Response

app = Flask(__name__)


@app.route('/', methods=['POST'])
def main():
   url = request.form.get('return_url')
   # just example. will return value of sent return_url
   return Response(
      response=json.dumps({'return_url': url}),
      status=httplib.OK,
      mimetype='application/json'
   )

Our tests - test_api.py:

import json
import unittest

from app import app
# set our application to testing mode
app.testing = True


class TestApi(unittest.TestCase):

    def test_main(self):
        with app.test_client() as client:
            # send data as POST form to endpoint
            sent = {'return_url': 'my_test_url'}
            result = client.post(
                '/',
                data=sent
            )
            # check result from server with expected data
            self.assertEqual(
                result.data,
                json.dumps(sent)
            )

How to run:

python -m unittest discover -p path_to_test_api.py

Result:

----------------------------------------------------------------------
Ran 1 test in 0.009s

OK

Hope it helps.

like image 129
Danila Ganchar Avatar answered Oct 21 '22 13:10

Danila Ganchar