diff --git a/common/base_api.py b/common/base_api.py index bd9a6dc..4904e64 100755 --- a/common/base_api.py +++ b/common/base_api.py @@ -19,7 +19,7 @@ from requests.structures import CaseInsensitiveDict from common.base_log import logger from common.exceptions import ValueTypeError 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.allure_handle import allure_attach_text, allure_attach_json, allure_attach_file from utils.time_utils import TimeUtil @@ -35,7 +35,7 @@ class BaseApi: if address.lower().startswith("http"): return address # 确保host不以/结尾 - host = EntryPoint.URL().rstrip("/") + host = EnvConfig.URL().rstrip("/") # 确保address是以/开头 address = "/" + address.lstrip("/") @@ -44,7 +44,7 @@ class BaseApi: @staticmethod def _make_headers(headers) -> dict[Any, Any]: """对请求头进行预处理""" - default_headers = EntryPoint.DEFAULT_HEADERS() + default_headers = EnvConfig.DEFAULT_HEADERS() headers = headers or {} merged_headers = {**default_headers, **headers} return merged_headers diff --git a/common/connect_DB.py b/common/connect_DB.py index 370b20d..5a31c26 100644 --- a/common/connect_DB.py +++ b/common/connect_DB.py @@ -10,7 +10,7 @@ import pymysql from dbutils.pooled_db import PooledDB from common.base_log import logger -from configs.lins_environment import EntryPoint +from configs.env_config import EnvConfig class Postgresql: @@ -176,7 +176,7 @@ if __name__ == '__main__': # with Postgresql(db_config) as db: # db.execute_query("SELECT * FROM mytable") - db_config = EntryPoint.DB_CONFIG() + db_config = EnvConfig.DB_CONFIG() with MySQL(db_config) as db: query = "SELECT * FROM student WHERE name = '张三'" result = db.execute_query_with_result(query) diff --git a/configs/env_config.py b/configs/env_config.py new file mode 100644 index 0000000..f169d0e --- /dev/null +++ b/configs/env_config.py @@ -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()) diff --git a/configs/lins_environment.py b/configs/lins_environment.py deleted file mode 100644 index dc9c6f7..0000000 --- a/configs/lins_environment.py +++ /dev/null @@ -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()) diff --git a/utils/allure_handle.py b/utils/allure_handle.py index c972202..acb07fe 100644 --- a/utils/allure_handle.py +++ b/utils/allure_handle.py @@ -14,7 +14,7 @@ import pytest from common.models import AllureAttachmentType from common.settings import ENV 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: @@ -134,7 +134,7 @@ class AllureReportBeautiful: # 需要写入的环境信息 allure_env = { 'OperatingEnvironment': ENV.name, - 'BaseUrl': EntryPoint.URL(), + 'BaseUrl': EnvConfig.URL(), 'PythonVersion': platform.python_version(), 'Platform': platform.platform(), 'PytestVersion': pytest.__version__, diff --git a/utils/command_parser.py b/utils/command_parser.py index 05f2213..dea141b 100644 --- a/utils/command_parser.py +++ b/utils/command_parser.py @@ -19,7 +19,7 @@ def command_parser(): help='指定是否需要发送企业微信群消息') parser.add_argument('-e', '--send-email', choices=['False', 'True'], type=str, default=None, 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='指定运行环境') # 解析命令行参数