【问题标题】:How can I pass scenario specific arguments to pytest bdd after_scenario hook?如何将场景特定的参数传递给 pytest bdd after_scenario 挂钩?
【发布时间】:2021-08-31 10:05:35
【问题描述】:

我正在使用 pytest bdd 来执行 bdd 场景。示例:

Scenario Outline: entry with special character
Given I am an authenticated user
When I request entry information with <entryName> name
Then I expect a 200 response code
And I check the output list contains valid data
Examples:
  | entryName     |
  | #@            |

在场景中,我创建条目,然后查询并验证响应代码/输出。 无论场景是否成功,我都希望能够清理我创建的条目(因此插入另一行“然后我清理我的数据”不会实现我的目标)。

根据https://pytest-bdd.readthedocs.io/en/latest/ - 有一个pytest_bdd_after_scenario(request, feature, scenario) 挂钩,无论场景成功与否,我都可以执行清理。

  1. 我应该在哪里实施它? (我试着把它放在 test_my_scenario.py 中,但它没有被执行,根据https://github.com/pytest-dev/pytest-bdd/issues/174 看起来它应该在 conftest 中?)
  2. 如何将场景特定的参数传递给钩子?与 pytest_bdd_step_error 不同,它的签名中没有 func_args。那么如何清理我在场景中创建的特定条目呢?

【问题讨论】:

    标签: pytest bdd pytest-bdd


    【解决方案1】:
    1. 是的,您应该将pytest_bdd_after_scenario(request, feature, scenario) 钩子放在conftest.py 中,这样所有测试用例都会执行它。

    2. 您可以创建一个 pytest 夹具并将清理所需的所有数据存储在其中,然后通过调用 request.getfixturevalue(name_of_fixture)pytest_bdd_after_scenario(request, feature, scenario) 中检索该夹具

    例子:

    @pytest.fixture
    def context():
        return {'entryName': None}
    
    @when("I request entry information with <entryName> name")
    def do_post(context, entryName):
        # Do stuff here ...
        context['entryName'] = entryName
    
    def pytest_bdd_after_scenario(request, feature, scenario):
        context = request.getfixturevalue('context')
        entry_name = context['entryName']
        # Clean up entry ...
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-15
      • 2020-12-29
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多