【问题标题】:Flask Redirect Returns 200 Instead of 302Flask 重定向返回 200 而不是 302
【发布时间】:2015-12-28 02:43:08
【问题描述】:

我正在为 Flask 应用程序编写单元测试,但不确定为什么响应返回状态代码 200 而不是 302。我正在测试的视图使用重定向,并且我的帖子设置了 follow_redirects=False

下面是测试和查看代码:

#test_views.py
def test_can_post_new_engagement(self):
        response = self.client.post(
                    url_for('main.new_engagement'),
                    data={
                        'title': 'Sample Title',
                        'client': 1},
                    follow_redirects=False)
    self.assertEqual(response.status_code, 302)

#views.py
@main.route('/engagement/new', methods=['GET', 'POST'])
def new_engagement():
    form = EngagementForm()
    form.client.choices = [(o.id, o.official_name) for o in
                           Organization.query.order_by('official_name')]
    form.client.choices.insert(0, (0, '--- Select Organization ---'))
    if form.validate_on_submit():
        eng = Engagement(title=form.title.data,
                         client_id=form.client.data)
        db.session.add(eng)
        return redirect(url_for('main.new_pentest'))
    return render_template('engagement_form.html', form=form)

错误:

 FAIL: test_can_post_new_engagement (test_views.NewEngagementView)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
    File "/home/ramces/dev/global_engagement_manager/tests/unit/test_views.py
    ", line 36, in test_can_post_new_engagement
       self.assertEqual(response.status_code, 302)
AssertionError: 200 != 302

【问题讨论】:

    标签: python flask python-unittest


    【解决方案1】:

    分辨率

    首先,正如 Wombatz 建议的那样,我没有意识到我的表单没有通过 form.validate_on_submit()

    经过一点调试,我意识到我的测试配置中缺少 CSRF 令牌,因此添加 WTF_CSRF_ENABLED = False 解决了这个问题。

    【讨论】:

      【解决方案2】:

      烧瓶重定向函数确实返回带有代码302的响应

      from flask import redirect
      print(redirect("some_url").status_code)  # 302
      

      您的测试可能失败,因为您的表单验证失败。 你能确定你确实进入了 if 分支吗?

      一个问题可能是您的client SelectField(假设您使用wtforms)使用int 作为键。确保在字段的构造函数中提供coerce=int

      我使用的是flask版本0.10.1

      注意:这可能应该是一个评论,但 SO 告诉我我需要 50 代表才能发表评论。但是当然可以发布答案。

      【讨论】:

      • 看来我昨天在屏幕前花了太多时间。 :) 表格没有正确验证。强制设置为 int... 问题是别的。感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 2011-05-16
      • 2011-03-25
      • 2018-05-28
      • 2023-04-09
      • 2011-11-09
      • 2023-03-21
      • 2012-02-04
      • 1970-01-01
      相关资源
      最近更新 更多