背景

不同 Scenario 都有 Given,不同的 Given 可以共同调用一个函数

second.feature

  1. Feature: Resource owner
  2. Scenario: I'm the author
  3. Given I'm an author
  4. And I have an article
  5. Scenario: I'm the admin
  6. Given I'm the admin
  7. And there's an article

test_second.py python 文件

  1. import pytest
  2. from pytest_bdd import given, scenario
  3. @given("I'm an author", target_fixture="author")
  4. def author():
  5. print("I'm an author")
  6. return dict(username="polo")
  7. @given("I'm the admin", target_fixture="author")
  8. def admin():
  9. print("I'm an admin")
  10. return dict(username="admin")
  11. @given("I have an article")
  12. @given("there's an article")
  13. def article(author):
  14. print("two given")
  15. return author
  16. # scenario
  17. @scenario('second.feature', "I'm the author")
  18. def test_publish():
  19. pass
  20. @scenario('second.feature', "I'm the admin")
  21. def test_publish2():
  22. pass

不同 Scenario 的 Given 可以装饰在同一个 Python 函数上

命令行运行

  1. pytest -sq test_second.py

运行结果

  1. I'm an author
  2. two given
  3. .I'm an admin
  4. two given
  5. .
  6. 2 passed in 0.01s

注意点

  1. @given("I have an article")
  2. @given("there's an article")
  3. def article(author):
  4. print("two given")
  5. return author

假设调用了一个 fixture(这里是 author)而且这个 fixture 是其他 step,那么必须拥有同名的 fixture 才能调用成功,否则会报错

  1. @given("I'm an author", target_fixture="author")
  2. def author():
  3. print("I'm an author")
  4. return dict(username="polo")
  5. @given("I'm the admin", target_fixture="author")
  6. def admin():
  7. print("I'm an admin")
  8. return dict(username="admin")

可以看到,两个 given 的 target_fixture 是同名的

  1. @given("I'm an author", target_fixture="author")
  2. def author():
  3. print("I'm an author")
  4. return dict(username="polo")
  5. # 假如这个 target_fixture 不是 author,那么运行就会报错:fixture 'author' not found
  6. @given("I'm the admin", target_fixture="admin")
  7. def admin():
  8. print("I'm an admin")
  9. return dict(username="admin")