[Flask] pytest 文件上传单元测试

http 小文件上传的接口一般采用 表单形式的上传(http post) 或者是 stream 的直接上传 (http put), 用flask实现了上传接口之后就需要测试,怎么造请求折腾了一会,下面记录下代码片段

test_upload.py

# coding:utf-8
from cStringIO import StringIO
import pytest
from ..server import app


@pytest.fixture
def client(request):
    test_client = app.test_client()

    def teardown():
        pass

    request.addfinalizer(teardown)
    return test_client


def test_post_upload(client):
    files = {'file': StringIO(b"post-data")}
    params = {name: (f, "mocked_name_{}".format(name)) for
              name, f in files.items()}
    params['bucket'] = 'test'
    params['keyname'] = 'mocaked_name_test'
    params['content_type'] = 'text/csv'
    res = client.post('/upload/key', data=params,
                      content_type='multipart/form-data')
    assert res.status_code == 200


def test_put_upload(client):
    headers = {
        "Content-MD5": "",
        "Content-Type": "text/csv",
        "x-elmeast-bucket": 'test',
        "x-elmeast-key": 'moack_name_test'
    }
    res = client.put('/upload/key',
                     input_stream=StringIO(b'put-data'),
                     headers=headers)
    assert res.status_code == 200

上面两个用例如果采用 curl,命令参数类似下面

# 采用 multipart/form-data; 方式 POST方法
curl -v -X post -F "data=@dump.rdb" -F "bucket=test" -F "key=test1" -F "md5=xxx" 'http://localhost:5003/upload/key'

# PUT 方法
$ curl -v --upload-file dump.rdb -H 'x-elmeast-bucket:test' 'http://localhost:5003/upload/key'

一般 restful 风格的上传使用 PUT 方式,参数一般放在 header 上,web页面采用 表单的形式(文件和参数都在表单中),服务端解析消耗稍微大一些

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值