Flask-WTF - 无法测试表单提交
Flask-WTF - Unable to test a form submission
我想用 crsf 令牌测试 wtf-form,但我不知道如何发送令牌。
这是我的表格:
class myLoginForm(FlaskForm):
username = StringField()
password = StringField()
mySubmit = SubmitField('Save')
这是我的路线:
@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")
这是我的测试:
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
断言失败,因为 validate_on_submit() returns False。我认为这是由于 crsf 令牌。
如何将 crsf 令牌发送到 POST 请求?
祝你有愉快的一天
也许这对你有帮助。
Make it easier to access a CSRF token in automated tests
除非您想 test actual CSRF protection in Flask-WTF 在 运行 单元测试时,在应用程序配置中完全关闭 CSRF 要简单得多。使用 integration/e2e 测试可以更容易地测试触发 CSRF 保护的条件。
我想用 crsf 令牌测试 wtf-form,但我不知道如何发送令牌。
这是我的表格:
class myLoginForm(FlaskForm):
username = StringField()
password = StringField()
mySubmit = SubmitField('Save')
这是我的路线:
@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")
这是我的测试:
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
断言失败,因为 validate_on_submit() returns False。我认为这是由于 crsf 令牌。
如何将 crsf 令牌发送到 POST 请求?
祝你有愉快的一天
也许这对你有帮助。 Make it easier to access a CSRF token in automated tests
除非您想 test actual CSRF protection in Flask-WTF 在 运行 单元测试时,在应用程序配置中完全关闭 CSRF 要简单得多。使用 integration/e2e 测试可以更容易地测试触发 CSRF 保护的条件。