2016-07-13 2 views
3

フラスコクラスのビューにabort()があります。私はアボートが呼び出されたと主張することができますが、コンテキストマネージャの406コードにアクセスすることはできません。 WERKZEUGライブラリHTTPエラーでテスト中にFlaskのステータスコードをキャッチしていますか?

views.py

from flask.views import View 
from flask import abort 

class MyView(View): 

    def validate_request(self): 
     if self.accept_header not in self.allowed_types: 
      abort(406) 

tests.py

from werkzeug.exceptions import HTTPException 

def test_validate_request(self): 
    # Ensure that an invalid accept header type will return a 406 

    self.view.accept_header = 'foo/bar' 
    with self.assertRaises(HTTPException) as http_error: 
     self.view.validate_request() 
     self.assertEqual(http_error.???, 406) 

答えて

1

だから私はばかだ。私は以前これを気付かなかったと信じられない。 http_errorの中には例外オブジェクトがあります。私のテストでは、validate_requestを呼び出す前にhttp_errorを呼び出していたので、私はそれを逃しました。正しい答えは次のとおりです。

from werkzeug.exceptions import HTTPException 

def test_validate_request(self): 
    # Ensure that an invalid accept header type will return a 406 

    self.view.accept_header = 'foo/bar' 
    with self.assertRaises(HTTPException) as http_error: 
     self.view.validate_request() 
     self.assertEqual(http_error.exception.code, 406) 

P.S.子供たち、あなたが死んで疲れているときに決してコード化しないでください。 :(

1

コードはHTTPException.Noneに保存されます。 sourcecode(またはNoneコードではない例:BadRequestの例外を参照してください)で自分自身を見ることができます。

関連する問題