pytest不使用 conftest.py 传递配置参数并设置全局变量

  1. 创建config_handler.py
python 复制代码
import os
import yaml

# 当前路径(使用 abspath 方法可通过dos窗口执行)
current_path = os.path.dirname(os.path.abspath(__file__))
# 上上级目录
ffather_path = os.path.abspath(os.path.join(current_path,"../../"))

global_config_path = os.path.join(ffather_path, r"conf/config.yaml")  # 默认yaml文件路径

def load_config(config_path=None):
    global global_config_path
    if config_path:
        global_config_path = config_path

    with open(global_config_path, 'r', encoding='utf-8', errors='ignore') as file:
        data = yaml.load(file, Loader=yaml.FullLoader)

    return data
  1. conftest.py
python 复制代码
import pytest
import config_handler

def pytest_addoption(parser):
    parser.addoption(
        "--config", action="store",  # 定义--config参数,用于接收配置文件的路径
        help="Path to the configuration file"
    )

def pytest_configure(config):
    config_path = config.getoption("--config")
    config_handler.global_config_path = config_path  # 设置全局配置文件路径
  1. test_script.py
python 复制代码
import config_handler

def test_example():
    config_data = config_handler.load_config()
    # 使用config_data进行测试

执行命令:pytest .\TestCases\A\test_add.py -s --config=conf/config_test.yaml

说明:

  • config_handler.py 包含加载配置文件的逻辑和全局变量的管理。
  • conftest.py

pytest_configure 函数用于初始化全局配置文件路径,根据命令行参数 --config 的值来设置全局变量。

pytest_addoption是一个 pytest 插件系统中的钩子函数,用于添加自定义的命令行选项。当 pytest 执行时,会调用这个函数来注册你定义的选项。

def pytest_addoption(parser):parser.addoption(...) 的结合使用,你定义了一个新的 pytest 命令行选项 --config,使得用户可以在运行 pytest 时通过命令行传递一个配置文件的路径

  • test_script.py 中的测试函数可以直接使用 config_handler.load_config() 来加载配置文件。

通过以上方式,可以根据需要选择合适的项目结构和需求的方法来传递配置参数,并在整个项目中共享和使用这些配置。

相关推荐
ademen25 分钟前
spring4第6课-bean之间的关系+bean的作用范围
java·spring
cccl.25 分钟前
Java在word中指定位置插入图片。
java·word
kingbal26 分钟前
Elasticsearch:spring2.x集成elasticsearch8.x
java·spring2.x·elastic8.x
三两肉2 小时前
Java 中 ArrayList、Vector、LinkedList 的核心区别与应用场景
java·开发语言·list·集合
clk66074 小时前
SSM 框架核心知识详解(Spring + SpringMVC + MyBatis)
java·spring·mybatis
shangjg35 小时前
Kafka 的 ISR 机制深度解析:保障数据可靠性的核心防线
java·后端·kafka
Amo Xiang7 小时前
Python 解释器安装全攻略(适用于 Linux / Windows / macOS)
linux·windows·python·环境安装
程序员杰哥7 小时前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
Alan3167 小时前
Qt 中,设置事件过滤器(Event Filter)的方式
java·开发语言·数据库
浩皓素7 小时前
用Python开启游戏开发之旅
python