繁体   English   中英

如何为我的单元测试模拟烧瓶装饰器 @login_required?

[英]How do I mock a flask decorator @login_required for my unit tests?

我正在开发一个需要编写一些单元测试的应用程序。 我想问一下如何在单元测试中模拟装饰器“@login_required”? 这是一个在 app.py 中具有 @login_required 函数的函数

@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    global application_inst
    if request.method == 'POST':
        print("Setting changed")

    return render_template('settings.html', user=session['user'], application=application_inst)

这是我在 test_app.py 中的单元测试用例

class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app(db)
        self.app.config['TESTING'] = True
        self.app.config['LOGIN_DISABLED'] = True
        self.app.config['WTF_CSRF_ENABLED'] = False
        self.app.config['DEBUG'] = True
        self.client = self.app.test_client(self)

    def test_settings_passed(self):
        with self.client:
            response = self.client.get('/settings', follow_redirects=True)
            self.assertEqual(response.status_code, 200)

因为我没有办法通过测试,即。 status_code = 200,因为它期望 404。我已经尝试了互联网上可用的所有内容,但并没有解决我的问题。 因此我想尝试模拟装饰器。 我该怎么做? 请帮助我,因为我长期以来一直被困在这个问题上。

我假设您使用的是flask_login的装饰器。

事后模拟装饰器是不可能的,因为它的装饰已经发生了。 也就是说,您可以查看装饰器的作用以了解如何模拟它。

正如您在源代码中看到的那样,有很多情况不会强制执行登录:

if request.method in EXEMPT_METHODS:
    return func(*args, **kwargs)
elif current_app.config.get('LOGIN_DISABLED'):
    return func(*args, **kwargs)
elif not current_user.is_authenticated:
    return current_app.login_manager.unauthorized()
return func(*args, **kwargs)

你可以:

  • 模拟EXEMPT_METHODS以包含GETPOST
  • 模拟LOGIN_DISABLED配置值
  • 模拟current_user.is_authenticated

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM