如何在单元测试中将 QuerySelectField 表单数据发送到 Flask 视图?



我正在尝试在我正在处理的烧瓶应用程序中测试编辑和添加视图。部署了网站的一个版本,视图工作正常,但我所做的测试似乎没有正确传递 QuerySelectField 数据。此外,在测试中,我会检查表单数据是否验证并且确实有效,因此它应该通过。

以下是测试:

class TestingWhileLoggedIn(TestCase):
def create_app(self):
app = c_app(TestConfiguration)
return app
# executed prior to each test
def setUp(self):
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
login(self.client, '******', '******')
# executed after each test
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
logout(self.client)
def test_add_post_page_li(self):
p_cat = PostCategory(name='Resources')
p_cat1 = PostCategory(name='Ressdgources')
p_cat2 = PostCategory(name='Ressdgsdgources')
p_cat3 = PostCategory(name='Reurces')
db.session.add(p_cat)
db.session.add(p_cat1)
db.session.add(p_cat2)
db.session.add(p_cat3)
db.session.commit()
all_cats = PostCategory.query.all()
self.assertEqual([p_cat,p_cat1,p_cat2,p_cat3], all_cats)
response = self.client.get('/add_post', follow_redirects=False)
self.assertEqual(response.status_code, 200)
data = dict(title='Hello', content='fagkjkjas', category=p_cat)
form = PostForm(data=data)
# this test passes!
self.assertEqual(form.validate(), True)
# printing the data to see what it is
print(form.data)
response_1 = self.client.post('/add_post', follow_redirects=False, data=form.data, content_type='multipart/form-data')
# this one fails
self.assertEqual(response_1.status_code, 302)
new_post = db.session.query(Post).filter_by(name='Hello').first()
self.assertNotEqual(new_post, None)

下面是测试的终端输出。最后两个失败与我发布的问题是相同的问题,所以我将它们排除在外。

.......................................{'title': None, 'category': None, 'content': None, 'submit': False}
{'title': 'Hello', 'category': <PostCategory 'Resources'>, 'content': 'fagkjkjas', 'submit': False}
{'title': 'Hello', 'category': None, 'content': 'fagkjkjas', 'submit': True}
F.F.......F..
======================================================================
FAIL: test_add_post_page_li (__main__.TestingWhileLoggedIn)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 165, in test_add_post_page_li
self.assertEqual(response_1.status_code, 302)
AssertionError: 200 != 302

字典打印输出来自我注入的一些打印语句,以帮助我理解 问题。第一个词典是当没有表单提交到add_post视图时,第二个词典来自测试,其中显示已填写的类别字段,最后一个词典来自显示未填充类别的add_post视图。

以下是add_post视图:

@blogs.route('/add_post', methods=['GET', 'POST'])
def add_post():
"""
Add a blog post
"""
if not session.get('logged_in'):
return redirect(url_for('other.home'))
form = PostForm()
print(form.data)
if form.validate_on_submit():
new_post = Post(name=form.title.data, content=form.content.data, category_id=form.category.data.id, category=form.category.data)
print('hello')
try:
db.session.add(new_post)
db.session.commit()
except:
# not the best behaviour and should change
return redirect(url_for('other.home'))
return redirect(url_for('other.home'))
return render_template('add_post.html', form=form)

这是包含PostForm的 forms.py 文件

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from ..models import PostCategory
#
# This function is designed to obtain choices for the categories in the PostForm.
#
def category_choices() :
return PostCategory.query

#
# PostForm
# Purpose:
#     Gives the user a way to input information into the post table.
#
# Fields:
#     Title: String Field (Required)
#     Category: QuerySelectField (Required)
#       Obtains the categories from the database. As of right now there exists
#       only two categories (Travel and Projects)
#
#     Content: Text Field (Required)
#     Submit: Submit Field
#
class PostForm(FlaskForm):
"""
Form that lets the user add a new post
"""
title = StringField('Title', validators=[DataRequired()])
category = QuerySelectField('Category', validators=[DataRequired()], query_factory=category_choices)
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Submit')

#
# PostCategoryForm
# Purpose:
#     allows user to add new subcategories
#
# Fields:
#     Name: String Field (Required)
#     Submit: SubmitField
#
class PostCategoryForm(FlaskForm) :
"""
Form used to submit new subcategories
"""
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')

下面是配置文件

import os
from os.path import abspath, dirname, join
# _cwd = dirname(abspath(__file__))
_basedir = os.path.abspath(os.path.dirname(__file__))

TOP_LEVEL_DIR = os.path.abspath(os.curdir)
class Config(object) :
pass
class BaseConfiguration(object):
SQLALCHEMY_TRACK_MODIFICATIONS = False

class ProductionConfiguration(BaseConfiguration):
SQLALCHEMY_DATABASE_URI = '**********************'
SQLALCHEMY_POOL_PRE_PING = True
SQLALCHEMY_ENGINE_OPTIONS = {'pool_recycle' : 3600}
SECRET_KEY = '******************'
UPLOAD_FOLDER = TOP_LEVEL_DIR + '/app/static'

class TestConfiguration(BaseConfiguration):
TESTING = True
WTF_CSRF_ENABLED = False
SECRET_KEY = '*************'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')

在我看来,wtforms在测试环境中没有发送QuerySelectView,但我不知道为什么。任何帮助,不胜感激。

编辑:在我的原始问题中,我没有明确表示这只是具有QuerySelectField的表单的问题。没有 QuerySelectField 的表单正在工作并通过其所有测试。

Flask 不和谐服务器上的一位乐于助人的人能够为我回答这个问题。

问题在于 Flask-wtforms 不会传递模型的整个实例,而只传递主键。解决方案是在数据字典中仅传递主键,如下所示:

class TestingWhileLoggedIn(TestCase):
def create_app(self):
app = c_app(TestConfiguration)
return app
# executed prior to each test
def setUp(self):
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
login(self.client, '******', '*****')
# executed after each test
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
logout(self.client)
def test_add_post_page_li(self):
p_cat = PostCategory(name='Resources')
p_cat1 = PostCategory(name='Ressdgources')
p_cat2 = PostCategory(name='Ressdgsdgources')
p_cat3 = PostCategory(name='Reurces')
db.session.add(p_cat)
db.session.add(p_cat1)
db.session.add(p_cat2)
db.session.add(p_cat3)
db.session.commit()
all_cats = PostCategory.query.all()
self.assertEqual([p_cat,p_cat1,p_cat2,p_cat3], all_cats)
response = self.client.get('/add_post', follow_redirects=False)
self.assertEqual(response.status_code, 200)
# the following line was changed from having category=p_cat to
# category=p_cat.id
data = dict(title='Hello', content='fagkjkjas', category=p_cat.id)
#
# The following code has been commented out since it is no longer needed
#
# form = PostForm(data=data)
#
# this would not pass anymore
# self.assertEqual(form.validate(), True)
#
# printing the data to see what it is
# print(form.data)

# This line was changed from having data=form.data to data=data
response_1 = self.client.post('/add_post', follow_redirects=False, data=data, content_type='multipart/form-data')
# this one fails
self.assertEqual(response_1.status_code, 302)
new_post = db.session.query(Post).filter_by(name='Hello').first()
self.assertNotEqual(new_post, None)

最新更新