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']
Solution 1:
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'])defmain():
url = request.form.get('return_url')
# just example. will return value of sent return_urlreturn 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 = TrueclassTestApi(unittest.TestCase):
deftest_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 testin 0.009s
OK
Hope it helps.
Post a Comment for "Flask Unittest For Post Method"