我们一般接口测试工具例如:PostMan、Jmeter都有设置环境变量文件那么在pytest接口自动化框架中如何设置
1、需要对yaml文件进行增、删、改、查需要导入模块`:
先导入模块
import yaml
from ruamel import yaml # pip install ruamel.yaml
2、比如新增&编辑(遇到相同key会进行覆盖):
import yaml
from ruamel import yaml # pip install ruamel.yaml
def add_envoriment(key: str, value):
with open(Environment_YAML_PATH, 'r', encoding='utf-8') as file:
res = yaml.safe_load(file)
key_list = []
if res is None:
res1 = {key: value}
with open(Environment_YAML_PATH, 'a', encoding='utf-8') as file:
yaml.dump(res1, file, default_flow_style=False, encoding='utf-8', allow_unicode=True)
else:
for rv in res:
key_list.append(rv)
if key not in key_list:
res1 = {key: value}
with open(Environment_YAML_PATH, 'a', encoding='utf-8') as file:
yaml.dump(res1, file, default_flow_style=False, encoding='utf-8', allow_unicode=True)
else:
with open(Environment_YAML_PATH, encoding="utf-8") as f:
content = yaml.load(f, Loader=yaml.RoundTripLoader)
# 修改yml文件中的参数
content[f'{key}'] = value
with open(Environment_YAML_PATH, 'w', encoding="utf-8") as nf:
yaml.dump(content, nf, Dumper=yaml.RoundTripDumper, allow_unicode=True)
2、读取对应环境变量的key值:
def read_envoriment(key: str):
with open(Environment_YAML_PATH, 'r', encoding='utf-8') as file:
res = yaml.safe_load(file)
return res[f'{key}']
3、删除对应环境变量的key值:
def del_envoriment(key):
with open(Environment_YAML_PATH, 'r', encoding='utf-8') as file:
res = yaml.safe_load(file)
if res is None:
pass
else:
rev = [item for item in res.keys()]
if key in rev:
del res[f'{key}']
if res is None:
pass
elif res == {}:
clear_envoriment()
else:
with open(Environment_YAML_PATH, 'w', encoding='utf-8') as file:
yaml.dump(res, file, default_flow_style=False, encoding='utf-8', allow_unicode=True)
else:
pass
4、清理yaml文件:
def clear_envoriment():
with open(Environment_YAML_PATH, 'r+', encoding='utf-8') as file:
file.truncate()
这样形成.py文件后我们在使用的过程中只需要导入响应文件和模块,例如现在要存储值:
num = 10
add_envoriment(“num”,num)
这样就能再对应的文件当中看到了
例如:想要读取刚才存入的环境变量key-num
read_envoriment(“num”)就可以了