| 1 | import re |
| 2 | from unittest import TestCase |
| 3 | |
| 4 | import numpy |
| 5 | |
| 6 | from pgzero.tone import ( |
| 7 | sine_array_onecycle, note_value, |
| 8 | note_to_hertz, validate_note, InvalidNote |
| 9 | ) |
| 10 | |
| 11 | TEST_NOTES = { |
| 12 | 'A4': dict(val = 0, hertz = 440, parts = ('A', '', 4)), |
| 13 | 'C4': dict(val = -9, hertz = 261.63, parts = ('C', '', 4)), |
| 14 | 'C0': dict(val = -57, hertz = 16.35, parts = ('C', '', 0)), |
| 15 | 'B8': dict(val = 50, hertz = 7902.13, parts = ('B', '', 8)), |
| 16 | 'A#4': dict(val = 1, hertz = 466.16, parts = ('A', '#', 4)), |
| 17 | 'Ab4': dict(val = -1, hertz = 415.30, parts = ('A', 'b', 4)), |
| 18 | 'Bb4': dict(val = 1, hertz = 466.16, parts = ('B', 'b', 4)), |
| 19 | } |
| 20 | |
| 21 | class ToneTest(TestCase): |
| 22 | def test_sine_array(self): |
| 23 | numpy.allclose( |
| 24 | sine_array_onecycle(2205), |
| 25 | numpy.array( |
| 26 | [0, 19260, 31164, 31164, 19260, 0, -19260, -31164, -31164, -19260], |
| 27 | dtype=numpy.int16 |
| 28 | ) |
| 29 | ) |
| 30 | |
| 31 | def test_validate_note(self): |
| 32 | for note, val in TEST_NOTES.items(): |
| 33 | self.assertEqual(validate_note(note), val['parts']) |
| 34 | |
| 35 | for note in ['A9', 'H4', '4A', 'a4', 'Az4']: |
| 36 | with self.assertRaisesRegex(InvalidNote, re.escape('%s is not a valid note. notes are A-F, are either normal, flat (b) or sharp (#) and of octave 0-8' % note)): |
| 37 | validate_note(note) |
| 38 | |
| 39 | def test_note_value(self): |
| 40 | for note, val in TEST_NOTES.items(): |
| 41 | self.assertEqual(note_value(*val['parts']), val['val']) |
| 42 | |
| 43 | |
| 44 | def test_note_to_hertz(self): |
| 45 | for note, val in TEST_NOTES.items(): |
| 46 | self.assertAlmostEqual(note_to_hertz(note), val['hertz'], 2) |
| 47 |