I would like to test a wtf-form with a crsf token but I don't know how to send the token.
Here is my form :
class myLoginForm(FlaskForm):
username = StringField()
password = StringField()
mySubmit = SubmitField('Save')
Here is my route :
@app.route('/login', methods=['GET', 'POST'])
def login():
loginForm = myLoginForm()
if loginForm.validate_on_submit():
result = request.form
username = result.get("username")
password = result.get("password")
Here is my test :
import unittest
from flask_testing import TestCase
from flask import Flask
import json
class TestLogin(TestCase):
def create_app(self):
app = Flask(__name__)
return app
def test_submission(self):
headers = {
'ContentType': 'application/json',
'dataType': 'json'
}
data = {
'username': 'foo',
'password': 'bar'
}
response = app.test_client().post(
'/login',
data=json.dumps(data),
content_type='application/json',
follow_redirects=True
)
assert self.get_context_variable("loginForm").validate_on_submit() == True
The assertion fails, because the validate_on_submit() returns False. I think it is due to the crsf token.
How can I send the crsf token to the POST request ?
Have a nice day
Maybe this could help you. Make it easier to access a CSRF token in automated tests
Unless you want to test actual CSRF protection in Flask-WTF it's much simpler to turn off CSRF completely in app config when running unit tests. The conditions that trigger CSRF protection may be easier tested with integration/e2e tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With