step fixtrue 会覆盖同名的 pytest fixture
fixture.feature
Feature: Target fixture
Scenario: Test given fixture injection
Given I have injecting given
Then foo should be "injected foo"
test_fixture.py
import pytest
from pytest_bdd import given, then, scenarios
@pytest.fixture
def foo():
print("pytest fixture")
return "foo"
@given("I have injecting given", target_fixture="foo")
def injecting_given():
print("step fixture")
return "injected foo"
@then('foo should be "injected foo"')
def foo_is_foo(foo):
assert foo == 'injected foo'
# 简化版,代替 @scenarios
scenarios("fixture.feature")
命令行运行
pytest -sq test_fixture.py
运行结果
step fixture
.
1 passed in 0.01s
@given 提供了一个 fixture,因为存在同名的 pytest.fixture,所以会把它覆盖掉
除了 @given,@when、@then 也可以提供 fixture 功能
request.feature
Feature: Blog
Scenario: Deleting the article
Given there is an article
When I request the deletion of the article
Then the request should be successful
test_request.py
import pytest
from pytest_bdd import scenarios, given, when, then
scenarios("request.feature")
@pytest.fixture
def http_client():
import requests
return requests.session()
@given("there is an article", target_fixture="article")
def there_is_an_article():
return dict(uid=1, name="book name", pages=150)
@when("I request the deletion of the article", target_fixture="request_result")
def there_should_be_a_new_article(article, http_client):
return http_client.delete(f"http://127.0.0.1:8080/articles/{article['uid']}")
@then("the request should be successful")
def article_is_published(request_result):
# 拿到 when 的结果进行断言
assert request_result.status_code != 200