在服务端自动化测试过程中,文件上传尅性的接口对应的请求头中的content-type为multipart/from-data; boundary=... ,对于这种类型的接口,使用Python的requests或者Java的RestAssured可实现接口测试。
实战演示
实战演示代码如下(Python版和Java版)。
(1)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.test
{
"args":{},
"data":"",
"files":{
"hogwarts_file":"123"
},
"form":{},
//省略
"url":"https://httpbin.ceshiren.com/post"
}
(2)Java演示代码
Java程序中需要使用given()方法提供的multipart()方法实现接口测试,multipart()方法中第一个参数为name,第二个参数是一个File实例对象。File实例化过程中,需要传入上传文件“绝对路径+文件名”。
import java.io.File;
import static io.restassured.RestAssured.*;
public class Requests{
public static void main (Sring[] args){
given().multipart("hogwartsFile",new File("绝对路径+文件名")).
when().post("https://httpbin.ceshiren.com/
post").then().log().all();
}
}
响应内容如下:
{
"args"":{
},
"data":"",
"files":{
"hogwarts_file":"123"
},
"from":{
},
"headers":{
//省略
},
"json":null,
"origin":"119.123.207.174",
"url":"https://httpbin.ceshiren.com/post"
}
使用抓包工具Charles抓取接口参数传递的数据,如图7-5所示。如果是Java程序,name传递的内容为multipart()方法的第一个参数;Python程序中,files参数传递的内容为字典的key值。
搜索微信公众号:TestingStudio霍格沃兹的干货都很硬核