def test_logging(ac='pyglet'): """Test logging to file (Pyglet).""" tempdir = _TempDir() orig_dir = os.getcwd() os.chdir(tempdir) try: with ExperimentController(*std_args, audio_controller=ac, response_device='keyboard', trigger_controller='dummy', **std_kwargs) as ec: test_name = ec._log_file stamp = ec.current_time ec.wait_until(stamp) # wait_until called w/already passed timest. with warnings.catch_warnings(record=True): warnings.simplefilter('always') ec.load_buffer([1., -1., 1., -1., 1., -1.]) # RMS warning with open(test_name) as fid: data = '\n'.join(fid.readlines()) # check for various expected log messages (TODO: add more) should_have = ['Participant: foo', 'Session: 01', 'wait_until was called', 'Stimulus max RMS ('] if ac == 'pyglet': should_have.append('Pyglet') else: should_have.append('TDT') for s in should_have: if s not in data: raise ValueError('Missing data: "{0}" in:\n{1}' ''.format(s, data)) finally: os.chdir(orig_dir)
def test_version(): """Test version assertions.""" with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(TypeError, assert_version, 1) assert_raises(TypeError, assert_version, '1' * 8) assert_raises(AssertionError, assert_version, 'x' * 7) assert_version(__version__[-7:]) assert_true(all('actual' in str(ww.message) for ww in w)) for want_version in ('090948e', 'cae6bc3', 'b6e8a81'): # old, broken, new tempdir = _TempDir() if not _has_git: assert_raises(ImportError, download_version, want_version, tempdir) else: assert_raises(IOError, download_version, want_version, op.join(tempdir, 'foo')) assert_raises(RuntimeError, download_version, 'x' * 7, tempdir) ex_dir = op.join(tempdir, 'expyfun') assert_true(not op.isdir(ex_dir)) download_version(want_version, tempdir) assert_true(op.isdir(ex_dir)) assert_true(op.isfile(op.join(ex_dir, '__init__.py'))) got_fname = op.join(ex_dir, '_version.py') with open(got_fname) as fid: line1 = fid.readline().strip() got_version = line1.split(' = ')[1][-8:-1] ex = want_version if want_version != 'cae6bc3' else '.dev0+c' assert_equal(got_version, ex, msg='File {0}: {1} != {2}'.format( got_fname, got_version, ex)) # auto dir determination orig_dir = os.getcwd() os.chdir(tempdir) try: assert_true(op.isdir('expyfun')) assert_raises(IOError, download_version, want_version) finally: os.chdir(orig_dir) # make sure we can get latest version tempdir_2 = _TempDir() if _has_git: assert_raises(IOError, download_version, dest_dir=tempdir) download_version(dest_dir=tempdir_2)
def test_data_line(): """Test writing of data lines """ entries = [['foo'], ['bar', 'bar\tbar'], ['bar2', r'bar\tbar'], ['fb', None, -0.5]] # this is what should be written to the file for each one goal_vals = ['None', 'bar\\tbar', 'bar\\\\tbar', 'None'] assert_equal(len(entries), len(goal_vals)) temp_dir = _TempDir() these_kwargs = deepcopy(std_kwargs) these_kwargs['output_dir'] = temp_dir with ExperimentController(*std_args, stim_fs=44100, **these_kwargs) as ec: for ent in entries: ec.write_data_line(*ent) fname = ec._data_file.name with open(fname) as fid: lines = fid.readlines() # check the header assert_equal(len(lines), len(entries) + 4) # header, colnames, flip, stop assert_equal(lines[0][0], '#') # first line is a comment for x in ['timestamp', 'event', 'value']: # second line is col header assert_true(x in lines[1]) assert_true('flip' in lines[2]) # ec.__init__ ends with a flip assert_true('stop' in lines[-1]) # last line is stop (from __exit__) outs = lines[1].strip().split('\t') assert_true( all(l1 == l2 for l1, l2 in zip(outs, ['timestamp', 'event', 'value']))) # check the entries ts = [] for line, ent, gv in zip(lines[3:], entries, goal_vals): outs = line.strip().split('\t') assert_equal(len(outs), 3) # check timestamping if len(ent) == 3 and ent[2] is not None: assert_equal(outs[0], str(ent[2])) else: ts.append(float(outs[0])) # check events assert_equal(outs[1], ent[0]) # check values assert_equal(outs[2], gv) # make sure we got monotonically increasing timestamps ts = np.array(ts) assert_true(np.all(ts[1:] >= ts[:-1]))
def test_integrated_version_checking(): """Test EC version checking during init.""" tempdir = _TempDir() args = ['test'] # experiment name kwargs = dict(output_dir=tempdir, full_screen=False, window_size=(1, 1), participant='foo', session='01', stim_db=0.0, noise_db=0.0, verbose=True) assert_raises(RuntimeError, ExperimentController, *args, version=None, **kwargs) assert_raises(AssertionError, ExperimentController, *args, version='59f3f5b', **kwargs) # the very first commit
import warnings from nose.tools import assert_raises, assert_true from genz.static.expyfun import EyelinkController, ExperimentController from genz.static.expyfun import _TempDir, _hide_window, requires_opengl21 warnings.simplefilter('always') std_args = ['test'] temp_dir = _TempDir() std_kwargs = dict(output_dir=temp_dir, full_screen=False, window_size=(1, 1), participant='foo', session='01', noise_db=0, version='dev') @_hide_window @requires_opengl21 def test_eyelink_methods(): """Test EL methods.""" with ExperimentController(*std_args, **std_kwargs) as ec: assert_raises(ValueError, EyelinkController, ec, fs=999) el = EyelinkController(ec) assert_raises(RuntimeError, EyelinkController, ec) # can't have 2 open assert_raises(ValueError, el.custom_calibration, ctype='hey') el.custom_calibration('H3') el.custom_calibration('HV9')
def test_crm(): """Test CRM Corpus functions.""" fs = 40000 # native rate, to avoid large resampling delay in testing crm_info() tempdir = _TempDir() # corpus prep talkers = [dict(sex='f', talker_num=0)] crm_prepare_corpus(fs, path_out=tempdir, talker_list=talkers, n_jobs=np.inf) crm_prepare_corpus(fs, path_out=tempdir, talker_list=talkers, overwrite=True) # no overwrite assert_raises(RuntimeError, crm_prepare_corpus, fs, path_out=tempdir) # load sentence from hard drive crm_sentence(fs, 'f', 0, 0, 0, 0, 0, ramp_dur=0, path=tempdir) crm_sentence(fs, 1, '0', 'charlie', 'red', '5', stereo=True, path=tempdir) # bad value requested assert_raises(ValueError, crm_sentence, fs, 1, 0, 0, 'periwinkle', 0, path=tempdir) # unprepared talker assert_raises(RuntimeError, crm_sentence, fs, 'm', 0, 0, 0, 0, path=tempdir) # unprepared sampling rate assert_raises(RuntimeError, crm_sentence, fs + 1, 0, 0, 0, 0, 0, path=tempdir) # CRMPreload class crm = CRMPreload(fs, path=tempdir) crm.sentence('f', 0, 0, 0, 0) # unprepared sampling rate assert_raises(RuntimeError, CRMPreload, fs + 1) # bad value requested assert_raises(ValueError, crm.sentence, 1, 0, 0, 'periwinkle', 0) # unprepared talker assert_raises(RuntimeError, crm.sentence, 'm', 0, 0, 0, 0) # try to specify parameters like fs, stereo, etc. assert_raises(TypeError, crm.sentence, fs, '1', '0', 'charlie', 'red', '5') # add_pad x1 = np.zeros(10) x2 = np.ones((2, 5)) x = add_pad([x1, x2]) assert_true(np.sum(x[..., -1] == 0)) x = add_pad((x1, x2), 'center') assert_true(np.sum(x[..., -1] == 0) and np.sum(x[..., 0] == 0)) x = add_pad((x1, x2), 'end') assert_true(np.sum(x[..., 0] == 0))
# -*- coding: utf-8 -*- import warnings from os import path as op import numpy as np from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array_almost_equal, assert_array_equal from genz.static.expyfun import _TempDir, _has_scipy_version from genz.static.expyfun import read_wav, write_wav warnings.simplefilter('always') tempdir = _TempDir() def test_read_write_wav(): """Test reading and writing WAV files """ fname = op.join(tempdir, 'temp.wav') data = np.r_[np.random.rand(1000), 1, -1] fs = 44100 # Use normal 16-bit precision: not great write_wav(fname, data, fs) data_read, fs_read = read_wav(fname) assert_equal(fs_read, fs) assert_array_almost_equal(data[np.newaxis, :], data_read, 4) # test our overwrite check assert_raises(IOError, write_wav, fname, data, fs)