Pytest在烧瓶重量上失效

问题描述 投票:0回答:1

我试图使用pytest测试登录功能,但测试失败了。

实际上,我的项目中的真正问题是,当我尝试将form.validate_on_submit()数据添加到登录表单时,False总是POST(所有form.field.data都是'')。

所以我决定做一个最小的项目来看看发生了什么。

我没有在这里包含数据库,因为数据库在我的真实项目中运行良好,我想弄清楚的是为什么似乎没有数据可以发布。

但是当谈到下面这个最小的项目时,会出现另一个问题:响应的状态代码变成了qazxsw poi。

我已经在这个最小的项目和我的真实项目中设置了404

这个最小的项目结构在这里:

app.config['WTF_CSRF_ENABLED'] = False

test_login.朋友:

.
├── Pipfile
├── Pipfile.lock
├── app.py
├── templates
│   └── login.html
└── tests
    └── test_login.py

app.朋友:

import pytest

from app import create_app


@pytest.fixture(scope='module')
def app():
    app = create_app()
    with app.app_context():
        app.config['WTF_CSRF_ENABLED'] = False
        yield app


@pytest.fixture
def client(app):
    return app.test_client()


def test_login(client):
    response = client.post('/login', data={'username': '1', 'password': '1'})
    # response.status_code is 404 here
    assert response.headers['Location'] == 'http://localhost/'

的login.html:

from flask import Flask, redirect, render_template, url_for
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, SubmitField
from wtforms.validators import DataRequired


class LoginForm(FlaskForm):
    username = StringField(validators=[DataRequired()])
    password = PasswordField(validators=[DataRequired()])
    submit = SubmitField()


def create_app():
    app = Flask('__name__')
    app.config['SECRET_KEY'] = "secretkey"
    return app


app = create_app()


@app.route('/')
def home():
    return 'hello'


@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        return redirect(url_for('home'))
    return render_template('login.html', form=form)

我选择的虚拟环境是<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form method="POST"> {{ form.hidden_tag() }} {{ form.username() }} {{ form.password() }} {{ form.submit() }} </form> </body> </html> pipenv,这是我的pyenv

Pipfile
python flask pytest flask-wtforms wtforms
1个回答
0
投票

事实证明我没有正确使用工厂模式。应使用[[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] pytest = "*" [packages] flask-wtf = "*" [requires] python_version = "3.7" 并在工厂注册应用程序。有关详细信息,请查看此Blueprint

© www.soinside.com 2019 - 2024. All rights reserved.