You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest-bdd中通过pytest_bdd_before_scenario获取场景名称

Retrieve Scenario Name with pytest-bdd's pytest_bdd_before_scenario Hook

Got it, let's get that scenario name for you! The pytest_bdd_before_scenario hook gives you direct access to the scenario object, which includes the exact name you're looking for. Here's how to set it up:

Step 1: Add the Hook to conftest.py

Create or update your conftest.py file (typically placed in your test root directory) with this code:

def pytest_bdd_before_scenario(request, scenario):
    # Pull the scenario name from the scenario object
    scenario_name = scenario.name
    # Print or use the name as required
    print(f"scenario : {scenario_name}")

How It Works

  • The scenario parameter passed to the hook holds all metadata about the running scenario, including its name attribute.
  • For your example Scenario Outline:
    @sanity
    Scenario Outline: B) Change User Name and validate message Master Credentials
      Given the case is "<case>"
    
    This hook will output exactly what you want:
    scenario : B) Change User Name and validate message Master Credentials
    

Bonus: Access Extra Scenario Context

If you need more details about the scenario, the scenario object has additional useful attributes:

  • scenario.filename: Path to the feature file containing the scenario
  • scenario.line_number: Line number where the scenario starts
  • scenario.tags: List of tags applied to the scenario (like @sanity in your example)

内容的提问来源于stack exchange,提问作者shujaat rahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:45:49