Newman执行含form-data的Postman测试时GitLab CI/CD中文件找不到
问题:GitLab CI中Newman执行带文件的POST请求失败
我在测试一个需要发送POST请求的API,请求体使用form-data,包含3个文本字段和1张图片。本地测试正常,但在GitLab CI/CD中通过newman run命令执行时,始终找不到文件并出现超时错误。
GitLab CI配置代码片段
newman run Postman_Collections/Media.json -e envtest.json --global-var "file=Images/Test.jpg"
GitLab仓库项目结构
- 测试文件路径:
Project/Images/Test.jpg - Postman集合路径:
Project/Postman_Collections/Media.json - 环境文件路径:
Project/envtest.json
Postman集合相关代码片段
"info": { "_postman_id": "d1c41d43-16c7-40b0-bdec-9d41258bd9ef", "name": "Media", "item": [ { "name": "Test", "item": [ { "name": "Create media file", "event": [ { "listen": "test", "script": { "exec": [ "\"Test 01\"\r", "pm.test(\"Validate status code.\", function () {\r", " pm.response.to.have.status(201);\r", "});" ], "type": "text/javascript", "packages": {} } }, { "listen": "prerequest", "script": { "exec": [ "" ], "type": "text/javascript", "packages": {} } } ], "protocolProfileBehavior": { "disabledSystemHeaders": {} }, "request": { "method": "POST", "header": [ { "key": "Authorization", "value": "ApiKey {{testkey}}", "type": "text" } ], "body": { "mode": "formdata", "formdata": [ { "key": "test", "value": "abc", "type": "text" }, { "key": "documenttype", "value": "test123", "type": "text" }, { "key": "iteminfo", "value": "11243200484648", "type": "text" }, { "key": "file", "type": "file", "src": "Images/Test.jpg" } ] }, "url": { "raw": "localhost:1234/TestMedia", "protocol": "https", "path": [ "api", "MediaAssets" ] } }, "response": [] }
问题排查与解决思路
工作目录与文件拉取检查
GitLab CI默认工作目录为仓库根目录(即Project/),可在newman命令前添加pwd确认当前路径。同时检查.gitignore是否排除了Images/Test.jpg,确保Runner能拉取到该文件。路径变量冲突修正
集合中硬编码了文件路径src": "Images/Test.jpg",但又通过--global-var传递了同名变量,两者未关联。要么删除全局变量参数,确保集合内路径正确;要么将集合中的src改为{{file}},让请求读取全局变量的值。文件权限调整
GitLab Runner执行用户可能无文件访问权限,可在CI脚本中添加chmod 644 Images/Test.jpg赋予可读权限。超时问题根源处理
文件找不到会导致请求无法正常发送,进而触发超时。解决文件路径问题后,再检查API地址:集合中localhost:1234指向Runner容器本身,若API部署在外部需替换为公网/内部可访问地址;若CI中启动服务,需添加等待逻辑(如sleep 10或wait-for-it工具)确保服务完全启动后再执行测试。
内容的提问来源于stack exchange,提问作者Bilawal Wajid Ali
相关产品推荐
相关产品推荐

