使用flask-login单元测试烧瓶时禁用@login_required [英] Disabling @login_required while unit-testing flask with flask-login

查看:235
本文介绍了使用flask-login单元测试烧瓶时禁用@login_required的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用webtest设置所有我的测试:

  class TestCase(unittest.TestCase):
$ b $ def setUp(self):
app.config [ TESTING'] = True
self.client = webtest.TestApp(app)

我尝试通过self.client.get()用@login_required装饰来访问网址,我得到一个401错误消息,我没有权限访问该网址。



根据 https://flask-login.readthedocs.org / en / latest /#protect-views
和这个讨论
将'TESTING'的配置值设置为True应该禁用登录要求,但这似乎不适用于我。 >

有什么建议?

解决方案

这是因为 Flask登录缓存 TESTING LOGIN_DISABLED on init_app https://github.com/maxcountryman/因此,如果你创建应用程序,然后在配置中设置的东西,那么你配置更改将会忽略。

更好的方法是使用应用程序工厂,为生产和测试使用不同的配置,它也降低了测试中未清理应用程序状态的概率。
$ b

最简单的方法是重新执行 login_manager

  class TestCase(unittest.TestCase):
def setUp(self):
app.config ['TESTING'] = True
app.login_manager.init_app(app)
self.client = webtest.TestApp(app)


I am unit testing my flask app which uses the flask-login extension.

I am setting up all my tests like this using webtest:

class TestCase(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        self.client = webtest.TestApp(app)

But when I try to visit urls through self.client.get() which are decorated with @login_required, I get a 401 error with a message that I am not authorized to access the url.

According to the documentation https://flask-login.readthedocs.org/en/latest/#protecting-views and this discussion, setting the config value of 'TESTING' to True should disable the login requirements, but that doesn't seem to be working for me.

Any suggestions?

解决方案

This because Flask-Login caching TESTING or LOGIN_DISABLED on init_app (https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L164).

So if you create application and then set something in config then you config changes will ignored.

Better way use application factory with separated configs for production and tests, it also decrease probability get errors with not cleaned application state in tests.

The easiest way reinit login_manager:

class TestCase(unittest.TestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.login_manager.init_app(app)
        self.client = webtest.TestApp(app)

这篇关于使用flask-login单元测试烧瓶时禁用@login_required的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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