使用以下方法测试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请求测试我的应用程序?
答案 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
`