httprunner2.x--上传图片:file-like-objects 方式
文件上传,在 HttpRunner 中可以使用两种方式来实现:
- 通过 requests 模块约定方法上传文件
- 通过 requests_toolbelt 方式上传文件
通过 requests 模块约定方法上传文件
我们知道 HttpRunner 实际是对 requests 模块的封装,而 requests 本身就支持了文件的上传功能,所以可以在 HttpRunner 中直接使用相同的文件上传方式。
先查看 HttpRunner 中 client.py 文件源码对文件上传的说明:
- 必须使用 multipart 方式上传文件
- 上传参数格式为:'filename': file-like-objects
源码:\httprunner-2.4.3\httprunner\client.py
class HttpSession(requests.Session): .......... def request(self, method, url, name=None, **kwargs): """ ....................... :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. ...................... """
再解读 request 模块的相关内容,其中对上传文件的定义方式为:
Requests官方说明:
POST一个多部分编码(Multipart-Encoded)的文件
>>> url = 'http://httpbin.org/post' >>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files
综合 HttpRunner 和 Request 的内容,二者对上传文件的解释是一致的:
- HttpRunner: Dictionary of ``'filename': file-like-objects`` for multipart encoding upload.
- Requests: {'file': open('report.xls', 'rb')}
补充:file-like Object
如果某个函数返回的对象中包含有一个 read() 方法,则该对象在Python中统称为file-like Object。
如下面例子,返回的对象 f 自带一个 read() 方法,则 f 称之为 file-like Object。
with open('/path/file', 'r') as f: print f.read()
再看 requests的源码:
requests-2.23.0\requests\api.py
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. ............ :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. """
从以上源码分析中,我们又可以看出,上传文件的参数有两种表示形式:
1-dict方式: 'name': file-like-objects
2-tuple方式: 'name': file-tuple
- 2-tuple ``('filename', fileobj)
- 3-tuple ``('filename', fileobj, 'content_type')
- 4-tuple ``('filename', fileobj, 'content_type', custom_headers)
其中方式1使用“file-like-objects”定义参数类型,需要提前定义好一个函数,并且在此函数中要返回一个打开待上传文件的 open()方法。
在 debugtalk.py 文件中定义函数,返回一个 file-like-objects 的对象:
def get_file(filepath): return open(filepath, 'rb')
注:
- 函数必须定义在 debugtalk.py 文件中(不要修改文件名)。
- 在测试用例中调用函数的格式如下,其中变量名用于接收函数的返回值:
变量名: ${函数名(参数)}
api文件
name: upload file request: url: http://graph.baidu.com/upload method: POST #上传图片 files: image: $p_fileobj validate: - eq: ["status_code", 200]
测试用例
config: name: 百度上传文件 variables: p_filepath: '.\\kenan.jpg' p_fileobj: ${get_file($p_filepath)} teststeps: - name: step 1 api: api/baiduUpload.yml validate: - eq: ["status_code", 200] - eq: [content.msg, Success]
查看报告