test: add unit and integration tests for M4 chord parsing, template matching, and pipeline

This commit is contained in:
2026-11-02 11:00:06 +01:00
parent 983102b588
commit fcc1cd2426
2 changed files with 151 additions and 0 deletions

75
tests/test_chords.py Normal file
View File

@ -0,0 +1,75 @@
"""Unit tests for Harte chord parsing, key detection, and template chord recognition."""
import numpy as np
from songsplit.pipeline.s6_chords import estimate_key, extract_chords_template, parse_harte_chord
def test_parse_harte_chord_labels():
# Major triad
root, quality, bass = parse_harte_chord("C")
assert root == "C"
assert quality == "maj"
assert bass is None
# Minor triad
root, quality, bass = parse_harte_chord("Am")
assert root == "A"
assert quality == "min"
assert bass is None
# Dominant 7th
root, quality, bass = parse_harte_chord("G7")
assert root == "G"
assert quality == "7"
assert bass is None
# Sus4
root, quality, bass = parse_harte_chord("Dsus4")
assert root == "D"
assert quality == "sus4"
assert bass is None
# Slash chord
root, quality, bass = parse_harte_chord("F/A")
assert root == "F"
assert quality == "maj"
assert bass == "A"
# No chord
root, quality, bass = parse_harte_chord("N")
assert root is None
assert quality is None
assert bass is None
def test_estimate_key():
# Synthetic C major profile (peaks at C, E, G -> indices 0, 4, 7)
c_maj_chroma = np.zeros(12)
c_maj_chroma[0] = 5.0
c_maj_chroma[4] = 4.0
c_maj_chroma[7] = 4.5
assert estimate_key(c_maj_chroma) == "C"
# Synthetic A minor profile (peaks at A, C, E -> indices 9, 0, 4)
a_min_chroma = np.zeros(12)
a_min_chroma[9] = 5.0
a_min_chroma[0] = 4.0
a_min_chroma[4] = 4.5
assert estimate_key(a_min_chroma) == "Am"
def test_extract_chords_template_synthetic():
sr = 22050
duration = 1.0
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
# Synthesize C major: C4 (261.63), E4 (329.63), G4 (392.00)
c_chord = (np.sin(2 * np.pi * 261.63 * t) + np.sin(2 * np.pi * 329.63 * t) + np.sin(2 * np.pi * 392.00 * t)).astype(
np.float32
)
raw_chords = extract_chords_template(c_chord, sr)
labels = [ch for _, ch in raw_chords]
# Dominant detected chord should be "C"
assert labels.count("C") > len(labels) * 0.5