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

Pytest:如何在每个test_file.py执行前仅运行一次初始化代码?

解决方案

方案一:模块级Fixture(延迟导入)

在conftest.py中定义模块级Fixture,通过在Fixture内部延迟导入common_library,规避conftest加载时的依赖问题。同时设置scope="module"保证代码仅在每个测试模块执行前运行一次,不会随参数化用例重复触发:

# conftest.py
import pytest

def _module_init():
    # 延迟导入,避免conftest初始化阶段的依赖冲突
    from common_library import serial_command
    # 此处编写需要执行的初始化逻辑
    ser = serial_command()
    ser.init_port()
    return ser

# autouse=True 自动应用到所有测试模块,无需在测试文件手动调用
@pytest.fixture(scope="module", autouse=True)
def module_setup():
    ser_instance = _module_init()
    yield ser_instance
    # 可选:模块执行结束后的清理逻辑
    # ser_instance.close_port()

方案二:自定义测试基类

在Test目录下创建测试基类文件,实现模块/类级别的初始化逻辑,所有测试文件的测试类继承该基类即可复用代码:

# Test/test_base.py
from common_library import serial_command

class TestBase:
    @classmethod
    def setup_class(cls):
        # 类级初始化,每个测试类对应一个测试模块执行前运行一次
        cls.ser = serial_command()
        cls.ser.init_port()
    
    @classmethod
    def teardown_class(cls):
        # 类级清理逻辑
        cls.ser.close_port()

# 或者使用模块级初始化函数(pytest会自动识别执行)
def setup_module(module):
    module.ser = serial_command()
    module.ser.init_port()

def teardown_module(module):
    module.ser.close_port()

测试文件中使用方式:

# Feature_folder_01/test_file_01.py
from test_base import TestBase

class TestFeature01(TestBase):
    def test_case1(self):
        # 直接使用基类初始化的串口实例
        self.ser.send_command("test_cmd")

方案三:利用pytest钩子函数pytest_module_started

在conftest.py中实现pytest_module_started钩子,该钩子会在每个测试模块启动时触发,同样通过延迟导入解决依赖问题:

# conftest.py
def pytest_module_started(session, module):
    # 模块启动时执行,此时可安全导入common_library
    from common_library import serial_command
    ser = serial_command()
    ser.init_port()
    # 将实例挂载到模块对象,方便测试用例调用
    module.serial_obj = ser

# 可选:模块执行结束后清理
def pytest_module_finished(session, module):
    if hasattr(module, "serial_obj"):
        module.serial_obj.close_port()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:50:15