Debian Codegraph @

tests/unit/media/test_synthesis.py

raw symbols SCIP
1 import os
2 import wave
3 import unittest
4
5 import pytest
6
7 from io import BytesIO
8
9 from pyglet.media.synthesis import *
10
11
12 local_dir = os.path.dirname(__file__)
13 test_data_path = os.path.abspath(os.path.join(local_dir, '..', '..', 'data'))
14 del local_dir
15
16
17 def get_test_data_file(*file_parts):
18 """Get a file from the test data directory in an OS independent way.
19
20 Supply relative file name as you would in os.path.join().
21 """
22 return os.path.join(test_data_path, *file_parts)
23
24
25 classes = [Silence, WhiteNoise, Sine, Triangle, Sawtooth, Square]
26 sample_rates = [44800, 11025]
27
28
29 @pytest.mark.parametrize('source_class', classes)
30 @pytest.mark.parametrize('sample_rate', sample_rates)
31 def test_instantiation(source_class, sample_rate):
32 source = source_class(duration=1, sample_rate=sample_rate)
33
34
35 @pytest.mark.parametrize('source_class', classes)
36 @pytest.mark.parametrize('sample_rate', sample_rates)
37 def test_total_duration(source_class, sample_rate):
38 source = source_class(duration=1) # One second of audio...
39 expected_bytes = source.audio_format.bytes_per_second # should match this.
40 audio_data = source.get_audio_data(expected_bytes + 100)
41
42 assert audio_data.length == pytest.approx(expected_bytes)
43 assert audio_data.duration == pytest.approx(1.0)
44 assert len(audio_data.data) == pytest.approx(expected_bytes)
45
46 # Should now be out of data
47 last_data = source.get_audio_data(100)
48 assert last_data is None
49
50
51 @pytest.mark.parametrize('source_class', classes)
52 @pytest.mark.parametrize('sample_rate', sample_rates)
53 def test_generated_bytes(source_class, sample_rate):
54 if source_class == WhiteNoise:
55 return
56
57 source = source_class(duration=1, sample_rate=sample_rate)
58 source_name = source_class.__name__.lower()
59 filename = "synthesis_{0}_{1}_{2}_1ch.wav".format(source_name, 16, sample_rate)
60
61 with wave.open(get_test_data_file('media', filename)) as f:
62 loaded_bytes = f.readframes(-1)
63 generated_data = source.get_audio_data(source._max_offset)
64 bytes_buffer = BytesIO(generated_data.data).getvalue()
65 # Compare a small chunk, to avoid hanging on mismatch:
66 assert bytes_buffer[:1000] == loaded_bytes[:1000], "Generated bytes do not match sample wave file."