背景
以前写接口自动化,一般都会用到数据驱动,假设 bdd 在没有数据驱动的情况下会怎么写?
Feature: EatingScenario: Eat 5 out of 12Given there are 12 cucumbersWhen I eat 5 cucumbersThen I should have 7 cucumbersScenario: Eat 5 out of 20Given there are 20 cucumbersWhen I eat 5 cucumbersThen I should have 15 cucumbers
Given、When、Then 高度重复,只是数据不一致而已
如何解决数据参数化的问题?就是通过 outlines
Scenario Outline: EatingGiven there are <start> cucumbersWhen I eat <eat> cucumbersThen I should have <left> cucumbersExamples:| start | eat | left || 12 | 5 | 7 || 20 | 5 | 15 |
outline 重点
- Examples 的第一行不会被当做数据进行运行,从第二行开始读取数据并运行,一行代表一个测试场景
- 通过
<占位符>来表示变量参数,它可以卸载 Given、When、Then 步骤中
实际 🌰
outline.feature
Scenario Outline: EatingGiven there are <start> cucumbersWhen I eat <eat> cucumbersThen I should have <left> cucumbersExamples:| start | eat | left || 12 | 5 | 7 || 20 | 5 | 15 |
test_outline.py
from pytest_bdd import given, then, parsers, scenarios, whenscenarios('outline.feature')@given(parsers.parse("there are {start} cucumbers"))def get_cucumbers(start):print(f"there ara {start} cucumbers")return start@when(parsers.parse("I eat {eat} cucumbers"))def eat_cucumbers(eat):print(f"I eat {eat} cucumbers")return eat@then(parsers.parse("I should have {left} cucumbers"))def left_cucumbers(left, eat, start):print(f"I should have {left} cucumbers")assert int(left) == (int(start) - int(eat))print("=== end ===")
命令行运行
pytest -sq test_outline.py
运行结果
there ara 12 cucumbersI eat 5 cucumbersI should have 7 cucumbers=== end ===.there ara 20 cucumbersI eat 5 cucumbersI should have 15 cucumbers=== end ===.2 passed in 0.01s
可看到,收集了两个测试用例
