背景
不同 Scenario 都有 Given,不同的 Given 可以共同调用一个函数
second.feature
Feature: Resource owner
Scenario: I'm the author
Given I'm an author
And I have an article
Scenario: I'm the admin
Given I'm the admin
And there's an article
test_second.py python 文件
import pytest
from pytest_bdd import given, scenario
@given("I'm an author", target_fixture="author")
def author():
print("I'm an author")
return dict(username="polo")
@given("I'm the admin", target_fixture="author")
def admin():
print("I'm an admin")
return dict(username="admin")
@given("I have an article")
@given("there's an article")
def article(author):
print("two given")
return author
# scenario
@scenario('second.feature', "I'm the author")
def test_publish():
pass
@scenario('second.feature', "I'm the admin")
def test_publish2():
pass
不同 Scenario 的 Given 可以装饰在同一个 Python 函数上
命令行运行
pytest -sq test_second.py
运行结果
I'm an author
two given
.I'm an admin
two given
.
2 passed in 0.01s
注意点
@given("I have an article")
@given("there's an article")
def article(author):
print("two given")
return author
假设调用了一个 fixture(这里是 author)而且这个 fixture 是其他 step,那么必须拥有同名的 fixture 才能调用成功,否则会报错
@given("I'm an author", target_fixture="author")
def author():
print("I'm an author")
return dict(username="polo")
@given("I'm the admin", target_fixture="author")
def admin():
print("I'm an admin")
return dict(username="admin")
可以看到,两个 given 的 target_fixture 是同名的
@given("I'm an author", target_fixture="author")
def author():
print("I'm an author")
return dict(username="polo")
# 假如这个 target_fixture 不是 author,那么运行就会报错:fixture 'author' not found
@given("I'm the admin", target_fixture="admin")
def admin():
print("I'm an admin")
return dict(username="admin")