如何将QuerySelectField表单数据发送到unittest中的Flask视图?

2024-09-28 05:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我正在开发的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视图,其中显示未填充的类别

以下是“添加帖子”视图:

@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的表单正在工作并通过所有测试


Tags: thenameselfformaddappnewdb
1条回答
网友
1楼 · 发布于 2024-09-28 05:28:11

Flask discord服务器上的一位有帮助的人能够为我回答这个问题

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

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)

相关问题 更多 >

    热门问题