6

总之,我正在编写一个烧瓶应用程序,它依赖于烧瓶主体来管理用户角色。我想编写一些简单的单元测试来检查哪个用户可以访问哪些视图。pastebin上发布了一个代码示例,以避免使这篇文章混乱。简而言之,我定义了一些路由,装饰了一些,以便它们只能由具有适当角色的用户访问,然后尝试在测试中访问它们。

在粘贴的代码中,test_memberandtest_admin_b都失败了,抱怨PermissionDenied. 显然,我没有正确声明用户;至少,有关用户角色的信息不在正确的上下文中。

任何有关上下文处理复杂性的帮助或见解将不胜感激。

4

3 回答 3

8

Flask-Principal 不会在请求之间为您存储信息。您可以根据自己的喜好执行此操作。请记住这一点,并考虑一下您的测试。你在test_request_context方法中调用setUpClass方法。这会创建一个新的请求上下文。您还在测试中进行测试客户端调用self.client.get(..)。这些调用创建了彼此之间不共享的附加请求上下文。因此,您的调用identity_changed.send(..)不会发生在检查权限的请求的上下文中。我已经继续编辑您的代码以使测试通过,希望它能帮助您理解。特别注意我在方法before_request中添加的过滤器。create_app

import hmac
import unittest

from functools import wraps
from hashlib import sha1

import flask

from flask.ext.principal import Principal, Permission, RoleNeed, Identity, \
    identity_changed, identity_loaded current_app


def roles_required(*roles):
    """Decorator which specifies that a user must have all the specified roles.
    Example::

        @app.route('/dashboard')
        @roles_required('admin', 'editor')
        def dashboard():
            return 'Dashboard'

    The current user must have both the `admin` role and `editor` role in order
    to view the page.

    :param args: The required roles.

    Source: https://github.com/mattupstate/flask-security/
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perms = [Permission(RoleNeed(role)) for role in roles]
            for perm in perms:
                if not perm.can():
                    # return _get_unauthorized_view()
                    flask.abort(403)
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper



def roles_accepted(*roles):
    """Decorator which specifies that a user must have at least one of the
    specified roles. Example::

        @app.route('/create_post')
        @roles_accepted('editor', 'author')
        def create_post():
            return 'Create Post'

    The current user must have either the `editor` role or `author` role in
    order to view the page.

    :param args: The possible roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = Permission(*[RoleNeed(role) for role in roles])
            if perm.can():
                return fn(*args, **kwargs)
            flask.abort(403)
        return decorated_view
    return wrapper


def _on_principal_init(sender, identity):
    if identity.id == 'admin':
        identity.provides.add(RoleNeed('admin'))
    identity.provides.add(RoleNeed('member'))


def create_app():
    app = flask.Flask(__name__)
    app.debug = True
    app.config.update(SECRET_KEY='secret', TESTING=True)
    principal = Principal(app)
    identity_loaded.connect(_on_principal_init)

    @app.before_request
    def determine_identity():
        # This is where you get your user authentication information. This can
        # be done many ways. For instance, you can store user information in the
        # session from previous login mechanism, or look for authentication
        # details in HTTP headers, the querystring, etc...
        identity_changed.send(current_app._get_current_object(), identity=Identity('admin'))

    @app.route('/')
    def index():
        return "OK"

    @app.route('/member')
    @roles_accepted('admin', 'member')
    def role_needed():
        return "OK"

    @app.route('/admin')
    @roles_required('admin')
    def connect_admin():
        return "OK"

    @app.route('/admin_b')
    @admin_permission.require()
    def connect_admin_alt():
        return "OK"

    return app


admin_permission = Permission(RoleNeed('admin'))


class WorkshopTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        app = create_app()
        cls.app = app
        cls.client = app.test_client()

    def test_basic(self):
        r = self.client.get('/')
        self.assertEqual(r.data, "OK")

    def test_member(self):
        r = self.client.get('/member')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, "OK")

    def test_admin_b(self):
        r = self.client.get('/admin_b')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, "OK")


if __name__ == '__main__':
    unittest.main()
于 2013-05-23T14:27:30.150 回答
1

正如马特解释的那样,这只是一个上下文问题。感谢他的解释,我提供了两种在单元测试期间切换身份的不同方法。

首先,让我们稍微修改一下应用程序的创建:

def _on_principal_init(sender, identity):
    "Sets the roles for the 'admin' and 'member' identities"
    if identity.id:
        if identity.id == 'admin':
            identity.provides.add(RoleNeed('admin'))
        identity.provides.add(RoleNeed('member'))

def create_app():
    app = flask.Flask(__name__)
    app.debug = True
    app.config.update(SECRET_KEY='secret',
                      TESTING=True)
    principal = Principal(app)
    identity_loaded.connect(_on_principal_init)
    #
    @app.route('/')
    def index():
        return "OK"
    #
    @app.route('/member')
    @roles_accepted('admin', 'member')
    def role_needed():
        return "OK"
    #
    @app.route('/admin')
    @roles_required('admin')
    def connect_admin():
        return "OK"

    # Using `flask.ext.principal` `Permission.require`...
    # ... instead of Matt's decorators
    @app.route('/admin_alt')
    @admin_permission.require()
    def connect_admin_alt():
        return "OK"

    return app

第一种可能性是创建一个函数,在我们测试中的每个请求之前加载一个身份。setUpClass最简单的方法是在应用程序创建后在测试套件中声明它,使用app.before_request装饰器:

class WorkshopTestOne(unittest.TestCase):
    #
    @classmethod
    def setUpClass(cls):
        app = create_app()
        cls.app = app
        cls.client = app.test_client()

        @app.before_request
        def get_identity():
            idname = flask.request.args.get('idname', '') or None
            print "Notifying that we're using '%s'" % idname
            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(idname))

然后,测试变为:

    def test_admin(self):
        r = self.client.get('/admin')
        self.assertEqual(r.status_code, 403)
        #
        r = self.client.get('/admin', query_string={'idname': "member"})
        self.assertEqual(r.status_code, 403)
        #
        r = self.client.get('/admin', query_string={'idname': "admin"})
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, "OK")
    #
    def test_admin_alt(self):
        try:
            r = self.client.get('/admin_alt')
        except flask.ext.principal.PermissionDenied:
            pass
        #
        try:
            r = self.client.get('/admin_alt', query_string={'idname': "member"})
        except flask.ext.principal.PermissionDenied:
            pass
        #
        try:
            r = self.client.get('/admin_alt', query_string={'idname': "admin"})
        except flask.ext.principal.PermissionDenied:
            raise
        self.assertEqual(r.data, "OK")

(顺便说一句,最后的测试表明 Matt 的装饰器更容易使用......)


第二种方法使用test_request_context带有 a 的函数with ...来创建临时上下文。无需定义由 装饰的函数@app.before_request,只需将要测试的路由作为参数传递,在上下文中test_request_context发送信号并使用该方法identity_changed.full_dispatch_request

class WorkshopTestTwo(unittest.TestCase):
    #
    @classmethod
    def setUpClass(cls):
        app = create_app()
        cls.app = app
        cls.client = app.test_client()
        cls.testing = app.test_request_context


    def test_admin(self):
        with self.testing("/admin") as c:
            r = c.app.full_dispatch_request()
            self.assertEqual(r.status_code, 403)
        #
        with self.testing("/admin") as c:
            identity_changed.send(c.app, identity=Identity("member"))
            r = c.app.full_dispatch_request()
            self.assertEqual(r.status_code, 403)
        #
        with self.testing("/admin") as c:
            identity_changed.send(c.app, identity=Identity("admin"))
            r = c.app.full_dispatch_request()
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.data, "OK")
于 2013-05-24T09:10:19.027 回答
0

根据 Matt 的回复,我创建了一个上下文管理器,以使 determine_identity 更简洁:

@contextmanager
def identity_setter(app, user):
    @app.before_request
    def determine_identity():
        #see http://stackoverflow.com/questions/16712321/unit-testing-a-flask-principal-application for details
        identity_changed.send(current_app._get_current_object(), identity=Identity(user.id))
    determine_identity.remove_after_identity_test = True
    try: 
        yield
    finally:
        #if there are errors in the code under trest I need this to be run or the addition of the decorator could affect other tests
        app.before_request_funcs = {None: [e for e in app.before_request_funcs[None] if not getattr(e,'remove_after_identity_test', False)]}

所以当我运行我的测试时,它看起来像:

with identity_setter(self.app,user):
           with user_set(self.app, user):
                with self.app.test_client() as c:
                    response = c.get('/orders/' + order.public_key + '/review')

我希望这会有所帮助,我欢迎任何反馈:)

~维克多

于 2014-09-01T20:54:08.657 回答