我正在为一个返回渲染模板的函数编写Flask单元测试。我尝试了几种方法,但似乎没有用。 这是功能:
@app.route('/', methods=['POST'])
@lti(request='initial', error=error, app=app)
def chooser(lti=lti):
return_url = request.form.get('launch_presentation_return_url', '#')
return render_template(
'chooser.html'
)
我一直尝试的方式很少:
# 1st way
rv = self.app.post('/')
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
# Error
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
AssertionError: False is not true
# 2nd way
rv = self.app.post('/chooser.html')
assert '<h1>Choose an Icon to Insert</h1>' in rv.data
# Error
assert 'Choose an Icon to Insert' in rv.data
AssertionError
chooser.html
<body>
<h1>Choose an Icon to Insert</h1>
</body>
感谢您的帮助。
答案 0 :(得分:3)
这里有一个可以帮助您理解的例子。我们的申请 - app.py
:
import httplib
import json
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/', methods=['POST'])
def main():
url = request.form.get('return_url')
# just example. will return value of sent return_url
return Response(
response=json.dumps({'return_url': url}),
status=httplib.OK,
mimetype='application/json'
)
我们的测试 - test_api.py
:
import json
import unittest
from app import app
# set our application to testing mode
app.testing = True
class TestApi(unittest.TestCase):
def test_main(self):
with app.test_client() as client:
# send data as POST form to endpoint
sent = {'return_url': 'my_test_url'}
result = client.post(
'/',
data=sent
)
# check result from server with expected data
self.assertEqual(
result.data,
json.dumps(sent)
)
如何运行:
python -m unittest discover -p path_to_test_api.py
结果:
----------------------------------------------------------------------
Ran 1 test in 0.009s
OK
希望它有所帮助。