如何在多份Artillery YAML文件中共享全局URI并通过package.json运行?
解决Artillery多测试文件共享Target的环境变量配置问题
我明白你的需求——要在多个Artillery测试.yml文件里复用同一个Target配置,而且是通过package.json的scripts来执行测试,不想每次手动输入环境变量对吧?这其实很容易搞定,分几步来:
1. 修改Artillery测试文件的Target配置
在每个测试.yml的config段中,把固定的target值替换成环境变量模板引用,让Artillery自动读取环境变量的值:
config: target: "$processEnvironment.TEST_TARGET" # 保留你的其他config配置(比如phases、defaults等) scenarios: # 你的场景定义内容...
2. 在package.json的scripts中配置环境变量
这里分两种方式,你可以根据项目的运行平台选择:
方式一:针对不同系统直接编写
- Linux/macOS(bash/zsh环境):在script命令前直接前置环境变量:
{ "scripts": { "test:prod": "TEST_TARGET=https://prod-api.example.com artillery run test-prod.yml", "test:staging": "TEST_TARGET=https://staging-api.example.com artillery run test-staging.yml" } }
- Windows(CMD命令行):用
set命令设置环境变量,再衔接测试命令:
{ "scripts": { "test:prod": "set TEST_TARGET=https://prod-api.example.com && artillery run test-prod.yml" } }
- Windows(PowerShell):语法略有区别,用
$env:前缀设置变量:
{ "scripts": { "test:prod": "$env:TEST_TARGET='https://prod-api.example.com'; artillery run test-prod.yml" } }
方式二:用cross-env实现跨平台兼容
如果你的项目需要在Windows、Linux、macOS上都能运行,推荐用cross-env包统一环境变量的设置逻辑:
- 先安装依赖:
npm install --save-dev cross-env
- 修改package.json的scripts:
{ "scripts": { "test:prod": "cross-env TEST_TARGET=https://prod-api.example.com artillery run test-prod.yml", "test:staging": "cross-env TEST_TARGET=https://staging-api.example.com artillery run test-staging.yml" } }
这样不管什么系统,运行npm run test:prod都会正确加载对应的Target值。
3. 验证配置是否生效
你可以在测试文件的scenario里加个简单的日志输出,确认Target是否正确读取:
scenarios: - name: "Check Target" flow: - log: "当前使用的Target: {{ $processEnvironment.TEST_TARGET }}"
运行测试后,控制台会打印出当前的Target值,就能确认配置生效了。
内容的提问来源于stack exchange,提问作者physicsboy
相关产品推荐
相关产品推荐

