pytest -- 基于pytest-variables插件的环境变量配置
前言:
典型的软件开发生命周期通常都是“开发环境 -> 测试环境 -> 预发布环境 -> 正式环境”这样的,而接口自动化测试通常会在测试环境和预发布环境。
环境 | 是否运行接口自动化测试 | 说明 |
---|---|---|
开发环境(Development) | ❌ 一般不运行 | 代码未稳定,接口频繁变动 |
测试环境(Test/QA) | ✅主要运行环境 | 功能完整,用于回归测试和质量验证 |
预发布环境(Staging) | ✅关键运行环境 | 与生产环境高度一致,用于上线前最终验证 |
正式环境(Production) | ⚠️极少数情况运行 | 风险高通常禁止,除非是监控类“冒烟测试” |
方案:
使用 pytest-variables 插件 + YAML 文件管理多环境配置
1、安装插件
pip install pytest-variables
2、创建项目结构和YAML配置文件
project/
├── config/ # 配置文件
├── utils/ # 工具类
├── data/ # 测试数据(yaml/json/excel)
├── environments/ # 环境配置
│ ├── test.yml # 测试环境
│ └── preprod.yml # 预发布环境
├── testcases/ # 测试用例目录
│ ├── test_login.py
│ └── test_register.py
├── conftest.py # 全局 fixture
├── pytest.ini # pytest 配置文件
├── run.py # 启动脚本(可选)
└── requirements.txt # 依赖文件
# test.yml
base_url: "https://test.api.xxxx.com"
api_key: "test_key_123456"
timeout: 5
db_config:
host: "test.db.xxxx.com"
port: 3306
username: "test_user"
# preprod.yml
base_url: "https://pre.api.xxxx.com"
api_key: "pre_key_123456"
timeout: 5
db_config:
host: "pre.db.xxxx.com"
port: 3306
username: "pre_user"
3、配置 pytest.ini 设置默认环境
可通过修改这个variables变量值来控制环境
[pytest]
# addopts: 指定运行 pytest 时默认附加的命令行选项
addopts =
--variables environments/test.yml
4、通过命令行切换环境
如果不想频繁修改pytest.ini文件,运行测试时也可指定不同的 YAML 文件:
# 使用测试环境配置
pytest --variables config/test.yaml
# 使用生产环境配置
pytest --variables config/prod.yaml
# 使用默认开发环境配置
pytest
5、在测试用例中访问配置变量
方式一:直接通过 variables fixture 访问
def test_api(variables):
base_url = variables["base_url"]
response = requests.get(f"{base_url}/users",
headers={"API-KEY": variables["api_key"]})
assert response.status_code == 200
这个直接使用的方式比较直接,适合用于小型项目。
方式二:通过自定义 fixture 封装(推荐)
在 conftest.py 中添加:
import pytest
@pytest.fixture(scope="session")
def api_config(variables):
"""封装API相关配置"""
return {
"base_url": variables["base_url"],
"headers": {
"API-KEY": variables["api_key"],
"Content-Type": "application/json"
},
"timeout": variables["timeout"]
}
@pytest.fixture(scope="session")
def db_config(variables):
"""封装数据库相关配置"""
return variables["db_config"]
然后在测试用例中使用:
def test_api(api_config):
response = requests.get(
f"{api_config['base_url']}/users",
headers=api_config["headers"],
timeout=api_config["timeout"]
)
assert response.status_code == 200
def test_db_connection(db_config):
# 使用db_config连接数据库测试
assert db_config["host"] == "test.db.xxxx.com"
通过自定义 fixture
封装注入,通过 api_config
、db_config
等命名明确的 fixture
,一目了然直观的看出具体配置,通过 @pytest.fixture(scope="session")
缓存配置,可以避免重复加载。
评论区