httprunner 2.x学习20 - env环境变量有#注释和空行处理
Posted 上海-悠悠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httprunner 2.x学习20 - env环境变量有#注释和空行处理相关的知识,希望对你有一定的参考价值。
前言
httprunner用.env 文件管理环境变量,但是必须是严格是key=value格式,如果加# 注释就会用例解析失败。
问题描述
问题版本:v2.5.9
问题描述:
.env
文件中带有#号注释
# 用户名
user = test1
运行用例的时候会报错:.env format error
主要原因是默认只能解析key=value格式的数据
解决办法
先看对应的源码,在httprunner.loader.load.py文件中找到
def load_dot_env_file(dot_env_path):
"""load .env file.
Args:
dot_env_path (str): .env file path
Returns:
dict: environment variables mapping
"UserName": "debugtalk",
"Password": "123456",
"PROJECT_KEY": "ABCDEFGH"
Raises:
exceptions.FileFormatError: If .env file format is invalid.
"""
if not os.path.isfile(dot_env_path):
return
logger.log_info("Loading environment variables from ".format(dot_env_path))
env_variables_mapping =
with io.open(dot_env_path, "r", encoding="utf-8") as fp:
for line in fp:
# maxsplit=1
if "=" in line:
variable, value = line.split("=", 1)
elif ":" in line:
variable, value = line.split(":", 1)
else:
raise exceptions.FileFormatError(".env format error")
env_variables_mapping[variable.strip()] = value.strip()
utils.set_os_environ(env_variables_mapping)
return env_variables_mapping
可以看到关键代码部分
if "=" in line:
variable, value = line.split("=", 1)
elif ":" in line:
variable, value = line.split(":", 1)
按每行读取后以等号"=“或冒号”:"分割。
只需加两行代码即可解决
def load_dot_env_file(dot_env_path):
"""load .env file.
Args:
dot_env_path (str): .env file path
Returns:
dict: environment variables mapping
"UserName": "debugtalk",
"Password": "123456",
"PROJECT_KEY": "ABCDEFGH"
Raises:
exceptions.FileFormatError: If .env file format is invalid.
"""
if not os.path.isfile(dot_env_path):
return
logger.log_info("Loading environment variables from ".format(dot_env_path))
env_variables_mapping =
with io.open(dot_env_path, "r", encoding="utf-8") as fp:
for line in fp:
if line.startswith("#") or "=" not in line:
# 忽略空行和# 注释行
continue
# maxsplit=1
if "=" in line:
variable, value = line.split("=", 1)
elif ":" in line:
variable, value = line.split(":", 1)
else:
raise exceptions.FileFormatError(".env format error")
env_variables_mapping[variable.strip()] = value.strip()
utils.set_os_environ(env_variables_mapping)
return env_variables_mapping
以上是关于httprunner 2.x学习20 - env环境变量有#注释和空行处理的主要内容,如果未能解决你的问题,请参考以下文章
httprunner 2.x学习16 - 调用HttpRunner类执行用例