Testing Flask applications is done with:
# main.py
from flask import Flask, request
app = flask.Flask(__name__)
@app.route('/')
def index():
s = 'Hello world!', 'AJAX Request: {0}'.format(request.is_xhr)
print s
return s
if __name__ == '__main__':
app.run()
Then here is my test script:
# test_script.py
import main
import unittest
class Case(unittest.TestCase):
def test_index():
tester = app.test_client()
rv = tester.get('/')
assert 'Hello world!' in rv.data
if __name__ == '__main__':
unittest.main()
In the test output, I'll get:
Hello world! AJAX Request: False
How do I test my app with AJAX requests?
AXJS(Asynchronous JavaScript and XML) is Asynchronous, so a user can continue to use the application while the client program requests information from the server in the background. Now we'll use jQuery AJAX to post the form data to the Python Flask method.
Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code.
Writing unit tests for your application lets you check that the code you wrote works the way you expect. Flask provides a test client that simulates requests to the application and returns the response data. You should test as much of your code as possible.
Prototype - AJAX Response() Method.
Try this:-
def test_index():
tester = app.test_client()
response = tester.get('/', headers=[('X-Requested-With', 'XMLHttpRequest')])
assert 'Hello world!' in response.data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With