修复测试snowboydecoder.py中的模拟对象创建问题

master
ganshihao21 5 months ago
parent 3aee067a00
commit 3c589f05c3

@ -2,44 +2,53 @@ import unittest
from unittest.mock import Mock, patch
from snowboydecoder import HotwordDetector
# 假设 RESOURCE_FILE 是在 snowboydecoder.py 中定义的
RESOURCE_FILE = 'path/to/resource.res'
RESOURCE_FILE = 'C:/Users/Lenovo/Desktop/项目/daomangzhang/src/Guide_stick_system/voice_assistant/resources/common.res'
class TestHotwordDetector(unittest.TestCase):
@patch('snowboydecoder.snowboydetect.SnowboyDetect')
@patch('snowboydecoder.pyaudio.PyAudio')
def test_init(self, mock_pyaudio, mock_snowboydetect):
# Mock SnowboyDetect
# 模拟SnowboyDetect对象
mock_detector = mock_snowboydetect.return_value
# 模拟NumChannels方法返回1
mock_detector.NumChannels.return_value = 1
# 模拟SampleRate方法返回16000
mock_detector.SampleRate.return_value = 16000
# 模拟BitsPerSample方法返回16
mock_detector.BitsPerSample.return_value = 16
# 模拟NumHotwords方法返回1
mock_detector.NumHotwords.return_value = 1
# Mock PyAudio
# 模拟PyAudio对象
mock_audio = mock_pyaudio.return_value
# Mock audio stream
# 模拟音频流
mock_stream = Mock()
mock_audio.open.return_value = mock_stream
# Initialize HotwordDetector
# 定义decoder_model
decoder_model = 'model_id'
# 定义sensitivity
sensitivity = 0.5
# 定义audio_gain
audio_gain = 1.0
# 实例化HotwordDetector
detector = HotwordDetector(decoder_model, RESOURCE_FILE, sensitivity, audio_gain)
# Verify interactions
# 检查SnowboyDetect是否被调用一次参数正确
mock_snowboydetect.assert_called_once_with(
resource_filename=RESOURCE_FILE.encode(),
model_str='model_id'.encode()
)
# 检查SetAudioGain是否被调用一次参数正确
mock_detector.SetAudioGain.assert_called_once_with(audio_gain)
# 检查SetSensitivity是否被调用一次参数正确
mock_detector.SetSensitivity.assert_called_once_with('0.5'.encode())
# Verify PyAudio and Stream configurations
# 检查PyAudio是否被调用一次
mock_pyaudio.assert_called_once()
# 检查PyAudio的open方法是否被调用一次参数正确
mock_audio.open.assert_called_once_with(
input=True, output=False,
format=mock_audio.get_format_from_width(2).return_value,
@ -49,7 +58,7 @@ class TestHotwordDetector(unittest.TestCase):
stream_callback=detector.audio_callback
)
# Verify RingBuffer size
# 检查ring_buffer的长度是否为0
self.assertEqual(len(detector.ring_buffer), 0)
if __name__ == '__main__':

Loading…
Cancel
Save