如何使用Flask测试客户端模拟AJAX请求?

时间:2012-01-30 13:37:30

标签: python ajax unit-testing flask

使用以下方法测试Flask应用程序:

# 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()

然后这是我的测试脚本:

# 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()

在测试输出中,我会得到:

Hello world! AJAX Request: False

问题

如何使用AJAX请求测试我的应用程序?

2 个答案:

答案 0 :(得分:21)

试试这个: -

def test_index():
    tester = app.test_client()
    response = tester.get('/', headers=[('X-Requested-With', 'XMLHttpRequest')])
    assert 'Hello world!' in response.data

答案 1 :(得分:1)

import json

def test_index():
    data = json.dumps({})
    client = app.test_client()
    headers = {
        'Content-Type': 'application/json',
    }
    response = client.post('/', data=data, headers=headers)
    data = json.loads(response.data)
    assert data

`