烧瓶在单元测试中禁用CSRF [英] Flask disable CSRF in unittest

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

问题描述

在我的项目__init__.py中,我有这个:

In my projects __init__.py I have this:

app = Flask(__name__)
app.config.from_object('config')
CsrfProtect(app)
db = SQLAlchemy(app)

我的开发配置文件如下:

My development config file looks like:

import os
basedir = os.path.abspath(os.path.dirname(__file__))

DEBUG = True
WTF_CSRF_ENABLED = True
SECRET_KEY = 'supersecretkey'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'project.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

在我的单元测试设置中,我有这个:

And in my unittest setUp I have this:

from project import app, db

class ExampleTest(unittest.TestCase):
   def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        self.app = app.test_client()
        db.create_all()

理论上,在此处将WTF_CSRF_ENABLED设置为False应该可以防止单元测试使用CSRF,但是如果在单元测试期间执行POST,我仍然会收到CSRF错误.我认为这是因为我已经调用了CsrfProtect(app),而WTF_CSRF_ENABLED为True(当我导入应用程序时,它被称为).如果我在配置文件中设置WTF_CSRF_ENABLED = False,它将按预期工作.

In theory, setting WTF_CSRF_ENABLED to False here should prevent CSRF for the unit tests, however I'm still getting CSRF errors if I do a POST while unit testing. I think it is because I have already called CsrfProtect(app) while WTF_CSRF_ENABLED is True (when I import app, it is called). If I set WTF_CSRF_ENABLED = False in the config file, it works as expected.

在启用CSRF之后,是否仍然可以禁用CSRF?还是我在这里树错树了?

Is there anyway I can disable CSRF after it has already been enabled? Or am I barking up the wrong tree here?

推荐答案

查看csrf_protect的代码,每次进入请求时,它都会检查app.config ['WTF_CSRF_METHODS'],以查看此请求类型是否应受CSRF保护.默认情况下,受保护的方法是:

Looking at the code for csrf_protect, it checks app.config['WTF_CSRF_METHODS'] every time a request comes in to see if this request type should be CSRF protected. By default the protected methods are:

app.config.setdefault('WTF_CSRF_METHODS', ['POST', 'PUT', 'PATCH'])

由于它实际上每次都会检查app.config,因此只需在我的单元测试setUp中将其更改为空列表即可解决此问题:

Because it actually checks the app.config every time, simply changing this to an empty list in my unit tests setUp resolves the issue:

from project import app, db

class ExampleTest(unittest.TestCase):
   def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_METHODS'] = []  # This is the magic
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        self.app = app.test_client()
        db.create_all()

Alternetly,它确实向app.before_request()注册了csrf保护,因此我认为可以通过修改

Alternetly, it does register the csrf protection with app.before_request(), so I think it may be possible to unregister it by modifying the before request functions. But I think going that route would be more likely to see problems on future updates.

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

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