Python 如何模拟单元测试所需的flask decorator@login\u?

Python 如何模拟单元测试所需的flask decorator@login\u?,python,python-3.x,unit-testing,flask,flask-testing,Python,Python 3.x,Unit Testing,Flask,Flask Testing,我正在开发一个需要编写一些单元测试的应用程序。我想问的是,如何在单元测试中模拟装饰程序“@login\u required”? 这里有一个函数,在app.py中有@login\u required函数 @app.route('/settings', methods=['GET', 'POST']) @login_required def settings(): global application_inst if request.method == 'POST':

我正在开发一个需要编写一些单元测试的应用程序。我想问的是,如何在单元测试中模拟装饰程序“@login\u required”? 这里有一个函数,在app.py中有@login\u 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)
因为我没有办法通过测试,即状态代码=200,因为它期望404。我尝试了互联网上的一切,但都没有解决我的问题。因此,我想试着嘲笑一下装饰师。我怎么做?
请帮助我,因为我长期以来一直被困在这个问题中。

我假设您使用的是来自
flask\u登录的装饰程序

实际上不可能事后模拟一个装饰者,因为它的装饰已经发生了。这就是说,你可以看看,以找出如何嘲笑它

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

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)
你可以:

  • 模拟
    豁免方法
    以包括
    GET
    POST
  • 模拟
    LOGIN\u禁用的
    config值
  • 模拟
    当前\u用户。是否经过身份验证

由于我已经在我的setUp()函数中将login\u disabled设置为True,是否需要再次模拟login\u disabled配置值?您不需要这样做。