如何在GitHub Action触发的Postman集合中正确加载输入文件?
解决GitHub Action中Newman加载Git仓库测试文件的问题
问题背景
需在GitHub Action触发的Postman集合中加载Git仓库内的测试文件,实现两种请求发送方式:
- 作为请求原始请求体发送至服务器
- 作为多部分文本文件输入发送至服务器
当前使用的Newman运行命令:
- name: Run API Tests id: run-newman run: newman run postman/foo.postman_collection.json -r cli --color on -e postman/${{ needs.build.outputs.tenant_name }}.postman_environment.json
执行时测试用例失败,报错信息:
→ Upload Image ┌ │ 'Form param `file`, file load error: "/Users/user/Downloads/20230823112156.png", no such file'
核心问题是Postman集合中硬编码了本地文件路径,而GitHub Action运行环境为全新容器,无法访问本地路径,需改用Git仓库内的相对路径加载文件。
解决方案
1. 替换Postman集合中的文件路径
将集合内所有文件引用改为相对于Git仓库根目录的相对路径(比如测试文件存放在test-data/目录下,路径就写./test-data/xxx.png)。
针对两种请求方式的具体配置:
方式1:作为原始请求体发送
在Postman请求的「Body」标签选择「raw」,添加Pre-request Script读取文件内容:const fs = require('fs'); const filePath = './test-data/your-test-file.txt'; // 相对仓库根目录的路径 pm.request.body.raw = fs.readFileSync(filePath, 'utf8');方式2:作为多部分文本文件输入发送
在Postman请求的「Body」标签选择「form-data」,找到file参数,将「File」选项中的路径替换为相对路径(如./test-data/20230823112156.png),保存集合。
2. 确保GitHub Action拉取完整仓库
在工作流的checkout步骤中,确保拉取整个仓库内容(默认已支持,有子模块需额外配置):
- name: Checkout repository uses: actions/checkout@v4 # 若仓库包含子模块,添加: # with: # submodules: true
3. (可选)通过环境变量动态传递文件路径
如果需要灵活切换测试文件,可在Newman命令中通过--env-var传递路径变量:
- name: Run API Tests id: run-newman run: | newman run postman/foo.postman_collection.json \ -r cli --color on \ -e postman/${{ needs.build.outputs.tenant_name }}.postman_environment.json \ --env-var "test_file_path=./test-data/20230823112156.png"
之后在Postman集合中用{{test_file_path}}作为文件路径的变量引用即可。
验证
将修改后的Postman集合和测试文件提交至Git仓库,重新触发GitHub Action工作流,确认文件可被正确加载、测试用例执行成功。
内容的提问来源于stack exchange,提问作者user352290
相关产品推荐
相关产品推荐

