1

我正在开发一个需要编写一些单元测试的应用程序。我想问如何在我的单元测试中模拟一个装饰器'@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。我已经尝试了互联网上可用的所有内容,但它并没有解决我的问题。因此,我想尝试嘲笑装饰者。我该怎么做?请帮助我,因为我长期以来一直陷入这个问题。

4

1 回答 1

1

我假设您正在使用来自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包括GETand POST
  • 模拟LOGIN_DISABLED配置值
  • 嘲笑current_user.is_authenticated
于 2020-10-13T10:32:35.793 回答