在API接口自动化测试过成中,经常会遇到上传文件的接口,那么在Karate框架中如何实现上传文件接口的自动化哪?今天我就将个人积累的小经验分享给大家; 【如果大家对karate还不熟悉,请参考我之前的写的培训教程,karate系列教程】 具体步骤如下: 第一步:我们需要知道上传接口的信息,我们以nGrinder上传脚本接口为例,我们打开nGrinder地址, 按 F12 ,抓取上传接口报文【这个是做API测试的基本功这里步多说,直接上图】 查看请求报文体 【上图中的数字1,2,3是Karate-脚本中需要用到的内容,具体】
第二步:karate 上传文件的方法是 “multipart file“ 格式如下 multipart file myFile = { read: ‘test.pdf’, filename: ‘upload-name.pdf’, contentType: ‘application/pdf’ } myFile-就是上图中的1, filename-就是上图中的2, contentType-就是上图中的3 参数详解: read:必填 需要上传的文件本地路径,classpath:可以指定classpath 。是必须的,除非value使用。 value:【和read作用相同】主要用于上传 JSON 或 XML csv等。 filename: 可选,如果没有指定,将没有filename属性Content-Disposition contentType: 可选,默认为application/octet-stream 【可以参考下面的Demo-包含了多种类型的文件上传】
Feature:
Karate-上传文件Demo
Background:
* def nGrinderInfo = read('/Users/perfEnvInfo.json')
* def uploadFileinfo = {"scriptName":"SendDataToZabix","description":"测试上传","filePath":"/Users/zhujiefu_1/Downloads/AutoTestLib_old.jar"}
* def filename = ((uploadFileinfo.filePath).split("/")[uploadFileinfo.filePath.split("/").length-1])
* print filename
* url 'http://10.0.11.57'
Scenario:
* def timtemp = (''+new Date().getTime())
#上传CSV
#* def filename = "SendDataToKafkabyJeff.csv"
Given url '/script/api/upload',uploadFileinfo.scriptName,'/resources'
And headers ngrinderHeader
And params {"description":"#(uploadFileinfo.description)","__timestap":"#(timtemp)"}
#file-为Body中字段名称,value为上传文件内容,filename 为文件名,contentType 为文件类型【可从请求体中看到】;
And multipart file uploadFile = {value: "#(karate.readAsString(uploadFileinfo.filePath))",filename: "#(filename)", content_type: 'text/csv' }
When method post
Then status 200
And match response contains {"success":true}
#上传groovy
@upscript
Scenario:
Given path '/script/api/upload',uploadFileinfo.scriptName
And headers ngrinderHeader
And params {"description":"#(uploadFileinfo.description)","__timestap":"#(timtemp)"}
And multipart file uploadFile = {read: "#(uploadFileinfo.filePath)",filename: '#(filename)', content_type: 'application/octet-stream' }
When method post
Then status 200
And match response contains {"success":true}
#上传 jar包
@uplib
Scenario:
Given path '/script/api/upload',uploadFileinfo.scriptName,'/lib'
And headers ngrinderHeader
And params {"description":"#(uploadFileinfo.description)","__timestap":"#(timtemp)"}
And multipart file uploadFile = {read: "#(uploadFileinfo.filePath)",filename: "#(filename)", content_type: 'application/java-archive' }
When method post
Then status 200
And match response contains {"success":true}
|