欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > pytest不使用 conftest.py 传递配置参数并设置全局变量

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

2025/2/25 16:29:45 来源:https://blog.csdn.net/songpeiying/article/details/140615452  浏览:    关键词:pytest不使用 conftest.py 传递配置参数并设置全局变量

1. 创建config_handler.py


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_pathif config_path:global_config_path = config_pathwith open(global_config_path, 'r', encoding='utf-8', errors='ignore') as file:data = yaml.load(file, Loader=yaml.FullLoader)return data

2. conftest.py

import pytest
import config_handlerdef 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  # 设置全局配置文件路径

 3. test_script.py 

import config_handlerdef 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() 来加载配置文件。

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词