認証に LDAP を使用する Flask アプリケーションがあり、複数のエンドポイントがフラスコ レストフルで管理されていますが、実際に LDAP サーバーにアクセスすることなく、認証されたエンドポイントを単体テストしたいと考えています。フラスコログインを偽造してこれを行うことを望んでいましたcurrent_user
が、このトリックを機能させることができませんでした。これが私が試したことです:
私は自分のクラスからすべてのリソースを派生させているため、エンドポイントは認証されています (これは実際のテストと手動テストでうまく機能し、flask-restful が推奨しているものです):
def authenticate(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not getattr(func, 'authenticated', True):
return func(*args, **kwargs)
if flask.ext.login.current_user and flask.ext.login.current_user.is_authenticated():
return func(*args, **kwargs)
flask.ext.restful.abort(401)
return wrapper
class AuthenticatedResource(flask.ext.restful.Resource ):
method_decorators = [authenticate]
以下は単純なエンドポイントです。
class RootResource(AuthenticatedResource):
def get(self):
return {'message':'Hello'}
単体テストで、flask-login's に書き込むことで、認証されたユーザーをモックできるはずだと考えましたcurrent_user
。
from flask.ext.login import UserMixin, current_user
class AuthenticatedUser(UserMixin):
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return "Test User"
class TestMyAPI(unittest.TestCase):
def test_root_endpoint_responds_properly(self):
with app.test_client() as client:
current_user = AuthenticatedUser()
response = client.get('/')
self.assertEqual(response.status_code, 200)
body = json.loads(response.data)
self.assertEqual(body, {'message':'Hello'})
残念ながら、テストは失敗で応答します。
==================================================================
FAIL: test_root_endpoint_responds_properly (test_my_api.TestMyAPI)
------------------------------------------------------------------
Traceback (most recent call last):
File "xxxx/test_graph_api.py", line xxx, in test_root_endpoint_responds_properly
self.assertEqual(response.status_code, 200)
AssertionError: 401 != 200
その他のメモ: 0.10 ではなく、フラスコ 0.9 を使用しています。同様の問題に対する Miguel Grinberg の回答は知っていますが、実際にはログインを呼び出したくありません。LDAP (または任意のテスト データベース) の使用を完全にバイパスしたいと考えています。
current_user
オーバーライド トリックが機能しないのはなぜですか? 私が使用すべき他のアプローチはありますか?