Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask disable CSRF in unittest

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()

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.

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

like image 323
vimalloc Avatar asked Jul 27 '16 22:07

vimalloc


People also ask

How do I disable CSRF Flask?

You can disable CSRF protection in all views by default, by setting WTF_CSRF_CHECK_DEFAULT to False , and selectively call protect() only when you need. This also enables you to do some pre-processing on the requests before checking for the CSRF token.

What is FlaskForm?

The FlaskForm base class is defined by the Flask-WTF extension, so it is imported from flask_wtf . The fields and validators, however, are imported directly from the WTForms package. The list of standard HTML fields supported by WTForms is shown in Table 4-1. Table 4-1. WTForms standard HTML fields.


1 Answers

You can disable it using the config variable WTF_CSRF_ENABLED,

for example

class TestConfig(Config):
    TESTING = True
    WTF_CSRF_ENABLED = False
    ...

or app.config['WTF_CSRF_ENABLED'] = False

See also flask-WTF documentation

like image 120
Jorge Leitao Avatar answered Sep 21 '22 19:09

Jorge Leitao