step fixtrue 会覆盖同名的 pytest fixture
fixture.feature
Feature: Target fixtureScenario: Test given fixture injectionGiven I have injecting givenThen foo should be "injected foo"
test_fixture.py
import pytestfrom pytest_bdd import given, then, scenarios@pytest.fixturedef 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'# 简化版,代替 @scenariosscenarios("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: BlogScenario: Deleting the articleGiven there is an articleWhen I request the deletion of the articleThen the request should be successful
test_request.py
import pytestfrom pytest_bdd import scenarios, given, when, thenscenarios("request.feature")@pytest.fixturedef http_client():import requestsreturn 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
