优化conftest测试夹具创建销毁对象方式

This commit is contained in:
谈林海 2023-03-31 16:24:06 +08:00
parent 38075164e6
commit 700cc47662
2 changed files with 9 additions and 40 deletions

View File

@ -8,6 +8,7 @@ from pathlib import Path
from utils import config
from utils.path import root
from utils.log_control import logger
from utils.database_control import MysqlDB
from utils.read_yaml_control import HandleYaml
from utils.allure_control import ReportStyle
from utils.data_handle_control import DataHandler, Config
@ -73,48 +74,17 @@ def pytest_collection_modifyitems(items):
@pytest.fixture(autouse=True)
def collection(requests, headers, sql, cache):
def collection():
class Core:
def __init__(self):
self.requests = requests
self.headers = headers
self.sql = sql
self.cache = cache
self.requests = RestClient()
self.headers = RestClient.headers()
self.cache = HandleYaml(root / 'test_data/cache.yml')
self.mysql = MysqlDB()
return Core()
yield Core()
@pytest.fixture()
def core(collection):
yield collection
del collection
@pytest.fixture()
def headers():
"""通用请求头"""
return RestClient().headers()
@pytest.fixture()
def requests():
"""返回实例化请求方法"""
yield RestClient()
@pytest.fixture()
def sql():
"""返回实例化数据库方法"""
from utils.database_control import MysqlDB
with MysqlDB() as sql:
yield sql
@pytest.fixture()
def cache():
"""返回一个字典,用作数据共享"""
yield HandleYaml(root / 'test_data/cache.yml')

View File

@ -14,7 +14,7 @@ class QueryState(enum.Enum):
class MysqlDB:
"""数据库封装"""
def __enter__(self):
def __init__(self):
try:
self.conn = pymysql.connect(
host=config.mysql_db.host,
@ -26,9 +26,8 @@ class MysqlDB:
except Exception as err:
logger.error(f"数据库连接失败: {err}")
raise
return self
def __exit__(self, exc_type, exc_val, exc_tb):
def __del__(self, exc_type, exc_val, exc_tb):
try:
self.conn.close()
except Exception as err: