Make unit tests use a mock version of PyAudio, while making integration tests using the real version. If no real microphone is available, these integration tests are skipped. ref: N25B-119
86 lines
2.7 KiB
Python
86 lines
2.7 KiB
Python
# coding=utf-8
|
||
import mock
|
||
import pytest
|
||
|
||
from common.microphone_utils import MicrophoneUtils
|
||
from robot_interface.utils.microphone import choose_mic_default, choose_mic_interactive
|
||
|
||
|
||
class MockPyAudio:
|
||
def __init__(self):
|
||
# You can predefine fake device info here
|
||
self.devices = [
|
||
{
|
||
"index": 0,
|
||
"name": u"Someone’s Microphone", # Using a Unicode ’ character
|
||
"maxInputChannels": 2,
|
||
"maxOutputChannels": 0,
|
||
"defaultSampleRate": 44100.0,
|
||
"defaultLowInputLatency": 0.01,
|
||
"defaultLowOutputLatency": 0.01,
|
||
"defaultHighInputLatency": 0.1,
|
||
"defaultHighOutputLatency": 0.1,
|
||
"hostApi": 0,
|
||
},
|
||
{
|
||
"index": 1,
|
||
"name": u"Mock Speaker 1",
|
||
"maxInputChannels": 0,
|
||
"maxOutputChannels": 2,
|
||
"defaultSampleRate": 48000.0,
|
||
"defaultLowInputLatency": 0.01,
|
||
"defaultLowOutputLatency": 0.01,
|
||
"defaultHighInputLatency": 0.1,
|
||
"defaultHighOutputLatency": 0.1,
|
||
"hostApi": 0,
|
||
},
|
||
]
|
||
|
||
def get_device_count(self):
|
||
"""Return the number of available mock devices."""
|
||
return len(self.devices)
|
||
|
||
def get_device_info_by_index(self, index):
|
||
"""Return information for a given mock device index."""
|
||
if 0 <= index < len(self.devices):
|
||
return self.devices[index]
|
||
else:
|
||
raise IOError("Invalid device index: {}".format(index))
|
||
|
||
def get_default_input_device_info(self):
|
||
"""Return info for a default mock input device."""
|
||
for device in self.devices:
|
||
if device.get("maxInputChannels", 0) > 0:
|
||
return device
|
||
raise IOError("No default input device found")
|
||
|
||
|
||
@pytest.fixture
|
||
def pyaudio_instance():
|
||
return MockPyAudio()
|
||
|
||
|
||
def _raise_io_error():
|
||
raise IOError()
|
||
|
||
|
||
class TestAudioUnit(MicrophoneUtils):
|
||
"""Run shared audio behavior tests with the mock implementation."""
|
||
def test_choose_mic_default_no_mic(self):
|
||
mock_pyaudio = mock.Mock()
|
||
mock_pyaudio.get_device_count = mock.Mock(return_value=0L)
|
||
mock_pyaudio.get_default_input_device_info = _raise_io_error
|
||
|
||
result = choose_mic_default(mock_pyaudio)
|
||
|
||
assert result is None
|
||
|
||
def test_choose_mic_interactive_no_mic(self):
|
||
mock_pyaudio = mock.Mock()
|
||
mock_pyaudio.get_device_count = mock.Mock(return_value=0L)
|
||
mock_pyaudio.get_default_input_device_info = _raise_io_error
|
||
|
||
result = choose_mic_interactive(mock_pyaudio)
|
||
|
||
assert result is None
|