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的相关功能,可以极大地提升测试代码的质量和执行效率。

相关推荐
传奇开心果编程几秒前
【传奇开心果系列】Flet框架实现的家庭记账本示例自定义模板
python·学习·ui·前端框架·自动化
王者鳜錸1 小时前
PYTHON让繁琐的工作自动化-PYTHON基础
python·microsoft·自动化
key_Go1 小时前
7.Ansible自动化之-实施任务控制
python·ansible·numpy
wyiyiyi9 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8249 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员9 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋10 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
AntBlack11 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
杜子不疼.12 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
myzzb13 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa