如何在 Flask 中对路由进行单元测试

How to Unit Test a Route in Flask

我一直在尝试使用 Flask,关注 Corey Schafer 在 Youtube 上的系列文章。我试图打破一些概念并构建一个非常简单的密码应用程序。

到目前为止它工作正常,但我想知道如何构建测试以确保它验证密码基本密码有效性。 (这不是测试密码匹配)。

显然,在应用程序中,它确认密码是否满足最低标准,即DataRequired()Length(min=8)

但是我如何在单元测试模块中确认它是正确的?我无法想象如何构建它...

您可以在此处找到存储库:https://github.com/branhoff/password-tester

我的代码的基本格式主要是注册表单和呈现功能的实际 flask 路由。

password_tester.py

from flask import Flask, render_template, flash
from forms import RegistrationForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'


@app.route("/")
@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Sucess!', 'success')
    return render_template('register.html', title='Register', form=form)

if __name__ == '__main__':
    app.run(debug=True)

forms.py

from flask_wtf import FlaskForm
from wtforms import PasswordField, SubmitField
from wtforms.validators import DataRequired, Length


class RegistrationForm(FlaskForm):
    password = PasswordField('Password', validators=[DataRequired(), Length(min=8)])
    submit = SubmitField('Submit')

我试过的测试 我尝试了以下代码作为测试。但是状态代码总是一样的,不管我把密码改成什么...所以我不太明白如何实际测试结果。

def test_pass_correct(self):
        tester = app.test_client(self)
        response = tester.post('/register', data=dict(password=''))
        self.assertEqual(response.status_code, 200)

这不是很优雅,但在我的html模板中,如果有错误消息,我会打印出来。我可以测试该消息是否在 HTML 语句中的某处。

所以这样的事情似乎可行:

# Ensure that the password-tester behaves correctly given correct credentials
    def test_pass_correct(self):
        tester = app.test_client(self)
        response = tester.post('/register', data=dict(password='testtest'))
        self.assertFalse(b'Field must be at least 8 characters long.' in response.data)

    # Ensure that the password-tester behaves correctly given incorrect credentials
    def test_pass_incorrect(self):
        tester = app.test_client(self)
        response = tester.post('/register', data=dict(password='test'))
        self.assertTrue(b'Field must be at least 8 characters long.' in response.data)