如何在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
scenarioparameter passed to the hook holds all metadata about the running scenario, including itsnameattribute. - For your example Scenario Outline:
This hook will output exactly what you want:@sanity Scenario Outline: B) Change User Name and validate message Master Credentials Given the case is "<case>"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 scenarioscenario.line_number: Line number where the scenario startsscenario.tags: List of tags applied to the scenario (like@sanityin your example)
内容的提问来源于stack exchange,提问作者shujaat rahim
相关产品推荐
相关产品推荐

