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