Pytest-Bdd-Playwright 系列教程(15):背景(Background)

Pytest-Bdd-Playwright 系列教程(15):背景(Background)

前言

在测试的过程中,我们往往会遇到这样的问题:多个测试场景需要相同的前置条件。如果每个场景重复编写这些前置条件,不仅显得冗余,还增加了维护成本。因此,pytest-bdd框架通常提供一种机制来解决这一问题,那就是背景(Background)。

一、什么是背景(Background)

在pytest-bdd中,背景(Background)用于定义在每个场景执行之前需要共享的步骤。通过使用背景,我们可以避免在多个场景中编写相同的Given步骤,从而减少重复并提高可读性。背景中的步骤在每个场景执行之前都会被调用,这样可以确保所有场景都有相同的初始条件。

背景的应用实例

假设在多个场景中,计算器的初始化状态是相同的。如果没有背景,每个场景都需要重复编写初始化步骤。使用背景,能够确保每个场景的前置条件一致,简化了代码。

二、特性文件

首先,新增features/calculator_demo.feature文件。背景部分通常位于.feature文件的开头,格式及内容如下:

gherkin 复制代码
Feature: 计算器
  一个简单的计算器,用于执行基本的算术操作。

  Background:
    Given 我已经准备好计算器

  Scenario: 检查计算器的尺寸
    Then 计算器的宽度应该是 12.5
    And 计算器的高度应该是 20.0
    And 计算器的厚度应该是 0.5

  Scenario: 打开计算器
    Given 我按下电源按钮
    Then 屏幕应该亮起

  Scenario Outline: 两个数字的计算
    Given 我检查按钮是否正常
    And 第一个数字是 <first_number>
    And 第二个数字是 <second_number>
    When 我按下 <operation>
    Then 结果应该是 <expected_result>

    Examples:
      | first_number | second_number | operation | expected_result |
      | 5            | 3            | 加号       | 8               |
      | 10           | 4            | 减号       | 6               |
      | 2            | 6            | 乘号       | 12              |
      | 8            | 2            | 除号       | 4               |

在这个示例中,背景部分定义了一些共同的前置条件,这些条件会在每个场景执行之前自动运行。通过这种方式,可以确保每个场景开始时的条件是一致的,避免了代码重复。

三、测试脚本

然后,新增test_calculator_demo.py文件,内容如下:

python 复制代码
from pytest_bdd import given, when, then, parsers, scenario

@scenario('calculator_demo.feature', '检查计算器的尺寸')
def test_calculator_size():
    pass

@scenario('calculator_demo.feature', '打开计算器')
def test_open_calculator():
    pass

@scenario('calculator_demo.feature', '两个数字的计算')
def test_two_numbers_calculation():
    pass


@given("我已经准备好计算器")
def _():
    print("计算器已准备好!")

@given("我检查按钮是否正常")
def _():
    print("按钮已检查。")

@given("我按下电源按钮")
def _():
    pass

@then("屏幕应该亮起")
def _():
    pass

@then(parsers.parse("计算器的宽度应该是 {expected_width:f}"))
def _(expected_width: float):
    print(f"宽度: {expected_width}")

@then(parsers.parse("计算器的高度应该是 {expected_height:f}"))
def _(expected_height: float):
    print(f"高度: {expected_height}")

@then(parsers.parse("计算器的厚度应该是 {expected_thickness:f}"))
def _(expected_thickness: float):
    print(f"厚度: {expected_thickness}")

@given(parsers.parse("第一个数字是 {first_number:d}"), target_fixture="first_number")
def _(first_number):
    return first_number

@given(parsers.parse("第二个数字是 {second_number:d}"), target_fixture="second_number")
def _(second_number):
    return second_number

@when(parsers.parse("我按下 {operation}"), target_fixture="result")
def _(operation, first_number, second_number):
    if operation == "加号":
        return first_number + second_number
    elif operation == "减号":
        return first_number - second_number
    elif operation == "乘号":
        return first_number * second_number
    elif operation == "除号":
        return first_number / second_number
    else:
        raise ValueError(f"不支持的操作: {operation}")

@then(parsers.parse("结果应该是 {expected_result:d}"))
def _(result, expected_result):
    assert result == expected_result

在这段代码中,我们定义了与计算器相关的步骤,并通过pytest-bdd的装饰器将其与特性文件中的场景绑定,每个步骤都与特性文件中的Given、When、Then对应。

四、运行测试

使用以下命令运行测试:

bash 复制代码
pytest ./tests/test_calculator_demo.py

运行结果如下:

总结

使用背景(Background)可以让我们的BDD测试更具可维护性和可读性,减少重复的代码,并帮助确保测试场景中的前提条件始终一致。在实际的项目中,善用背景和BDD的相关功能,可以极大地提升测试代码的质量和执行效率。

相关推荐
Jackson@ML44 分钟前
如何快速高效学习Python?
开发语言·python
UFIT2 小时前
Python函数与模块笔记
开发语言·python
言之。2 小时前
别学了,打会王者吧
java·python·mysql·容器·spark·php·html5
YiSLWLL3 小时前
使用Tauri 2.3.1+Leptos 0.7.8开发桌面小程序汇总
python·rust·sqlite·matplotlib·visual studio code
花酒锄作田3 小时前
[flask]自定义请求日志
python·flask
SsummerC5 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
Tandy12356_5 小时前
Godot开发2D冒险游戏——第一节:主角登场!
python·游戏引擎·godot
西柚小萌新6 小时前
【Python爬虫基础篇】--4.Selenium入门详细教程
爬虫·python·selenium
橘猫云计算机设计6 小时前
springboot基于hadoop的酷狗音乐爬虫大数据分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·hadoop·spring boot·爬虫·python·数据分析·毕业设计
YOULANSHENGMENG7 小时前
linux 下python 调用c++的动态库的方法
c++·python