Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Flask重定向返回200而不是302_Python_Flask_Python Unittest - Fatal编程技术网

Python Flask重定向返回200而不是302

Python Flask重定向返回200而不是302,python,flask,python-unittest,Python,Flask,Python Unittest,我正在为一个Flask应用程序编写单元测试,不知道为什么响应返回状态代码200而不是302。我正在测试的视图使用重定向,我的帖子设置了follow\u redirects=False 以下是测试和查看代码: #test_views.py def test_can_post_new_engagement(self): response = self.client.post( url_for('main.new_engagement'),

我正在为一个Flask应用程序编写单元测试,不知道为什么响应返回状态代码200而不是302。我正在测试的视图使用重定向,我的帖子设置了
follow\u 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

烧瓶重定向功能返回代码为
302的响应

from flask import redirect
print(redirect("some_url").status_code)  # 302
您的测试可能失败,因为表单验证失败。 你能确定你确实进入了if分支吗

一个问题可能是您的
客户端
选择字段
(假设您使用的是
wtforms
)使用
int
作为键。确保在字段的构造函数中提供
concurve=int

我使用的是flask版本0.10.1


注意:这可能是一个评论,但告诉我在评论之前我需要50个代表。当然,发布答案是可以的。

分辨率

首先,正如Wombatz所建议的,我没有意识到我的表单没有传递
form.validate\u on\u submit()


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

昨天我似乎在屏幕前花了太多时间。:)表单未正确验证。强制设置为int。。。问题是别的。谢谢你的帮助!