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页面采用 表单的形式(文件和参数都在表单中),服务端解析消耗稍微大一些