当前位置: 首页 > news >正文

Pytest夹具autouse参数使用。True表示会自动在测试中使用,而无需显式指定

1. 全局conftest文件日志记录功能

# 当前路径(使用 abspath 方法可通过dos窗口执行)
current_path = os.path.dirname(os.path.abspath(__file__))
# 上上级目录
ffather_path = os.path.abspath(os.path.join(current_path,"../"))LOG_FILE_PATH = f'{ffather_path}/log/test.log'def clear_log_file():"""Clear the content of the log file."""open(LOG_FILE_PATH, 'w').close()@pytest.fixture(scope='session', autouse=True)
def configure_logging():# Clear the log file before starting the testsclear_log_file()logger = logging.getLogger()handler = logging.FileHandler(LOG_FILE_PATH, encoding='utf-8')logger.info('Logging configured')handler.setLevel(logging.INFO)formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')handler.setFormatter(formatter)handler.encoding = 'utf-8'logger.addHandler(handler)logger.setLevel(logging.INFO)logging.getLogger().encording = 'utf-8'logger.info('Starting test session')yield handlerlogger.info('Ending test session')logging.getLogger().removeHandler(handler)def pytest_runtest_makereport(item, call):if call.when == 'call' and call.excinfo is not None:logging.error(f"Test case failed: {item.nodeid}")# ***************以下二选一# # 01获取失败的简单内容# failure = call.excinfo._getreprcrash()# logging.error(failure)# 02获取失败的详细信息excinfo = call.excinfoif excinfo:# 格式化异常信息formatted_exception = ''.join(traceback.format_exception(excinfo.type, excinfo.value, excinfo.tb))logging.error(f"Exception details:\n{formatted_exception}")

 

Python 的日志记录和测试框架 pytest 的配置。以下是详细解释:

  1. 获取当前路径

    current_path = os.path.dirname(os.path.abspath(__file__))
  2. 获取上上级目录

    ffather_path = os.path.abspath(os.path.join(current_path,"../"))
  3. 日志文件路径

    LOG_FILE_PATH = f'{ffather_path}/log/test.log'
  4. 清空日志文件内容

    def clear_log_file(): """Clear the content of the log file.""" open(LOG_FILE_PATH, 'w').close()

    这个函数打开日志文件并清空其内容。

  5. pytest 测试夹具配置

    scope='session' 表示此夹具在测试会话开始时设置并在会话结束时清理。

    autouse=True 表示此夹具会自动在测试中使用,而无需显式指定。

  6. 处理测试失败并记录详细信息

    pytest_runtest_makereport 钩子用于生成测试报告。

    如果测试失败(call.when == 'call'),记录测试失败的信息和详细的异常信息。

2.模块conftest.py文件配置前置、后置

@pytest.fixture(scope='function')
def connections():print('建立连接')ssh_client = 'a'ssh_server = 'b'connections = {'c_client':ssh_client,'s_client':ssh_server}yield connectionsprint('断开连接')

 

这段代码展示了如何使用 pytest 的夹具(fixtures)来设置和清理测试环境。夹具是 pytest 提供的一种机制,用于提供测试所需的前置条件和后置处理。详细解释如下:

  1. import pytest:导入 pytest 库,提供了测试框架和夹具功能。

  2. @pytest.fixture(scope='function'):这是 pytest 的夹具装饰器,用于定义一个夹具。夹具是测试执行前和后进行准备和清理的代码块。

    • scope='function':指定夹具的作用范围。在这里,scope='function' 表示每个测试函数都会调用一次该夹具。每次测试函数调用夹具时,夹具都会执行一次准备和清理代码。其他可选的作用范围包括 'module'(模块级别)、'class'(类级别)和 'session'(会话级别)。
  3. def connections()::定义一个名为 connections 的夹具函数。

  4. print('建立连接'):在夹具执行时,打印一条消息,表示正在建立连接。这个步骤用于模拟或实际创建测试所需的资源或状态。

  5. ssh_client = 'a'ssh_server = 'b':模拟创建两个连接对象(ssh_clientssh_server)。在实际的测试中,这里可能会用实际的连接对象或资源初始化代码。

  6. connections = {'c_client': ssh_client, 's_client': ssh_server}:将这些连接对象放入一个字典中,并将字典命名为 connections。这个字典作为夹具的返回值,将被提供给需要它的测试函数。

  7. yield connections:将 connections 字典作为夹具的返回值提供给测试函数。yield 语句表示夹具的“前置准备”部分结束了,接下来是“后置清理”部分的代码。

  8. print('断开连接'):在所有使用此夹具的测试函数执行完毕后,打印一条消息,表示正在断开连接。这是夹具的“后置清理”部分,用于清理测试资源或状态。在实际使用中,这里可能包含关闭连接或释放资源的代码。

3.测试用例

import pytest@pytest.mark.parametrize("title,input,expected", [('title1',1, 2),('title2',2, 4),('title3',3, 6)
])
class Test_connection1:def test_connection1(self,connections,title, input, expected):print('\t')print(title, input, expected)c_conn = connections['c_client']s_conn = connections['s_client']print(c_conn, s_conn)assert 1==1
  1. import pytest:导入 pytest 库,用于编写和执行测试。

  2. @pytest.mark.parametrize("title,input,expected", [...]):这是 pytest 的参数化装饰器,用于将多个输入值传递给测试方法。参数化使得同一测试方法可以使用不同的输入数据运行多次,以确保方法在各种情况下都能正常工作。

    • "title,input,expected":指定参数名称。
    • [...]:定义了三组测试数据:
      • ('title1', 1, 2)
      • ('title2', 2, 4)
      • ('title3', 3, 6)
  3. class Test_connection1:定义了一个测试类 Test_connection1,用于组织测试方法。测试方法会被应用于类中的每个测试用例。

  4. def test_connection1(self, connections, title, input, expected)::这是测试方法 test_connection1。该方法将会接收由参数化装饰器提供的参数 titleinputexpected,以及 connections 夹具。

    • connections:这是 pytest 的夹具,提供了测试所需的连接对象。
    • title, input, expected:来自参数化装饰器的参数值。
  5. print('\t'):打印一个制表符,用于输出格式化。

  6. print(title, input, expected):打印测试用例的当前参数值,帮助调试和验证测试数据。

  7. c_conn = connections['c_client']s_conn = connections['s_client']:从 connections 夹具中提取 c_clients_client 连接对象,并赋值给变量 c_conns_conn

  8. print(c_conn, s_conn):打印提取的连接对象,用于检查其值。

  9. assert 1 == 1:一个基本的断言,用于确保测试运行时不会失败。实际测试中会用复杂的断言来验证 inputexpected 是否符合预期。

http://www.lryc.cn/news/433438.html

相关文章:

  • Linux:归档及压缩
  • jenkins 安装
  • mysql学习教程,从入门到精通,MySQL 删除数据库教程(6)
  • C语言:刷题日志(2)
  • 微带结环行器仿真分析+HFSS工程文件
  • 怎么仿同款小程序的开发制作方法介绍
  • 音视频入门基础:WAV专题(10)——FFmpeg源码中计算WAV音频文件每个packet的pts、dts的实现
  • 0.91寸OLED屏幕大小的音频频谱,炫酷
  • 6. LinkedList与链表
  • Statcounter Global Stats 提供全球统计数据信息
  • Linux kernel中的dts dtsi dtb dtc dtb.img dtbo.img
  • 微信小程序页面制作——个人信息
  • 使用C++11的`std::async`执行异步任务:实战指南
  • 【高阶数据结构】B树、B+树、B*树
  • HBuilderx中vue页面引用scss样式
  • 粒子群算法原理的示例介绍
  • GNU/Linux - Open函数使用的O_CLOEXEC flag
  • AWQ量化(Activation-aware Weight Quantization)
  • SprinBoot+Vue体育商品推荐的设计与实现
  • 【Python基础】Python函数
  • 【超简单】1分钟解决ppt全文字体一键设置
  • 数组与贪心算法——179、56、57、228(2简2中)
  • WireShark过滤器
  • 2024年全新deepfacelive如何对应使用直播伴侣-腾讯会议等第三方软件
  • 告别懵逼——前端项目调试与问题排查方法小结
  • [数据集][目标检测]肺炎检测数据集VOC+YOLO格式4983张2类别
  • 顶层const和底层const
  • 嵌入式Openharmony系统构建与启动详解
  • 锡林郭勒奶酪品牌呼和浩特市大召店盛大开业
  • 【Java算法】模拟