Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate an AJAX request with Flask test client?

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

Question

How do I test my app with AJAX requests?

like image 218
Kit Avatar asked Jan 30 '12 13:01

Kit


People also ask

Can we use AJAX in flask?

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.

Can you use AJAX with Python?

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.

What is test client flask?

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.

Which method is used to get the response of an AJAX call as a string?

Prototype - AJAX Response() Method.


1 Answers

Try this:-

def test_index():
    tester = app.test_client()
    response = tester.get('/', headers=[('X-Requested-With', 'XMLHttpRequest')])
    assert 'Hello world!' in response.data
like image 149
sojin Avatar answered Sep 20 '22 17:09

sojin