如何在烧瓶模板中模拟`current_user`? [英] How to mock `current_user` in flask templates?

查看:37
本文介绍了如何在烧瓶模板中模拟`current_user`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在模板渲染下模拟flask-logincurrent_user.此函数返回当前登录的用户.

I want to mock flask-login's current_user under the template rendering. This function return the current logged user.

现在我正在模拟flask-login中的AnnonymousUserMixin,如果用户未通过身份验证,则默认情况下会返回AnnonymousUserMixin.但这会导致各种杂耍.如果我可以简单地模拟current_user,我将可以创建一个模拟对象以使其返回.

Right now I'm mocking the AnnonymousUserMixin from flask-login which is returned by default if the user is not authenticated. But this leads to all kind of juggles. If I could simply mock current_user I would be able to create a Mocked object for it to return.

以下是我今天使用的示例:

Here a sample of what I'm using today:

import unnittest
from flask_login.mixins import AnonymousUserMixin


class TestFoo(unittest.TestCase):
    @patch.object(AnonymousUserMixin, 'is_admin', create=True,                  
                  return_value=False)                                           
    @patch.object(AnonymousUserMixin, 'is_authenticated',  return_value=True)                                           
    def test_user_restriction(self, *args):
        ...                            

此致

推荐答案

好的.我找到了答案.

flask-login将要求您使用login_manager.init_app(your_app)初始化LoginManager实例.执行此操作时,它将current_user添加到您的应用上下文处理器.这发生在flask_login.utils._user_context_processor函数中,该函数定义为

flask-login will ask you to initialize a LoginManager instance with login_manager.init_app(your_app). When you do this it add the current_user to your app contexts processors. This happens at flask_login.utils._user_context_processor function, which is defined as

def _user_context_processor():
    return dict(current_user=_get_user())

此处_get_user在同一模块中定义.我对模拟current_user所做的操作是在flask_login.utils进行模拟_get_user的操作.

Here _get_user is defined at the same module. What I do to mock current_user is mock _get_user at flask_login.utils.

这里是如何完成此工作的示例.我正在打印响应内容,以便人们可以看到不同的结果.真正的测试不会手动实例化Test类,而应使用unittest.main或适当的方法.

Here is a working example of how it can be done. I am printing the response content so people can see the result differing. A real test would not instantiate Test class by hand and should use unittest.main or something appropriated.

from flask import Flask, render_template_string as render_string
from flask_login import LoginManager, UserMixin

app = Flask(__name__)
loginmgr = LoginManager(app)
loginmgr.init_app(app)


class User(UserMixin):
    pass


@loginmgr.user_loader
def load_user(user_id):
    return User.get(user_id)


@app.route('/')
def index():
    return render_string('Hello, {{ current_user | safe }}')


if __name__ == '__main__':
    import unittest
    from unittest import mock

    class Test:
        def test(self):
            client = app.test_client()
            response = client.get('/')
            data = response.data.decode('utf-8')
            print(data)

        @mock.patch('flask_login.utils._get_user')
        def test_current_user(self, current_user):
            user = mock.MagicMock() 
            user.__repr__ = lambda self: 'Mr Mocked'
            current_user.return_value = user
            client = app.test_client()
            response = client.get('/')
            data = response.data.decode('utf-8')
            print(data)


    t = Test()
    t.test()
    t.test_current_user()

这是它的输出:

Hello, <flask_login.mixins.AnonymousUserMixin object at 0x7f9d5ddaaf60>
Hello, Mr Mocked

此致

这篇关于如何在烧瓶模板中模拟`current_user`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆