2013-05-29 88 views
0

我有一個只有POST方法實現的python FLASK視圖。我不需要GET,因爲外部模板會將數據發佈到此視圖。 現在我想爲這個視圖編寫單元測試,在這裏我想模擬最初的POST請求並斷言視圖實現能正常工作。外部模板模擬HTTP 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

你需要使用硒,也可以使用內置的測試客戶端瓶? http://flask.pocoo.org/docs/testing/,http://stackoverflow.com/a/15838404/594589 – dm03514

+0

會使用測試客戶端內置的燒瓶使模擬POST請求更容易嗎? – Priyam

+0

是的,這就是測試客戶端設計的目的, – dm03514

回答

0

我只是堅持了2個小時,事實證明,你可以通過一個字典作爲你的數據有效載荷在你的測試,你將能夠訪問我通過request.form.get

從您的代碼T實施例的測試代碼

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'})