audio: add mocking UT

This commit is contained in:
Roman Zeyde
2015-01-06 17:34:26 +02:00
parent 7f9e84dd02
commit bd329c19d0
3 changed files with 29 additions and 34 deletions

View File

@@ -1,3 +1,4 @@
sudo: false
language: python
python:
- "2.6"
@@ -6,9 +7,6 @@ python:
- "3.3"
- "3.4"
before_install:
- sudo apt-get install portaudio19-dev
install:
- pip install .
- pip install coveralls pep8 mock

View File

@@ -7,11 +7,11 @@ log = logging.getLogger(__name__)
class Library(object):
def __init__(self, name):
self.lib = ctypes.CDLL(name)
self.lib.Pa_GetVersionText.restype = ctypes.c_char_p
log.debug('Library version: "%s"', self.lib.Pa_GetVersionText())
self.lib.Pa_GetErrorText.restype = ctypes.c_char_p
assert self.lib.Pa_GetErrorText(0) == 'Success'
self.streams = []
assert self._error_string(0) == 'Success'
def _error_string(self, code):
return self.call('GetErrorText', code, restype=ctypes.c_char_p)
def call(self, name, *args, **kwargs):
func = getattr(self.lib, 'Pa_{0}'.format(name))
@@ -20,7 +20,7 @@ class Library(object):
def _error_check(self, res):
if res != 0:
raise Exception(res, self.lib.Pa_GetErrorText(res))
raise Exception(res, self._error_string(res))
def __enter__(self):
self.call('Initialize')

View File

@@ -1,33 +1,30 @@
from amodem import audio
from amodem import config
import mock
import pytest
def test_pyaudio_mock():
m = mock.Mock()
m.paInt16 = 8
m.PyAudio.return_value = m
m.open.return_value = m
def test():
length = 1024
data = b'\x12\x34' * length
with mock.patch('ctypes.CDLL') as cdll:
lib = mock.Mock()
lib.Pa_GetErrorText = lambda code: 'Error' if code else 'Success'
lib.Pa_GetDefaultInputDevice.return_value = 1
lib.Pa_OpenStream.return_value = 0
cdll.return_value = lib
interface = audio.Library('portaudio')
with interface:
s = interface.player()
s.stream = 1 # simulate non-zero output stream handle
s.write(data=data)
s.close()
cfg = config.fastest()
interface = audio.Interface(config=cfg, library=m)
recorder = interface.recorder()
n = 1024
data = recorder.read(n)
with interface:
s = interface.recorder()
s.stream = 2 # simulate non-zero input stream handle
s.read(len(data))
s.close()
data = '\x00' * n
player = interface.player()
player.write(data)
kwargs = dict(
channels=1, frames_per_buffer=cfg.samples_per_buffer,
rate=cfg.Fs, format=m.paInt16
)
assert m.mock_calls == [
mock.call.PyAudio(),
mock.call.open(input=True, **kwargs),
mock.call.read(n // cfg.sample_size),
mock.call.open(output=True, **kwargs),
mock.call.write(data)
]
with pytest.raises(Exception):
interface._error_check(1)