BDD - Python Behave log 日志

2024-01-01 21:44
文章标签 python 日志 log bdd behave

本文主要是介绍BDD - Python Behave log 日志,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

BDD - Python Behave log 日志

  • 引言
  • Behave log
    • Behave log 项目准备
      • feature 文件
      • step 文件
      • environment.py 文件
    • Behave log 执行
      • log_capture 模式
        • log_capture 开模式
        • log_capture 关模式即普通模式
      • logging-filter
      • logging-level
        • logcapture 模式
        • no-logcapture 模式
      • logging_format
        • log_capture 模式
        • no-logcapture 模式

引言

日志在整个测试运行中是非常重要的,帮助我们定位问题。也许你习惯用 Print。。。。,尽管效果差不多,但是显得不那么专业了,也不方便日志管理。今天我们来了解一下 Behave 日志机制。

想了解更多 Behave 相关的文章,欢迎阅读《Python BDD Behave 系列》,持续更新中。

Behave log

Behave 使用 Python 的标准 logging 模块进行日志记录。这意味着 Behave 继承了 Python 的日志机制,可以使用相同的配置和方法。

Behave log 项目准备

举个简单的实例

feature 文件

创建 log.feature 文件,准备一些 log 记录,一个运行会失败的 Scenario, 一个运行会成功的 Scenario

# log.featureFeature: Log ExampleScenario: PassingGiven I create log records with:| category | level   | message || root     |  FATAL  | Hello Alice  || foo      |  ERROR  | Hello Bob    || foo.bar  |  WARN   | Hello Charly || bar      |  INFO   | Hello Dora   || baz      |  DEBUG  | Hello Emily  |When another step passesScenario: FailingGiven I create log records with:| category | level   | message || root     |  FATAL  | Hello Alice  || foo      |  ERROR  | Hello Bob    || foo.bar  |  WARN   | Hello Charly || bar      |  INFO   | Hello Dora   || baz      |  DEBUG  | Hello Emily  |When another step fails

step 文件

# log_steps.pyfrom behave import *
from behave.configuration import LogLevel
import loggingdef make_log_record(category, level, message):if category in ("root", "__ROOT__"):category = Nonelogger = logging.getLogger(category)logger.log(level, message)@Given('I create log records with')
def step_I_create_logrecords_with_table(context):assert context.table, "REQUIRE: context.table"context.table.require_columns(["category", "level", "message"])for row in context.table.rows:category = row["category"]if category == "__ROOT__":category = Nonelevel = LogLevel.parse_type(row["level"])message = row["message"]make_log_record(category, level, message)# -----------------------------------------------------------------------------
# STEPS FOR: passing
# -----------------------------------------------------------------------------
@When('{word:w} step passes')
def step_passes(context, word):"""Step that always passes, mostly needed in examples."""pass# -----------------------------------------------------------------------------
# STEPS FOR: failing
# -----------------------------------------------------------------------------
@when(u'{word:w} step fails')
def step_fails(context, word):"""Step that always fails, mostly needed in examples."""assert False, "EXPECT: Failing step"

environment.py 文件

context.config.setup_logging() 简单地全局配置日志记录系统的基本配置,以设置默认的日志处理器、日志级别、格式等参数。

# environment.pyfrom behave import *def before_all(context):pass# print("Before all tests")context.before_all = "before all"# -- SAME-AS:# import logging# logging.basicConfig(level=context.config.logging_level)context.config.setup_logging()

Behave log 执行

log_capture 模式

  • Behave 默认 log_capture 模式是开的
  • log_capture 模式可通过命令行方式设置
  • log_capture 模式也可在 behave 配置文件 behave.ini 中设置
  • log_capture 模式只有在 Scenario 运行失败时才会捕获 log 记录
log_capture 开模式

所以执行命令 behave -f plain --logcapturebehave -f plain 效果是一样的,只有在 Scenario 运行失败时才会捕获 log 记录(看到 Captured logging: 部分

PS C:\Automation\Test\bdd> behave -f plain   
Feature: Log ExampleScenario: PassingGiven I create log records with ... passed in 0.000s| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step passes ... passed in 0.001sScenario: FailingGiven I create log records with ... passed in 0.001s| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step fails ... failed in 0.001s
Assertion Failed: EXPECT: Failing step
Captured logging:
CRITICAL:root:Hello Alice
ERROR:foo:Hello Bob
WARNING:foo.bar:Hello Charly
INFO:bar:Hello DoraFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.003s
log_capture 关模式即普通模式

命令行选项 --no-logcapture 普通模式,运行成功的 Scenario 也会输出 log

也可以在配置文件 behave.ini 设置,只需执行命令 behave -f plain
[behave]
log_capture = false

PS C:\Automation\Test\bdd> behave -f plain  --no-logcapture
Feature: Log ExampleScenario: Passing
CRITICAL:root:Hello Alice
ERROR:foo:Hello Bob
WARNING:foo.bar:Hello Charly
INFO:bar:Hello DoraGiven I create log records with ... passed in 0.000s| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step passes ... passed in 0.000sScenario: Failing
CRITICAL:root:Hello Alice
ERROR:foo:Hello Bob
WARNING:foo.bar:Hello Charly
INFO:bar:Hello DoraGiven I create log records with ... passed in 0.013s| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step fails ... failed in 0.000s
Assertion Failed: EXPECT: Failing stepFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.013s

logging-filter

根据 log catalog 来过滤 log 记录,只输出想要的 log 信息,前提条件是 log_capture 模式下
e.g.
过滤出包含 foo catalog 的日志记录: behave --logcapture --logging-filter=foo
过滤出包含子类 foo.bar catalog 的日志记录:behave --logcapture --logging-filter=foo.bar
过滤出包含非 foo catalog 的日志记录:behave --logcapture --logging-filter=-foo
过滤出包含 foo 或 bar catalog 的日志记录:behave --logcapture --logging-filter=foo,bar

过滤出包含 foo.bar 或不包含 bar catalog 的日志记录:behave --logcapture --logging-filter=foo.bar,-bar
所以会包含下面这些 log 记录
root --》 非 bar
foo.bar–》foo.bar

  Captured logging:CRITICAL:root:Hello Alice  ERROR:foo:Hello BobWARNING:foo.bar:Hello Charly
PS C:\ForKelly\Automation\Test\bdd> behave --logcapture --logging-filter=foo.bar,-bar
Feature: Log Example # Features/log/log.feature:1Scenario: Passing                 # Features/log/log.feature:3Given I create log records with # steps/log_steps.py:13| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step passes        # steps/log_steps.py:30Scenario: Failing                 # Features/log/log.feature:13Given I create log records with # steps/log_steps.py:13| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step fails         # steps/log_steps.py:40Assertion Failed: EXPECT: Failing stepCaptured logging:CRITICAL:root:Hello AliceERROR:foo:Hello BobWARNING:foo.bar:Hello CharlyFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.001s

logging-level

日志级别(logging level)用于指定日志消息的严重程度。不同的级别对应不同的常量(debug,info, warning, error),logcapture 模式和 logcapture 模式都可以应用.

logcapture 模式
PS C:\Automation\Test\bdd> behave -f plain -T --logging-level=WARN
Feature: Log ExampleScenario: PassingGiven I create log records with ... passed| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step passes ... passedScenario: FailingGiven I create log records with ... passed| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step fails ... failed
Assertion Failed: EXPECT: Failing step
Captured logging:
CRITICAL:root:Hello Alice
ERROR:foo:Hello Bob
WARNING:foo.bar:Hello CharlyFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.000s
no-logcapture 模式
PS C:Automation\Test\bdd> behave -f plain -T --logging-level=WARN --no-logcapture
Feature: Log ExampleScenario: Passing
CRITICAL:root:Hello Alice
ERROR:foo:Hello Bob
WARNING:foo.bar:Hello CharlyGiven I create log records with ... passed| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step passes ... passedScenario: Failing
CRITICAL:root:Hello Alice
ERROR:foo:Hello Bob
WARNING:foo.bar:Hello CharlyGiven I create log records with ... passed| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step fails ... failed
Assertion Failed: EXPECT: Failing stepFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.003s

logging_format

logging.Formatter 类用于配置日志的输出格式。通过使用格式化字符串,您可以指定日志消息的显示方式,包括日期、日志级别、消息内容等。
behave -f plain -T --logging-format=‘LOG.%(levelname)-8s %(name)-10s: %(message)s’

也可以通过配置文件设置:
[behave]
logging_format = %(asctime)s LOG.%(levelname)-8s %(name)s: %(message)s
logging_datefmt = %Y-%m-%dT%H:%M:%S

log_capture 模式
 [behave]
# config for log
log_capture = true
logging_level = WARN
logging_format = %(asctime)s  LOG.%(levelname)-8s %(name)s: %(message)s
logging_datefmt = %Y-%m-%dT%H:%M:%S
PS C:\Automation\Test\bdd> behave
Feature: Log Example # Features/log/log.feature:1Scenario: Passing                 # Features/log/log.feature:3Given I create log records with # steps/log_steps.py:13| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step passes        # steps/log_steps.py:30Scenario: Failing                 # Features/log/log.feature:13Given I create log records with # steps/log_steps.py:13| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |When another step fails         # steps/log_steps.py:40Assertion Failed: EXPECT: Failing stepCaptured logging:2024-01-01T20:51:36  LOG.CRITICAL root: Hello Alice2024-01-01T20:51:36  LOG.ERROR    foo: Hello Bob2024-01-01T20:51:36  LOG.WARNING  foo.bar: Hello CharlyFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.002s
no-logcapture 模式
 [behave]
# config for log
log_capture = false
logging_level = WARN
logging_format = %(asctime)s  LOG.%(levelname)-8s %(name)s: %(message)s
logging_datefmt = %Y-%m-%dT%H:%M:%S
PS C:\Automation\Test\bdd> behave
Feature: Log Example # Features/log/log.feature:1Scenario: Passing                 # Features/log/log.feature:3Given I create log records with # steps/log_steps.py:13| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |
2024-01-01T20:53:25  LOG.CRITICAL root: Hello Alice
2024-01-01T20:53:25  LOG.ERROR    foo: Hello Bob
2024-01-01T20:53:25  LOG.WARNING  foo.bar: Hello CharlyWhen another step passes        # steps/log_steps.py:30Scenario: Failing                 # Features/log/log.feature:13Given I create log records with # steps/log_steps.py:13| category | level | message      || root     | FATAL | Hello Alice  || foo      | ERROR | Hello Bob    || foo.bar  | WARN  | Hello Charly || bar      | INFO  | Hello Dora   || baz      | DEBUG | Hello Emily  |
2024-01-01T20:53:25  LOG.CRITICAL root: Hello Alice
2024-01-01T20:53:25  LOG.ERROR    foo: Hello Bob
2024-01-01T20:53:25  LOG.WARNING  foo.bar: Hello CharlyWhen another step fails         # steps/log_steps.py:40Assertion Failed: EXPECT: Failing stepFailing scenarios:Features/log/log.feature:13  Failing0 features passed, 1 failed, 0 skipped
1 scenario passed, 1 failed, 0 skipped
3 steps passed, 1 failed, 0 skipped, 0 undefined
Took 0m0.003s

这篇关于BDD - Python Behave log 日志的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/560599

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

内核启动时减少log的方式

内核引导选项 内核引导选项大体上可以分为两类:一类与设备无关、另一类与设备有关。与设备有关的引导选项多如牛毛,需要你自己阅读内核中的相应驱动程序源码以获取其能够接受的引导选项。比如,如果你想知道可以向 AHA1542 SCSI 驱动程序传递哪些引导选项,那么就查看 drivers/scsi/aha1542.c 文件,一般在前面 100 行注释里就可以找到所接受的引导选项说明。大多数选项是通过"_

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

flume系列之:查看flume系统日志、查看统计flume日志类型、查看flume日志

遍历指定目录下多个文件查找指定内容 服务器系统日志会记录flume相关日志 cat /var/log/messages |grep -i oom 查找系统日志中关于flume的指定日志 import osdef search_string_in_files(directory, search_string):count = 0

我在移动打工的日志

客户:给我搞一下录音 我:不会。不在服务范围。 客户:是不想吧 我:笑嘻嘻(气笑) 客户:小姑娘明明会,却欺负老人 我:笑嘻嘻 客户:那我交话费 我:手机号 客户:给我搞录音 我:不会。不懂。没搞过。 客户:那我交话费 我:手机号。这是电信的啊!!我这是中国移动!! 客户:我不管,我要充话费,充话费是你们的 我:可是这是移动!!中国移动!! 客户:我这是手机号 我:那又如何,这是移动!你是电信!!

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',