【问题标题】:Flask-WTF - Unable to test a form submissionFlask-WTF - 无法测试表单提交
【发布时间】:2020-01-06 16:32:06
【问题描述】:

我想用 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() 返回 False。我认为这是由于 crsf 令牌。

如何将 crsf 令牌发送到 POST 请求?

祝你有美好的一天

【问题讨论】:

标签: python flask python-unittest flask-wtforms wtforms


【解决方案1】:

【讨论】:

  • 感谢您的回答。我想知道是否有更“原生”的东西。在这个答案中,有些课程已经过时了,这有点痛苦
【解决方案2】:

除非您想test actual CSRF protection in Flask-WTF,否则在运行单元测试时在应用配置中完全关闭 CSRF 会简单得多。使用集成/e2e 测试可能更容易测试触发 CSRF 保护的条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2015-05-18
    相关资源
    最近更新 更多