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

使用Pytest测试Sounddevice回调函数遇NameError问题求助

问题:测试sounddevice回调函数时出现NameError错误

我用sounddevice库写了带回调函数的代码,想用pytest测试这个回调函数,只需要验证它不会抛出异常就行。但pytest一直提示回调函数的indata参数未定义,虽然我已经把回调函数导入测试文件了,而且原代码运行正常。我是Python新手,求帮忙。

测试代码

from project import callback

def test_callback():
    try:
        callback(indata, frames, time, status)
    except ValueError:
        assert False

pytest报错信息

_________ test_callback _________
def test_callback():
try:
callback(indata, frames, time, status)
E NameError: name 'indata' is not defined

解决方法
  • 报错原因很明确:你在调用callback时用到的indata、frames、time、status都是未定义的变量,Python找不到这些变量的取值,所以抛出了NameError。
  • sounddevice的回调函数是由库本身调用的,会自动传入符合要求的参数,但你手动测试时必须自己构造这些参数。

修正后的测试代码示例

import numpy as np
import sounddevice as sd
from project import callback

def test_callback():
    # 构造回调所需的模拟参数
    frames = 1024  # 选一个常用的音频帧大小即可
    indata = np.zeros((frames, 1))  # 模拟单通道的空输入音频数据
    time_info = None  # 如果你的回调里没用到time参数的具体属性,直接传None即可
    status = sd.CallbackStatus.NONE  # 无错误的状态

    try:
        callback(indata, frames, time_info, status)
    except Exception:  # 捕获所有异常,确保回调执行过程不会崩溃
        assert False

进阶模拟(如果回调用到time参数的属性)

如果你的回调函数里需要访问time对象的具体属性,比如currentTime,可以自己模拟一个TimeInfo类:

class MockTimeInfo:
    def __init__(self):
        self.currentTime = 0.0
        self.inputBufferAdcTime = 0.0
        self.outputBufferDacTime = 0.0

# 测试时使用这个模拟对象
time_info = MockTimeInfo()
callback(indata, frames, time_info, status)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:50:23