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

如何从测试文件获取TEST_NAME常量到conftest.py中

如何在conftest.py中获取测试文件的TEST_NAME常量

可以通过pytest fixture中的request对象的module属性直接访问测试文件的模块级常量,具体实现如下:

实现步骤

  1. 修改conftest.py中的fixture,利用request.module获取当前测试模块:
# conftest.py
import pytest

@pytest.fixture(scope="class")
def class_setup_teardown(request):
    # 从当前测试模块中获取TEST_NAME常量
    test_name = request.module.TEST_NAME
    print(f"Attempting to run {test_name} test case")
    
    # 可选:将test_name绑定到request.node,方便teardown阶段使用
    request.node.test_name = test_name
    
    # 执行测试用例前的setup逻辑
    yield
    
    # teardown阶段获取该测试名称
    print(f"Completed running {request.node.test_name} test case")
  1. 测试文件保持原有定义即可(比如test_01.py、test_02.py中的TEST_NAME):
# test_01.py
TEST_NAME = "C4901. Get results using lookup feature"

class TestLookupFeature:
    def test_lookup_results(self, class_setup_teardown):
        # 测试逻辑
        pass

原理说明

request.module指向当前执行测试用例所属的测试模块文件(即test_01.py、test_02.py对应的Python模块),因此直接通过request.module.TEST_NAME就能访问到文件中定义的模块级常量。

容错处理(可选)

如果存在未定义TEST_NAME的测试文件,可通过getattr避免抛出AttributeError:

test_name = getattr(request.module, "TEST_NAME", "未命名测试用例")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:08:26