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

Python 如何使用Flask测试客户端模拟AJAX请求?,python,ajax,unit-testing,flask,Python,Ajax,Unit Testing,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.

测试烧瓶应用程序是通过以下方式完成的:

# 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请求测试我的应用程序?

试试以下方法:-

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

好极了!:)我只是在寻找可以为
.get()
函数设置的参数。我已经在深入挖掘
werkzeug
docs:S文档的哪一部分你得到了这个&
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