utils/music_theory/music_theory/tests/test_wav.py
Krzysztof kuhy Rudnicki d5b3f2cff3 music_theory: music theory from first principles, as code you can hear
New subproject porting Luke Haas's "Music Theory for Programmers" section
by section into typed Python: pitch (MIDI <-> Hz), tuning (harmonic
series, the Pythagorean comma, brute-forced "why twelve"), scales as step
arrays with modes as rotations, chords stacked in thirds with Roman
numerals and the V7 -> I resolution, named progressions, a numpy synth
(waveforms, ADSR, low-pass), a bar-exact sequencer, and a seeded Recipe ->
WAV composer. `degrade` is the same piece ruined by a 0..1 amount, so an
ending can be the opening destroyed on the same seed; filtering runs LAST
because filtering first measured brighter than the clean render.

17 demos (`python -m music_theory demo all`) each print the article's
numbers -- the comma is 1.013643, the tempered fifth is 0.113 % flat,
twelve is the first acceptable division -- and the FFT of the render, so
the claims are tested rather than asserted. 157 tests, 100 % branch
coverage, ruff ALL, mypy strict, pylint 10.

Consumed next by roadside-assistance for its three world-state beds.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VC17zymxkeiUcHrMvt8W5W
2026-09-11 18:29:13 +02:00

43 lines
1.2 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki
from typing import TYPE_CHECKING
import wave
import numpy as np
import pytest
from music_theory import synth, wav
if TYPE_CHECKING:
from pathlib import Path
def test_write_and_read_round_trip(tmp_path: Path) -> None:
signal = synth.oscillator(440.0, 0.1)
path = wav.write(tmp_path / "sub" / "a.wav", signal, 8000)
back, rate = wav.read(path)
assert rate == 8000
assert len(back) == len(signal)
assert np.allclose(back, signal, atol=1e-3)
def test_read_rejects_stereo(tmp_path: Path) -> None:
path = tmp_path / "stereo.wav"
with wave.Wave_write(str(path)) as handle:
handle.setnchannels(2)
handle.setsampwidth(2)
handle.setframerate(8000)
handle.writeframes(b"\0\0\0\0")
with pytest.raises(ValueError, match="16-bit mono"):
wav.read(path)
def test_sha256_is_stable(tmp_path: Path) -> None:
path = wav.write(tmp_path / "a.wav", np.zeros(10))
assert wav.sha256(path) == wav.sha256(path)
assert len(wav.sha256(path)) == 64
def test_duration_and_play_command(tmp_path: Path) -> None:
assert wav.duration_seconds(np.zeros(22050)) == 1.0
assert wav.play_command(tmp_path / "x.wav").startswith("aplay -q ")