Spaces:
Sleeping
Sleeping
File size: 20,136 Bytes
8648e23 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | """
Pure unit tests for src/core/data_structures.py — no file I/O required.
Coverage:
TimeSignature – construction, properties, validation
MusicalEvent – construction, pitch_class, offset, transpose, validation
Chord – construction, offset, validation
HarmonicSegment – construction, duration, new optional fields
RomanNumeral.label – representative notation cases
KeyEstimate – construction, label, validation
Score – event sorting, time-sig lookup, range queries, properties
"""
import pytest
from fractions import Fraction
from src.core.data_structures import (
Chord,
HarmonicFunction,
HarmonicSegment,
KeyEstimate,
MusicalEvent,
ProlongationLevel,
RomanNumeral,
Score,
TimeSignature,
)
# ===========================================================================
# TimeSignature
# ===========================================================================
class TestTimeSignature:
def test_simple_4_4(self):
ts = TimeSignature(4, 4)
assert not ts.is_compound
assert ts.beats_per_measure == 4
assert ts.beat_duration == Fraction(1)
def test_simple_3_4(self):
ts = TimeSignature(3, 4)
assert not ts.is_compound
assert ts.beats_per_measure == 3
assert ts.beat_duration == Fraction(1)
def test_simple_2_4(self):
ts = TimeSignature(2, 4)
assert not ts.is_compound
assert ts.beats_per_measure == 2
assert ts.beat_duration == Fraction(1)
def test_compound_6_8(self):
ts = TimeSignature(6, 8)
assert ts.is_compound
assert ts.beats_per_measure == 2
assert ts.beat_duration == Fraction(3, 2)
def test_compound_9_8(self):
ts = TimeSignature(9, 8)
assert ts.is_compound
assert ts.beats_per_measure == 3
assert ts.beat_duration == Fraction(3, 2)
def test_compound_12_8(self):
ts = TimeSignature(12, 8)
assert ts.is_compound
assert ts.beats_per_measure == 4
assert ts.beat_duration == Fraction(3, 2)
def test_str(self):
assert str(TimeSignature(4, 4)) == "4/4"
assert str(TimeSignature(6, 8)) == "6/8"
assert str(TimeSignature(3, 4)) == "3/4"
def test_invalid_zero_numerator(self):
with pytest.raises(ValueError):
TimeSignature(0, 4)
def test_invalid_denominator(self):
with pytest.raises(ValueError):
TimeSignature(4, 3) # 3 not in [1, 2, 4, 8, 16, 32]
def test_is_frozen(self):
ts = TimeSignature(4, 4)
with pytest.raises(Exception):
ts.numerator = 3 # type: ignore[misc]
# ===========================================================================
# MusicalEvent
# ===========================================================================
class TestMusicalEvent:
def test_valid_note(self):
ev = MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1))
assert ev.pitch == 60
assert not ev.is_rest
assert ev.pitch_class == 0
def test_valid_rest(self):
ev = MusicalEvent(
pitch=None, onset=Fraction(0), duration=Fraction(1),
velocity=0, is_rest=True,
)
assert ev.is_rest
assert ev.pitch is None
assert ev.pitch_class is None
def test_offset(self):
ev = MusicalEvent(pitch=60, onset=Fraction(1), duration=Fraction(2))
assert ev.offset == Fraction(3)
def test_pitch_class_c(self):
assert MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1)).pitch_class == 0
def test_pitch_class_g(self):
assert MusicalEvent(pitch=67, onset=Fraction(0), duration=Fraction(1)).pitch_class == 7
def test_pitch_class_wraps(self):
assert MusicalEvent(pitch=72, onset=Fraction(0), duration=Fraction(1)).pitch_class == 0
def test_transpose_up(self):
ev = MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1))
up = ev.transpose(12)
assert up.pitch == 72
assert up.onset == ev.onset
assert up.duration == ev.duration
assert up is not ev
def test_transpose_clamps_high(self):
ev = MusicalEvent(pitch=120, onset=Fraction(0), duration=Fraction(1))
assert ev.transpose(20).pitch == 127
def test_transpose_clamps_low(self):
ev = MusicalEvent(pitch=5, onset=Fraction(0), duration=Fraction(1))
assert ev.transpose(-20).pitch == 0
def test_transpose_rest_returns_self(self):
rest = MusicalEvent(
pitch=None, onset=Fraction(0), duration=Fraction(1),
velocity=0, is_rest=True,
)
assert rest.transpose(12) is rest
def test_invalid_none_pitch_on_note(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=None, onset=Fraction(0), duration=Fraction(1))
def test_invalid_pitch_set_on_rest(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1),
velocity=0, is_rest=True)
def test_invalid_pitch_out_of_range(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=200, onset=Fraction(0), duration=Fraction(1))
def test_invalid_velocity(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1), velocity=200)
def test_invalid_zero_duration(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(0))
def test_invalid_beat_strength_too_high(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1), beat_strength=1.5)
def test_invalid_beat_strength_negative(self):
with pytest.raises(ValueError):
MusicalEvent(pitch=60, onset=Fraction(0), duration=Fraction(1), beat_strength=-0.1)
# ===========================================================================
# Chord
# ===========================================================================
class TestChord:
def test_valid_construction(self):
c = Chord(
onset=Fraction(0), duration=Fraction(1),
root=0, quality='major',
pitches=frozenset([0, 4, 7]), bass=0,
)
assert c.root == 0
assert c.offset == Fraction(1)
assert c.inversion == 0
def test_first_inversion(self):
c = Chord(
onset=Fraction(0), duration=Fraction(1),
root=0, quality='major',
pitches=frozenset([0, 4, 7]), bass=4, inversion=1,
)
assert c.bass == 4
assert c.inversion == 1
def test_invalid_root(self):
with pytest.raises(ValueError):
Chord(onset=Fraction(0), duration=Fraction(1),
root=12, quality='major', pitches=frozenset([0, 4, 7]), bass=0)
def test_invalid_bass(self):
with pytest.raises(ValueError):
Chord(onset=Fraction(0), duration=Fraction(1),
root=0, quality='major', pitches=frozenset([0, 4, 7]), bass=-1)
def test_invalid_duration(self):
with pytest.raises(ValueError):
Chord(onset=Fraction(0), duration=Fraction(0),
root=0, quality='major', pitches=frozenset([0, 4, 7]), bass=0)
# ===========================================================================
# HarmonicSegment
# ===========================================================================
class TestHarmonicSegment:
def test_valid_segment(self):
seg = HarmonicSegment(start=Fraction(0), end=Fraction(4),
key_tonic=0, key_mode='major')
assert seg.duration == Fraction(4)
assert seg.roman_numerals == []
assert seg.prolongation_level is None
assert seg.chords == []
def test_duration_property(self):
seg = HarmonicSegment(start=Fraction(2), end=Fraction(7),
key_tonic=7, key_mode='minor')
assert seg.duration == Fraction(5)
def test_with_prolongation_level(self):
seg = HarmonicSegment(
start=Fraction(0), end=Fraction(4),
key_tonic=0, key_mode='major',
prolongation_level=ProlongationLevel.FOREGROUND,
)
assert seg.prolongation_level == ProlongationLevel.FOREGROUND
def test_end_before_start_raises(self):
with pytest.raises(ValueError):
HarmonicSegment(start=Fraction(4), end=Fraction(0),
key_tonic=0, key_mode='major')
def test_invalid_key_tonic(self):
with pytest.raises(ValueError):
HarmonicSegment(start=Fraction(0), end=Fraction(4),
key_tonic=12, key_mode='major')
def test_invalid_key_mode(self):
with pytest.raises(ValueError):
HarmonicSegment(start=Fraction(0), end=Fraction(4),
key_tonic=0, key_mode='dorian')
# ===========================================================================
# RomanNumeral.label
# ===========================================================================
class TestRomanNumeralLabel:
"""
Tests are grouped by chord family. Cases are chosen for the most common
patterns; secondary dominants and inversions get dedicated tests.
Note: for seventh chords, the label is built as base + inversion_figure
(e.g. V + 7 → V7). Quality markers for dim7 / half-dim7 / major7 are
*not* added in the current implementation — see TODO in data_structures.py.
"""
# -- helpers --
@staticmethod
def _rn(degree, quality, inversion, mode='major',
is_secondary=False, secondary_target=None):
return RomanNumeral(
degree=degree, quality=quality, inversion=inversion,
local_key_tonic=0, local_key_mode=mode,
is_secondary=is_secondary, secondary_target=secondary_target,
)
# Triads – major mode
def test_I(self):
assert self._rn(1, 'major', 0).label == 'I'
def test_I6(self):
assert self._rn(1, 'major', 1).label == 'I6'
def test_I64(self):
assert self._rn(1, 'major', 2).label == 'I64'
def test_ii(self):
assert self._rn(2, 'minor', 0).label == 'ii'
def test_IV(self):
assert self._rn(4, 'major', 0).label == 'IV'
def test_V(self):
assert self._rn(5, 'major', 0).label == 'V'
def test_V6(self):
assert self._rn(5, 'major', 1).label == 'V6'
def test_viio(self):
assert self._rn(7, 'diminished', 0).label == 'viio'
def test_viio6(self):
assert self._rn(7, 'diminished', 1).label == 'viio6'
def test_iio6(self):
assert self._rn(2, 'diminished', 1).label == 'iio6'
# Seventh chords – dominant7 (dominant7 label is correct out of the box)
def test_V7(self):
assert self._rn(5, 'dominant7', 0).label == 'V7'
def test_V65(self):
assert self._rn(5, 'dominant7', 1).label == 'V65'
def test_V43(self):
assert self._rn(5, 'dominant7', 2).label == 'V43'
def test_V42(self):
assert self._rn(5, 'dominant7', 3).label == 'V42'
# Secondary dominants
def test_V7_of_V(self):
assert self._rn(5, 'dominant7', 0,
is_secondary=True, secondary_target=5).label == 'V7/V'
def test_V7_of_iv_in_minor(self):
rn = RomanNumeral(
degree=5, quality='dominant7', inversion=0,
local_key_tonic=0, local_key_mode='minor',
is_secondary=True, secondary_target=4,
)
assert rn.label == 'V7/iv'
# Minor mode triads
def test_i_minor(self):
rn = RomanNumeral(degree=1, quality='minor', inversion=0,
local_key_tonic=0, local_key_mode='minor')
assert rn.label == 'i'
def test_iv_minor(self):
rn = RomanNumeral(degree=4, quality='minor', inversion=0,
local_key_tonic=0, local_key_mode='minor')
assert rn.label == 'iv'
def test_V_in_minor(self):
rn = RomanNumeral(degree=5, quality='major', inversion=0,
local_key_tonic=0, local_key_mode='minor')
assert rn.label == 'V'
# Seventh chords – quality marks (fixed from known gap)
def test_dim7_root_position(self):
assert self._rn(7, 'dim7', 0).label == 'viio7'
def test_half_dim7_root_position(self):
assert self._rn(7, 'half-dim7', 0).label == 'viiø7'
def test_major7_root_position(self):
assert self._rn(1, 'major7', 0).label == 'IM7'
def test_minor7_root_position(self):
assert self._rn(2, 'minor7', 0).label == 'ii7'
def test_dim7_first_inversion(self):
assert self._rn(7, 'dim7', 1).label == 'viio65'
def test_half_dim7_second_inversion(self):
assert self._rn(7, 'half-dim7', 2).label == 'viiø43'
# ===========================================================================
# HarmonicEvent
# ===========================================================================
class TestHarmonicEvent:
def _make_chord(self, onset=0, dur=4):
from src.core.data_structures import Chord
return Chord(
onset=Fraction(onset), duration=Fraction(dur),
root=0, quality='major',
pitches=frozenset({0, 4, 7}), bass=0, inversion=0,
)
def _make_rn(self):
return RomanNumeral(
degree=1, quality='major', inversion=0,
local_key_tonic=0, local_key_mode='major',
)
def test_onset_delegates_to_chord(self):
from src.core.data_structures import HarmonicEvent
chord = self._make_chord(onset=8)
he = HarmonicEvent(chord=chord, roman_numeral=self._make_rn())
assert he.onset == Fraction(8)
def test_duration_delegates_to_chord(self):
from src.core.data_structures import HarmonicEvent
chord = self._make_chord(dur=3)
he = HarmonicEvent(chord=chord, roman_numeral=self._make_rn())
assert he.duration == Fraction(3)
# ===========================================================================
# KeyEstimate
# ===========================================================================
class TestKeyEstimate:
def test_c_major(self):
ke = KeyEstimate(tonic=0, mode='major', confidence=0.9, onset=Fraction(0))
assert ke.label == 'C major'
def test_g_major(self):
ke = KeyEstimate(tonic=7, mode='major', confidence=0.95, onset=Fraction(0))
assert ke.label == 'G major'
def test_d_minor(self):
ke = KeyEstimate(tonic=2, mode='minor', confidence=0.8, onset=Fraction(4))
assert ke.label == 'D minor'
def test_eb_major(self):
ke = KeyEstimate(tonic=3, mode='major', confidence=0.7, onset=Fraction(0))
assert ke.label == 'Eb major'
def test_b_minor(self):
ke = KeyEstimate(tonic=11, mode='minor', confidence=0.85, onset=Fraction(0))
assert ke.label == 'B minor'
def test_invalid_tonic_12(self):
with pytest.raises(ValueError):
KeyEstimate(tonic=12, mode='major', confidence=0.9, onset=Fraction(0))
def test_invalid_tonic_negative(self):
with pytest.raises(ValueError):
KeyEstimate(tonic=-1, mode='major', confidence=0.9, onset=Fraction(0))
def test_invalid_confidence_high(self):
with pytest.raises(ValueError):
KeyEstimate(tonic=0, mode='major', confidence=1.5, onset=Fraction(0))
def test_invalid_confidence_negative(self):
with pytest.raises(ValueError):
KeyEstimate(tonic=0, mode='major', confidence=-0.1, onset=Fraction(0))
def test_invalid_mode(self):
with pytest.raises(ValueError):
KeyEstimate(tonic=0, mode='lydian', confidence=0.9, onset=Fraction(0))
def test_is_frozen(self):
ke = KeyEstimate(tonic=0, mode='major', confidence=0.9, onset=Fraction(0))
with pytest.raises(Exception):
ke.tonic = 5 # type: ignore[misc]
# ===========================================================================
# Score
# ===========================================================================
def _ev(pitch, onset, duration, voice=0):
return MusicalEvent(
pitch=pitch, onset=Fraction(onset), duration=Fraction(duration),
velocity=64, measure=1, beat=Fraction(0), beat_strength=1.0,
voice=voice, is_rest=False,
)
class TestScore:
def test_events_sorted_by_onset(self):
events = [_ev(64, 2, 1), _ev(60, 0, 1), _ev(62, 1, 1)]
score = Score(events=events)
onsets = [e.onset for e in score.events]
assert onsets == sorted(onsets)
def test_default_time_signature_added(self):
score = Score(events=[_ev(60, 0, 1)])
assert len(score.time_signatures) == 1
assert score.time_signatures[0][1] == TimeSignature(4, 4)
def test_custom_time_signature_preserved(self):
ts = TimeSignature(3, 4)
score = Score(events=[_ev(60, 0, 1)],
time_signatures=[(Fraction(0), ts)])
assert score.get_time_signature_at(Fraction(0)) == ts
def test_get_time_signature_at_changes(self):
ts1, ts2 = TimeSignature(4, 4), TimeSignature(3, 4)
score = Score(
events=[_ev(60, 0, 1)],
time_signatures=[(Fraction(0), ts1), (Fraction(8), ts2)],
)
assert score.get_time_signature_at(Fraction(0)) == ts1
assert score.get_time_signature_at(Fraction(4)) == ts1
assert score.get_time_signature_at(Fraction(8)) == ts2
assert score.get_time_signature_at(Fraction(16)) == ts2
def test_duration(self):
# two events: onset=0 dur=1 (offset=1), onset=1 dur=2 (offset=3)
score = Score(events=[_ev(60, 0, 1), _ev(62, 1, 2)])
assert score.duration == Fraction(3)
def test_duration_empty(self):
assert Score(events=[]).duration == Fraction(0)
def test_num_voices(self):
events = [_ev(60, 0, 1, voice=0), _ev(64, 0, 1, voice=1), _ev(67, 0, 1, voice=2)]
score = Score(events=events)
assert score.num_voices == 3
def test_num_voices_empty(self):
assert Score(events=[]).num_voices == 0
def test_pitch_range(self):
rest = MusicalEvent(pitch=None, onset=Fraction(2), duration=Fraction(1),
velocity=0, is_rest=True)
score = Score(events=[_ev(60, 0, 1), _ev(72, 1, 1), rest])
assert score.pitch_range == (60, 72)
def test_pitch_range_all_rests(self):
rest = MusicalEvent(pitch=None, onset=Fraction(0), duration=Fraction(1),
velocity=0, is_rest=True)
assert Score(events=[rest]).pitch_range == (None, None)
def test_get_events_in_range_exact_boundaries(self):
# event [0, 1) should NOT appear in window [1, 2)
events = [_ev(60, 0, 1), _ev(62, 1, 1), _ev(64, 2, 1)]
score = Score(events=events)
result = score.get_events_in_range(Fraction(1), Fraction(2))
assert len(result) == 1
assert result[0].pitch == 62
def test_get_events_in_range_overlap(self):
# event spanning [0, 3) should appear in window [2, 4)
events = [_ev(60, 0, 3)]
score = Score(events=events)
result = score.get_events_in_range(Fraction(2), Fraction(4))
assert len(result) == 1
def test_get_events_in_range_empty_window(self):
score = Score(events=[_ev(60, 0, 1)])
assert score.get_events_in_range(Fraction(5), Fraction(10)) == []
def test_get_events_by_voice(self):
events = [_ev(60, 0, 1, voice=0), _ev(64, 0, 1, voice=1), _ev(67, 1, 1, voice=0)]
score = Score(events=events)
v0 = score.get_events_by_voice(0)
v1 = score.get_events_by_voice(1)
assert all(e.voice == 0 for e in v0)
assert all(e.voice == 1 for e in v1)
assert len(v0) == 2
assert len(v1) == 1
|