我有一个使用 LDAP 进行身份验证的 Flask 应用程序,其中几个端点由 Flask-restful 管理,但我想对经过身份验证的端点进行单元测试,而无需实际访问 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'}
现在在我的单元测试中,我想我应该能够通过写入烧瓶登录来模拟经过身份验证的用户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.9,而不是 0.10。我知道Miguel Grinberg 对类似问题的回答,但我实际上并不想调用登录;我想完全绕过 LDAP(或任何测试数据库)的使用。
为什么current_user
覆盖技巧不起作用?我应该使用其他方法吗?