重构环境变量文件及方法
This commit is contained in:
parent
7c2b60455a
commit
6dba7a1c33
|
@ -19,7 +19,7 @@ from requests.structures import CaseInsensitiveDict
|
||||||
from common.base_log import logger
|
from common.base_log import logger
|
||||||
from common.exceptions import ValueTypeError
|
from common.exceptions import ValueTypeError
|
||||||
from common.models import Method
|
from common.models import Method
|
||||||
from configs.lins_environment import EntryPoint
|
from configs.env_config import EnvConfig
|
||||||
from utils.MIME_type_classifier import get_MIME
|
from utils.MIME_type_classifier import get_MIME
|
||||||
from utils.allure_handle import allure_attach_text, allure_attach_json, allure_attach_file
|
from utils.allure_handle import allure_attach_text, allure_attach_json, allure_attach_file
|
||||||
from utils.time_utils import TimeUtil
|
from utils.time_utils import TimeUtil
|
||||||
|
@ -35,7 +35,7 @@ class BaseApi:
|
||||||
if address.lower().startswith("http"):
|
if address.lower().startswith("http"):
|
||||||
return address
|
return address
|
||||||
# 确保host不以/结尾
|
# 确保host不以/结尾
|
||||||
host = EntryPoint.URL().rstrip("/")
|
host = EnvConfig.URL().rstrip("/")
|
||||||
# 确保address是以/开头
|
# 确保address是以/开头
|
||||||
address = "/" + address.lstrip("/")
|
address = "/" + address.lstrip("/")
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@ class BaseApi:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _make_headers(headers) -> dict[Any, Any]:
|
def _make_headers(headers) -> dict[Any, Any]:
|
||||||
"""对请求头进行预处理"""
|
"""对请求头进行预处理"""
|
||||||
default_headers = EntryPoint.DEFAULT_HEADERS()
|
default_headers = EnvConfig.DEFAULT_HEADERS()
|
||||||
headers = headers or {}
|
headers = headers or {}
|
||||||
merged_headers = {**default_headers, **headers}
|
merged_headers = {**default_headers, **headers}
|
||||||
return merged_headers
|
return merged_headers
|
||||||
|
|
|
@ -10,7 +10,7 @@ import pymysql
|
||||||
from dbutils.pooled_db import PooledDB
|
from dbutils.pooled_db import PooledDB
|
||||||
|
|
||||||
from common.base_log import logger
|
from common.base_log import logger
|
||||||
from configs.lins_environment import EntryPoint
|
from configs.env_config import EnvConfig
|
||||||
|
|
||||||
|
|
||||||
class Postgresql:
|
class Postgresql:
|
||||||
|
@ -176,7 +176,7 @@ if __name__ == '__main__':
|
||||||
# with Postgresql(db_config) as db:
|
# with Postgresql(db_config) as db:
|
||||||
# db.execute_query("SELECT * FROM mytable")
|
# db.execute_query("SELECT * FROM mytable")
|
||||||
|
|
||||||
db_config = EntryPoint.DB_CONFIG()
|
db_config = EnvConfig.DB_CONFIG()
|
||||||
with MySQL(db_config) as db:
|
with MySQL(db_config) as db:
|
||||||
query = "SELECT * FROM student WHERE name = '张三'"
|
query = "SELECT * FROM student WHERE name = '张三'"
|
||||||
result = db.execute_query_with_result(query)
|
result = db.execute_query_with_result(query)
|
||||||
|
|
|
@ -0,0 +1,92 @@
|
||||||
|
# !/usr/bin/python
|
||||||
|
# -*- coding:utf-8 -*-
|
||||||
|
# @Time : 2022/7/7 11:40
|
||||||
|
# @Author : wangjie
|
||||||
|
# @File : env_config.py
|
||||||
|
# @project : SensoroApi
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
from common.settings import ENV
|
||||||
|
from utils.command_parser import command_parser
|
||||||
|
|
||||||
|
|
||||||
|
class DevConfig:
|
||||||
|
"""开发环境配置"""
|
||||||
|
URL = "https://dev.com"
|
||||||
|
DEFAULT_HEADERS = {}
|
||||||
|
|
||||||
|
|
||||||
|
class TestConfig:
|
||||||
|
"""测试环境配置"""
|
||||||
|
URL = "https://www.wanandroid.com"
|
||||||
|
DEFAULT_HEADERS = {
|
||||||
|
'Content-Type': 'application/json;charset=UTF-8',
|
||||||
|
'accept-language': 'zh-CN,zh;q=0.9',
|
||||||
|
# 'authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50SWQiOiIxNDc3NTQyMDEwNTk2NDc4OTc4IiwiYXZhdGFySWQiOiIxNjIyOTA1ODE5MTk5NTQ5NDQxIiwibWVyY2hhbnRJZCI6IjE2MjI5MDM1NDI3Mjg0NzA1MjkiLCJuaWNrbmFtZSI6IuaxquadsCIsInRlbmFudElkIjoiMTYyMjkwMzU0MjYyMzYxMjkzMCIsImV4cCI6MTcxNTg0NjIxOSwidXNlcklkIjoiMTYyMjkwNTgxOTE5OTU0OTQ0MSIsImlhdCI6MTY4MzYxOTAxOSwidXNlcm5hbWUiOiIrODYxMzcxODM5NTQ3OCJ9.wUV6NxBzG5dgpslNz2NUlpEehSfkbWaNMFYsYOrdO01gg4OfLbZrYOQDWdew2_LjnmORD_toPfLpL6_OawvEPg',
|
||||||
|
}
|
||||||
|
DB_CONFIG = {
|
||||||
|
'host': 'localhost',
|
||||||
|
'port': 3306,
|
||||||
|
'user': 'root',
|
||||||
|
'password': '',
|
||||||
|
'db': 'autotest',
|
||||||
|
'charset': 'utf8',
|
||||||
|
# 'cursorclass': pymysql.cursors.DictCursor # 使返回的数据格式为字典类型
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ProdConfig:
|
||||||
|
"""生产环境配置"""
|
||||||
|
URL = ""
|
||||||
|
DEFAULT_HEADERS = {}
|
||||||
|
|
||||||
|
|
||||||
|
class EnvConfig:
|
||||||
|
"""环境配置入口"""
|
||||||
|
|
||||||
|
# 获取命令行参数中指定的运行环境,如果没有的话就用settings中指定的环境
|
||||||
|
args = command_parser()
|
||||||
|
env = args.env.lower() if args.env else ENV.value
|
||||||
|
|
||||||
|
# 缓存 _ENV_CONFIGS 字典
|
||||||
|
_ENV_CONFIGS = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _generate_env_configs(cls):
|
||||||
|
"""自动匹配并生成环境配置字典"""
|
||||||
|
if cls._ENV_CONFIGS is None: # 只在第一次访问时生成
|
||||||
|
cls._ENV_CONFIGS = {}
|
||||||
|
for name, obj in globals().items():
|
||||||
|
if inspect.isclass(obj) and name.endswith('Config'):
|
||||||
|
env_name = name.lower().replace('config', '') # 自动获取环境名称(例如 DevConfig -> dev)
|
||||||
|
cls._ENV_CONFIGS[env_name] = obj
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_config(cls):
|
||||||
|
"""获取指定环境的配置"""
|
||||||
|
cls._generate_env_configs() # 确保在第一次访问时生成配置字典
|
||||||
|
if cls.env not in cls._ENV_CONFIGS:
|
||||||
|
raise ValueError(
|
||||||
|
f'运行的环境 "{cls.env}" 不存在,请检查运行的环境参数,目前支持的环境有:{", ".join(cls._ENV_CONFIGS.keys())}'
|
||||||
|
)
|
||||||
|
return cls._ENV_CONFIGS.get(cls.env)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def URL(cls):
|
||||||
|
"""获取项目默认URL"""
|
||||||
|
return cls.get_config().URL
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def DEFAULT_HEADERS(cls):
|
||||||
|
"""获取项目默认headers"""
|
||||||
|
return cls.get_config().DEFAULT_HEADERS
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def DB_CONFIG(cls):
|
||||||
|
"""获取项目默认数据库配置"""
|
||||||
|
return cls.get_config().DB_CONFIG
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print(EnvConfig.URL())
|
||||||
|
print(EnvConfig.DEFAULT_HEADERS())
|
|
@ -1,73 +0,0 @@
|
||||||
# !/usr/bin/python
|
|
||||||
# -*- coding:utf-8 -*-
|
|
||||||
# @Time : 2022/7/7 11:40
|
|
||||||
# @Author : wangjie
|
|
||||||
# @File : lins_environment.py
|
|
||||||
# @project : SensoroApi
|
|
||||||
from utils.command_parser import command_parser
|
|
||||||
from common.settings import ENV
|
|
||||||
|
|
||||||
|
|
||||||
class EntryPoint:
|
|
||||||
"""配置类,存放项目各个环境的默认配置"""
|
|
||||||
_ENVIRONMENT_CONFIGS = {
|
|
||||||
'dev': {
|
|
||||||
'URL': "https://dev.com",
|
|
||||||
'DEFAULT_HEADERS': {},
|
|
||||||
},
|
|
||||||
'test': {
|
|
||||||
'URL': "https://www.wanandroid.com",
|
|
||||||
'DEFAULT_HEADERS': {
|
|
||||||
'Content-Type': 'application/json;charset=UTF-8',
|
|
||||||
'accept-language': 'zh-CN,zh;q=0.9',
|
|
||||||
# 'authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50SWQiOiIxNDc3NTQyMDEwNTk2NDc4OTc4IiwiYXZhdGFySWQiOiIxNjIyOTA1ODE5MTk5NTQ5NDQxIiwibWVyY2hhbnRJZCI6IjE2MjI5MDM1NDI3Mjg0NzA1MjkiLCJuaWNrbmFtZSI6IuaxquadsCIsInRlbmFudElkIjoiMTYyMjkwMzU0MjYyMzYxMjkzMCIsImV4cCI6MTcxNTg0NjIxOSwidXNlcklkIjoiMTYyMjkwNTgxOTE5OTU0OTQ0MSIsImlhdCI6MTY4MzYxOTAxOSwidXNlcm5hbWUiOiIrODYxMzcxODM5NTQ3OCJ9.wUV6NxBzG5dgpslNz2NUlpEehSfkbWaNMFYsYOrdO01gg4OfLbZrYOQDWdew2_LjnmORD_toPfLpL6_OawvEPg',
|
|
||||||
},
|
|
||||||
'DB_CONFIG': {
|
|
||||||
'host': 'localhost',
|
|
||||||
'port': 3306,
|
|
||||||
'user': 'root',
|
|
||||||
'password': '',
|
|
||||||
'db': 'autotest',
|
|
||||||
'charset': 'utf8',
|
|
||||||
# 'cursorclass': pymysql.cursors.DictCursor
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'prod': {
|
|
||||||
'URL': "",
|
|
||||||
'DEFAULT_HEADERS': {},
|
|
||||||
},
|
|
||||||
'dianjun': {
|
|
||||||
'URL': "",
|
|
||||||
'DEFAULT_HEADERS': {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# 获取命令行参数中指定的运行环境,如果没有的话就用settings中指定的环境
|
|
||||||
args = command_parser()
|
|
||||||
env = args.env.lower() if args.env else None
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def URL(cls, env=env):
|
|
||||||
"""获取项目默认URL"""
|
|
||||||
if env is None:
|
|
||||||
env = ENV.value
|
|
||||||
return cls._ENVIRONMENT_CONFIGS[env]['URL']
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def DEFAULT_HEADERS(cls, env=env):
|
|
||||||
"""获取项目默认headers"""
|
|
||||||
if env is None:
|
|
||||||
env = ENV.value
|
|
||||||
return cls._ENVIRONMENT_CONFIGS[env]['DEFAULT_HEADERS']
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def DB_CONFIG(cls, env=env):
|
|
||||||
"""获取项目默认数据库配置"""
|
|
||||||
if env is None:
|
|
||||||
env = ENV.value
|
|
||||||
return cls._ENVIRONMENT_CONFIGS[env]['DB_CONFIG']
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
print(EntryPoint.URL())
|
|
||||||
print(EntryPoint.DEFAULT_HEADERS())
|
|
|
@ -14,7 +14,7 @@ import pytest
|
||||||
from common.models import AllureAttachmentType
|
from common.models import AllureAttachmentType
|
||||||
from common.settings import ENV
|
from common.settings import ENV
|
||||||
from configs.paths_config import TEMP_DIR, ALLURE_REPORT_DIR
|
from configs.paths_config import TEMP_DIR, ALLURE_REPORT_DIR
|
||||||
from configs.lins_environment import EntryPoint
|
from configs.env_config import EnvConfig
|
||||||
|
|
||||||
|
|
||||||
def allure_title(title: str) -> None:
|
def allure_title(title: str) -> None:
|
||||||
|
@ -134,7 +134,7 @@ class AllureReportBeautiful:
|
||||||
# 需要写入的环境信息
|
# 需要写入的环境信息
|
||||||
allure_env = {
|
allure_env = {
|
||||||
'OperatingEnvironment': ENV.name,
|
'OperatingEnvironment': ENV.name,
|
||||||
'BaseUrl': EntryPoint.URL(),
|
'BaseUrl': EnvConfig.URL(),
|
||||||
'PythonVersion': platform.python_version(),
|
'PythonVersion': platform.python_version(),
|
||||||
'Platform': platform.platform(),
|
'Platform': platform.platform(),
|
||||||
'PytestVersion': pytest.__version__,
|
'PytestVersion': pytest.__version__,
|
||||||
|
|
|
@ -19,7 +19,7 @@ def command_parser():
|
||||||
help='指定是否需要发送企业微信群消息')
|
help='指定是否需要发送企业微信群消息')
|
||||||
parser.add_argument('-e', '--send-email', choices=['False', 'True'], type=str, default=None,
|
parser.add_argument('-e', '--send-email', choices=['False', 'True'], type=str, default=None,
|
||||||
help='指定是否需要发送邮件')
|
help='指定是否需要发送邮件')
|
||||||
parser.add_argument('-env', '--env', choices=['DEV', 'TEST', 'PROD', 'DIANJUN'], type=str, default=None,
|
parser.add_argument('-env', '--env', choices=['DEV', 'TEST', 'PROD'], type=str, default=None,
|
||||||
help='指定运行环境')
|
help='指定运行环境')
|
||||||
|
|
||||||
# 解析命令行参数
|
# 解析命令行参数
|
||||||
|
|
Loading…
Reference in New Issue