关于软件测试:技术分享-接口自动化测试中文件上传该如何测试

3次阅读

共计 1142 个字符,预计需要花费 3 分钟才能阅读完成。

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

实战练习

Python 版本

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

url = ‘https://httpbin.ceshiren.com/…’ >>> 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” }

​编辑 image1080×224 26.5 KB

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

正文完
 0