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

相关推荐
博观而约取33 分钟前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector2 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习2 小时前
Python入门Day2
开发语言·python
Vertira2 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉2 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗3 小时前
黑马python(二十四)
开发语言·python
晓13133 小时前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr
是小王同学啊~3 小时前
(LangChain)RAG系统链路向量检索器之Retrievers(五)
python·算法·langchain
AIGC包拥它3 小时前
提示技术系列——链式提示
人工智能·python·langchain·prompt
孟陬3 小时前
Python matplotlib 如何**同时**展示正文和 emoji
python