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 language: python
python: python:
- "2.6" - "2.6"
@@ -6,9 +7,6 @@ python:
- "3.3" - "3.3"
- "3.4" - "3.4"
before_install:
- sudo apt-get install portaudio19-dev
install: install:
- pip install . - pip install .
- pip install coveralls pep8 mock - pip install coveralls pep8 mock

View File

@@ -7,11 +7,11 @@ log = logging.getLogger(__name__)
class Library(object): class Library(object):
def __init__(self, name): def __init__(self, name):
self.lib = ctypes.CDLL(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 = [] 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): def call(self, name, *args, **kwargs):
func = getattr(self.lib, 'Pa_{0}'.format(name)) func = getattr(self.lib, 'Pa_{0}'.format(name))
@@ -20,7 +20,7 @@ class Library(object):
def _error_check(self, res): def _error_check(self, res):
if res != 0: if res != 0:
raise Exception(res, self.lib.Pa_GetErrorText(res)) raise Exception(res, self._error_string(res))
def __enter__(self): def __enter__(self):
self.call('Initialize') self.call('Initialize')

View File

@@ -1,33 +1,30 @@
from amodem import audio from amodem import audio
from amodem import config
import mock import mock
import pytest
def test_pyaudio_mock(): def test():
m = mock.Mock() length = 1024
m.paInt16 = 8 data = b'\x12\x34' * length
m.PyAudio.return_value = m with mock.patch('ctypes.CDLL') as cdll:
m.open.return_value = m 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() with interface:
interface = audio.Interface(config=cfg, library=m) s = interface.recorder()
recorder = interface.recorder() s.stream = 2 # simulate non-zero input stream handle
n = 1024 s.read(len(data))
data = recorder.read(n) s.close()
data = '\x00' * n with pytest.raises(Exception):
player = interface.player() interface._error_check(1)
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)
]