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

发布于:2023-01-01 ⋅ 阅读:(550) ⋅ 点赞:(0)
68ee9017cf6dbd1c6f753b8e369f82ff.jpeg

本文节选自霍格沃兹测试开发学社内部教材

https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=toutiao×tamp=TIMESTAMP&author=QD


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

实战练习

a444130f1317292595d9f0b34edbdc48.jpeg
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"
}


d1cffb3bd4b14c58fcdad03502797050.jpeg

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

推荐学习

8c2926f3292f39f1845179b764440e17.jpeg

Python App自动化测试训练营全面升级,资深测试开发工程师带你从0到1快速上手APP自动化测试,扫码可领取课程资料哦~

c0895d4e46c3ed1dc648245d441655be.jpeg



网站公告

今日签到

点亮在社区的每一天
去签到