HttpRunner3.X - .env环境变量文件的运用
一、前言
在自动化测试中,有时需要借助环境变量实现某些特定的目的,常见的场景包括:
- 切换测试环境
- 切换测试配置
- 存储敏感数据(从信息安全的角度出发)
二、.env文件设置环境变量
base_url=https://qa1-xxx.cn host=qa1-api.xxng.cn username=李白 password=123456
三、Pytest脚本引用变量案例
在 HttpRunner 3.x版本中内置了函数 ENV
函数读取环境变量的值,引用环境变量使用ENV函数 ${ENV(keyname)}
注:.env
文件必须放到项目根目录(debugtalk.py同一层级)
# NOTE: Generated By HttpRunner v3.1.5 # FROM: har\login.har from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase class TestCaseLogin(HttpRunner): config = Config("登录").verify(False)\ .variables(**{"username":"${ENV(username)}","password":"${ENV(password)}","base_url":"${ENV(base_url)}"}) teststeps = [ Step( RunRequest("登录接口") .post("https://xxx.com/auth/login_password") .with_headers( **{ "content-length": "148", "sec-ch-ua": '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"', "current-department-id": "", "sec-ch-ua-mobile": "?0", "oschannel": "web", "req-agent": "test", "accept": "application/json, text/plain, */*", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36", "current-user-id": "", "content-type": "application/json;charset=UTF-8", "current-user-name": "", "origin":"$base_url", "sec-fetch-site": "cross-site", "sec-fetch-mode": "cors", "sec-fetch-dest": "empty", "referer": "$base_url", "accept-encoding": "gzip, deflate, br", "accept-language": "zh-CN,zh;q=0.9", } ) .with_json( { "employeeName": "$username", "loginType": "PASSWORD", "password": "$password", } ) .extract() .with_jmespath("body.data.userId", "userId") .with_jmespath("body.data.userNo", "userNo") .with_jmespath("body.data.userName", "userName") .validate() .assert_equal("status_code", 200) .assert_equal("body.successful", True) .assert_equal("body.code", "200") .assert_equal("body.message", "请求成功"), ), ] if __name__ == "__main__": TestCaseLogin().test_start()