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

如何检测代码是否处于pytest运行环境?实现测试函数按需绘图

实现测试函数仅在非pytest环境下绘图的方案

你可以通过以下几种方式实现running_in_pytest()的判断逻辑,让绘图代码只在手动运行时执行:

方法1:检查pytest环境变量

pytest运行时会自动设置PYTEST_CURRENT_TEST环境变量,直接检查这个变量是否存在即可:

import os

def running_in_pytest():
    # 若当前在pytest环境中,该环境变量会被自动设置
    return "PYTEST_CURRENT_TEST" in os.environ

def test_my_func():
    output = my_func() 
    if not running_in_pytest():
        plot_my_output(output)

这种方法简单高效,是最常用的判断方式。

方法2:检查调用栈

通过inspect模块遍历调用栈,判断是否有pytest相关的代码在调用链中:

import inspect

def running_in_pytest():
    # 遍历调用栈的所有帧信息
    for frame_info in inspect.stack():
        # 判断帧的文件名是否包含pytest相关标识
        if "pytest" in frame_info.filename or "_pytest" in frame_info.filename:
            return True
    return False

def test_my_func():
    output = my_func() 
    if not running_in_pytest():
        plot_my_output(output)

这种方法不依赖环境变量,判断更精准,但性能略低于环境变量检查。

方法3:利用pytest的fixture标记

如果你需要在pytest中更精细化控制,可以自定义fixture传递运行环境标识:

import pytest

@pytest.fixture(scope="function")
def is_running_in_pytest():
    return True

def test_my_func(is_running_in_pytest):
    output = my_func() 
    if not is_running_in_pytest:
        plot_my_output(output)

# 手动运行时直接调用函数,传入非pytest标识
if __name__ == "__main__":
    test_my_func(is_running_in_pytest=False)

这种方式适合需要在pytest内部也有条件判断的复杂场景,但需要额外处理手动运行的入口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:29:52