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

相关推荐
CodeCraft Studio38 分钟前
CAD文件处理控件Aspose.CAD教程:使用 Python 将绘图转换为 Photoshop
python·photoshop·cad·aspose·aspose.cad
Python×CATIA工业智造3 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco3 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
狐凄4 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊5 小时前
Python之--基本知识
开发语言·前端·python
笑稀了的野生俊6 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva6 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了7 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿7 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack8 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python