1

即使在我的 Web 界面上手动提交表单确实有效,以下测试代码也不会通过。

import os
from flask.ext.testing import TestCase
from flask import url_for

from config import _basedir
from app import app, db
from app.users.models import User


class TestUser(TestCase):

    def create_app(self):
        """
        Required method. Always implement this so that app is returned with context.
        """
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(_basedir, 'test.db')
        app.config['WTF_CSRF_ENABLED'] = False  # This must be disabled for post to succeed during tests
        self.client = app.test_client()
        ctx = app.app_context()
        ctx.push()
        return app

    def setUp(self):
        db.create_all()
        #pass

    @app.teardown_appcontext
    def tearDown(self):
        db.session.remove()
        db.drop_all()
        #pass

    def test_admin_home(self):

        # url is the admin home page
        url = url_for('admin.index')
        resp = self.client.get(url)
        self.assertTrue(resp.status_code == 200)

    def test_admin_registration(self):

        url = url_for('admin.register_view')
        data = {'username': 'admin', 'email': 'admin@example.com', 'password': 'admin'}
        resp = self.client.post(url, data)
        self.assertTrue(resp.status_code == 200)

        u = User.query.filter_by(username=u'admin').first()
        self.assertTrue(u.username == 'admin')   # <----- This fails. Why?

在测试客户端发布到register_viewurl 并返回 200 OK 响应后,我无法从测试数据库中检索“管理员”用户。为什么会这样?

这是视图代码(这是一个烧瓶管理视图)

from flask import request
from flask.ext.admin import expose, AdminIndexView, helpers

from app.auth.forms import LoginForm, RegistrationForm
from app.users.models import User
from app import db


class MyAdminIndexView(AdminIndexView):

    @expose('/', methods=('GET', 'POST'))
    def index(self):
        # handle user login
        form = LoginForm(request.form)
        self._template_args['form'] = form
        return super(MyAdminIndexView, self).index()

    @expose('/register/', methods=('GET', 'POST'))
    def register_view(self):
        # handle user registration
        form = RegistrationForm(request.form)
        if helpers.validate_form_on_submit(form):
            user = User()
            form.populate_obj(user)
            db.session.add(user)
            db.session.commit()

        self._template_args['form'] = form
        return super(MyAdminIndexView, self).index()
4

1 回答 1

3

有史以来最愚蠢的错误。

我的测试代码中的违规行是

resp = self.client.post(url, data)

它应该是

resp = self.client.post(url, data=data)

我设法通过煞费苦心地遍历逻辑并ipdb.set_trace()逐步插入来追踪它,直到我发现我的客户发出的错误 POST 请求。

于 2014-04-09T09:13:39.987 回答