我有一个只有POST方法实现的python FLASK视图。我不需要GET,因为外部模板会将数据POST到此视图。 现在我想为这个视图编写单元测试,在那里我想模拟初始POST请求并断言视图实现正常工作。
将访问我的视图实现的外部模板示例:
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Author" CONTENT="Richard Ward">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="Test Page">
</HEAD>
<BODY>
<FORM METHOD="POST" ACTION="www.myView.com/testview">
<INPUT TYPE="hidden" NAME="employeeId" value="304253498022">
<INPUT TYPE="hidden" NAME="employeeName" value="testName">
<INPUT TYPE="submit" name="submit" value="Show Information">
</FORM>
</BODY>
</HTML>
我的观点类
class TestView(MethodView):
app = None
def post(self):
"""
Implementation of the post request for this view
"""
employeeId= request.form.get('employeeId', None)
employeeName = request.form.get('employeeName', None)
# some data processing code
return render_template("summary.html")
@classmethod
def registerSelf(cls, app):
"""
Registers itself as a view with the passed Flask application
"""
TestView.app = app
app.flaskApp.add_url_rule('/testview', view_func=TestView.as_view('testview'))
我想直接调用我的视图帖子并在请求正文中传递模拟表单数据
答案 0 :(得分:0)
我刚刚坚持了2个小时,事实证明您可以在测试中将字典作为数据有效负载传递,并且您可以通过request.form.get
示例测试代码
from <the module you want to test> import app
app.testing = True
self.app = app.test_client()
self.app.post(<endpoint name, for example /index>, data={
'employeeId': '1',
'employeeName': 'Ruth'})