step fixtrue 会覆盖同名的 pytest fixture

fixture.feature

  1. Feature: Target fixture
  2. Scenario: Test given fixture injection
  3. Given I have injecting given
  4. Then foo should be "injected foo"

test_fixture.py

  1. import pytest
  2. from pytest_bdd import given, then, scenarios
  3. @pytest.fixture
  4. def foo():
  5. print("pytest fixture")
  6. return "foo"
  7. @given("I have injecting given", target_fixture="foo")
  8. def injecting_given():
  9. print("step fixture")
  10. return "injected foo"
  11. @then('foo should be "injected foo"')
  12. def foo_is_foo(foo):
  13. assert foo == 'injected foo'
  14. # 简化版,代替 @scenarios
  15. scenarios("fixture.feature")

命令行运行

  1. pytest -sq test_fixture.py

运行结果

  1. step fixture
  2. .
  3. 1 passed in 0.01s

@given 提供了一个 fixture,因为存在同名的 pytest.fixture,所以会把它覆盖掉

除了 @given,@when、@then 也可以提供 fixture 功能

比较常用在 HTTP 请求断言

request.feature

  1. Feature: Blog
  2. Scenario: Deleting the article
  3. Given there is an article
  4. When I request the deletion of the article
  5. Then the request should be successful

test_request.py

  1. import pytest
  2. from pytest_bdd import scenarios, given, when, then
  3. scenarios("request.feature")
  4. @pytest.fixture
  5. def http_client():
  6. import requests
  7. return requests.session()
  8. @given("there is an article", target_fixture="article")
  9. def there_is_an_article():
  10. return dict(uid=1, name="book name", pages=150)
  11. @when("I request the deletion of the article", target_fixture="request_result")
  12. def there_should_be_a_new_article(article, http_client):
  13. return http_client.delete(f"http://127.0.0.1:8080/articles/{article['uid']}")
  14. @then("the request should be successful")
  15. def article_is_published(request_result):
  16. # 拿到 when 的结果进行断言
  17. assert request_result.status_code != 200