如何在Flask中测试重定向到创建的实例

时间:2015-01-17 09:24:23

标签: python unit-testing flask flask-sqlalchemy flask-testing

views.py中有以下功能:

def ask_question():
        form = QuestionForm()
        if form.validate_on_submit():
            question = Question(title=form.title.data, text=form.text.data)
            db.session.add(question)
            db.session.commit()
            return redirect('/questions/%d/' % question.id)
        return render_template('ask_question.html', form=form)

如何获取已创建模型的ID以将其置于断言中?

def test_can_post_question(self):
    response = self.tester.get('/new-question')
    self.assert_200(response)
    form = self.get_context_variable('form')
    self.assertIsInstance(form, QuestionForm)
    response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?',
                                                       'text': 'What is it?'})
    self.assertRedirects(response, '/questions/%d' % created_question.id)
                                                     #^ how can I get id of created model here?

我正在使用Flask,Flask-SQLAlchemy,Flask-Testing

1 个答案:

答案 0 :(得分:1)

查询创建的问题对象。作为副作用,您可以测试问题是否已创建。

...
q = Question.query.filter_by(title='What about somestuff in Flask?').first()
self.assertRedirects(response, '/questions/%d/' % q.id)