微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

技术分享 | 接口自动化测试中,文件上传该如何测试?

在服务端自动化测试过程中,文件上传类型的接口对应的请求头中的 content-type 为 multipart/form-data; boundary=…,碰到这种类型的接口,使用 Java 的 REST Assured 或者 Python 的 Requests 均可解决

实战练习

Python 版本

在 Python 版本中,可以使用 files 参数上传文件,files 要求传递的参数内容为字典格式,key 值为上传文件名,value 通常要求传递一个二进制模式的文件流。

>>> url = 'https://httpbin.ceshiren.com/post' >>> files = {"hogwarts_file": open("hogwarts.txt", "rb")} >>> r = requests.post(url, files=files) >>> r.text { "args": {}, "data": "", "files": { "hogwarts_file": "123" }, "form": {}, ...省略... "url": "https://httpbin.ceshiren.com/post" }

Java 版本

Java 需要使用 given() 方法提供的 multiPart() 方法,第一个参数为 name, 第二个参数需要传递一个 File 实例对象,File 实例化过程中,需要传入上传文件绝对路径+文件名。

import java.io.File; import static io.restassured.RestAssured.*; public class Requests { public static void main(String[] args) { given().multiPart("hogwartsFile", new File("绝对路径+文件名")). when().post("https://httpbin.ceshiren.com/post").then().log().all(); } }

响应内容

{ "args": { }, "data": "", "files": { "hogwarts_file": "123" }, "form": { }, "headers": { ...省略... }, "json": null, "origin": "119.123.207.174", "url": "https://httpbin.ceshiren.com/post" }

f627ee95a22cbd4f277b879c53c6c3a4.png

image1080×224 26.5 KB

使用抓包工具抓取过程数据数据,可以清楚看到传递数据过程中,如果是 Java 版本,name 传递内容为 multiPart() 方法的第一个参数,在 Python 版本中为 files 参数传递的字典的 key 值,而 filename 不论是 Java 版本还是 Python 版本,传递的内容均为传递文件文件名。

原文地址:https://www.jb51.cc/wenti/3283782.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐