软件测试 | 测试开发 | 接口自动化测试中,文件上传该如何测试?

167 阅读1分钟

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

实战练习

Python 版本

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

` url = '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": "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("httpbin.ceshiren.com/post").then…);

}

}

响应内容为

{ "args": { },

"data": "",

"files": {

"hogwarts_file": "123"

},

"form": { }, "headers": {

...省略...

},

"json": null,

"origin": "119.123.207.174",

"url": "httpbin.ceshiren.com/post"

}

编辑切换为居中

添加图片注释,不超过 140 字(可选)

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