要求是基于在功能级别定义的自定义标签,针对功能文件中的所有场景运行代码“一次”。我已经在 pytest.ini 中定义了自定义标签。 但是,以下代码会针对功能文件中的每个场景执行。无论功能文件中有多少场景,我都只需要执行一次:
@pytest.hookimpl()
@pytest.mark.tag_is_at_feature_level
def pytest_bdd_before_scenario(request, feature, scenario):
if "tag_is_at_feature_level" in feature.tags:
print(f"This process should run only once regardless of how many scenarios in the feature file...")
这是功能文件:
@tag_is_at_feature_level
Feature: TableStructureValidation
This feature is to validate table structure
Scenario: Table Structure Validation - table_name
When I query the INFORMATION_SCHEMA.COLUMNS for the table "table_name" from the databse "database_name"
Then I should see following table definition in the INFORMATION_SCHEMA.COLUMNS:
| COLUMN_NAME | COLUMN_DEFAULT | IS_NULLABLE | DATA_TYPE |
| FileName | | YES | varchar |
| TotalRowsSourceFile | | YES | bigint |
| TotalRowsLoadedToDB | | YES | bigint |
| Validation | | YES | varchar |
| LoadTime | (getdate()) | YES | datetime |
import pytest
from pytest_bdd import scenario, given, when, then, parsers
# Define a fixture that checks for the custom tag and runs once per feature
@pytest.fixture(scope="session")
def check_feature_tag(request):
feature_tags = request.node.iter_markers_with_node(name='tag_is_at_feature_level')
has_tag = any(node for marker, node in feature_tags if node.parent is None) # Check if the tag is at the feature level
if has_tag:
print("This process should run only once regardless of how many scenarios in the feature file.")
# Use the fixture in your scenarios
@scenario('your_feature_file.feature', 'Table Structure Validation - table_name')
def test_table_structure():
pass
@given("I query the INFORMATION_SCHEMA.COLUMNS for the table 'table_name' from the database 'database_name'")
def step_impl():
# Your step implementation here
pass
@then("I should see following table definition in the INFORMATION_SCHEMA.COLUMNS:")
def step_impl():
# Your step implementation here
pass
# Make sure to use the fixture in the test function
def test_features(check_feature_tag):
# This test function will use the fixture that runs once per feature
pass