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

pytest-bdd是否有before_feature钩子?需按特性标签仅执行一次代码

解决pytest-bdd特性级标签代码仅执行一次的问题

你现在的问题是用pytest_bdd_before_scenario钩子时,只要特性文件带@tag_is_at_feature_level标签,每个场景都会触发代码执行,但你需要这段代码不管文件里有多少场景都只跑一次。

最优解决方案:改用pytest_bdd_before_feature钩子

pytest-bdd提供了特性级别的钩子pytest_bdd_before_feature,这个钩子会在整个特性文件的所有场景执行前仅触发一次,刚好匹配你的需求。修改后的代码如下:

@pytest.hookimpl()
def pytest_bdd_before_feature(request, feature):
    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...")

为什么这个方案可行?

  • pytest_bdd_before_feature钩子的触发时机是特性文件加载后、所有场景执行前,每个特性文件只会触发一次
  • 直接通过feature.tags判断是否包含目标标签,逻辑清晰,不需要额外的状态标记

备选方案:用缓存标记避免重复执行(如果必须用场景钩子)

如果因为某些原因不能改用feature级钩子,可以用pytest的缓存机制记录已经处理过的特性文件,避免重复执行:

@pytest.hookimpl()
def pytest_bdd_before_scenario(request, feature, scenario):
    if "tag_is_at_feature_level" in feature.tags:
        # 用特性文件路径作为唯一标识,避免不同文件重复判断
        processed_key = f"feature_{feature.filename}_processed"
        # 检查缓存中是否已标记为处理过
        if not request.config.cache.get(processed_key, False):
            print(f"This process should run only once regardless of how many scenarios in the feature file...")
            # 标记为已处理
            request.config.cache.set(processed_key, True)

你的特性文件示例(供参考)

@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  | 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:32:33