python - flask 测试客户端 : Testing DELETE request with data

标签 python unit-testing flask werkzeug

我正在尝试使用来自 http://flask.pocoo.org/docs/testing/ 的建议来测试我的 Flask 应用程序,但我无法弄清楚如何使用表单数据测试 DELETE 方法。

我的删除方法看起来像这样:

from flask.ext.restful import Resource, reqparse 
...
def delete(self):
    self.reqparse.add_argument('arg1', type=str, required=True, location='form')
    args = self.reqparse.parse_args()
    ...

我想测试一下:

def setUp(self):
    self.app = myApp.app.test_client()

def test_delete(self):
    rv = self.app.delete('MyEndPoint', data={'arg1', 'val'})

但它不起作用。我还在 werkzeug.test 中查看了 EnvironBuilder 的源代码,但仍然不知道如何传递数据。

最佳答案

我刚遇到同样的问题,这主要是因为 Werkzeug 的测试方法目前不支持设置 DELETE 请求的 content_type

代码here展示了 Werkzeug 如何获取内容类型:

def _get_content_type(self):
    ct = self.headers.get('Content-Type')
    if ct is None and not self._input_stream:
        if self.method in ('POST', 'PUT', 'PATCH'):
            if self._files:
                return 'multipart/form-data'
            return 'application/x-www-form-urlencoded'
        return None
    return ct

如果没有 content_type,那么表单数据永远不会从 environ 中进入请求,因此您的 Flask 服务器实际上不会发送数据.

最终,这是 Werkzeug 的一个错误,因为您可以制作一个使用 DELETE 方法并包含表单数据的 curl 请求。我已经向 Werkzeug 存储库提交了一个拉取请求来解决这个问题。欢迎在 github 上发表意见:https://github.com/mitsuhiko/werkzeug/pull/620

更新:同时要实际解决您的问题,您可以通过在请求中明确说明内容类型来解决这个问题,如下所示:

def test_delete(self):
    rv = self.app.delete('MyEndPoint',
                         data={'arg1', 'val'},
                         headers={'Content-Type': 'application/x-www-form-urlencoded'})

再次更新:我提交的拉取请求已经过审查、完善和合并,并将包含在 Werkzeug 的 0.10 版本中,希望这不再是问题:)

关于python - flask 测试客户端 : Testing DELETE request with data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24073488/

相关文章:

来自 ANTLR 解析树的 Python AST?

python - 我可以使用 'eval' 在 Python 中定义函数吗?

python - 类似于numpy的diff的功能

unit-testing - 在 Mathematica Notebook 中编写单元测试的好模式是什么?

python - Flask-SQLAlchemy - 模型没有属性 'foreign_keys'

python - 收到一封没有回复历史记录的电子邮件

javascript - 如何使用Jasmine测试用例覆盖Marionette View的事件?

unit-testing - 如何在 Camel 中对这个路由构建器进行单元测试?

python - 分发本地 Flask 应用程序

python - Flask-SQLAlchemy 和 Flask-ReSTLess 不取孙子