diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..2d1dc61 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,25 @@ +"""Unit tests for songsplit CLI.""" + +from typer.testing import CliRunner + +from songsplit.cli import app + +runner = CliRunner() + + +def test_cli_help(): + result = runner.invoke(app, ["--help"]) + assert result.exit_code == 0 + assert "Audio analysis pipeline decomposing songs into song packages" in result.stdout + assert "doctor" in result.stdout + assert "analyze" in result.stdout + + +def test_cli_doctor(): + result = runner.invoke(app, ["doctor"]) + assert result.exit_code == 0 + # Rich table output is printed to stderr as configured in cli.py + output = result.stdout + result.stderr + assert "Python" in output + assert "ffmpeg" in output + assert "Model Cache" in output diff --git a/tests/test_runner.py b/tests/test_runner.py new file mode 100644 index 0000000..4b88b9c --- /dev/null +++ b/tests/test_runner.py @@ -0,0 +1,144 @@ +"""Unit tests for PipelineRunner, caching, and hash invalidation.""" + +from pathlib import Path + +import pytest + +from songsplit.pipeline.runner import PipelineContext, PipelineRunner, Stage + + +class MockStageA(Stage): + name = "stage_a" + version = "1.0.0" + model_name = "mock_model_a" + model_version = "1.0.0" + dependencies: list[str] = [] + + def get_inputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.source_file] + + def get_outputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_a.txt"] + + def run(self, ctx: PipelineContext) -> None: + (ctx.output_dir / "out_a.txt").write_text("output A") + + +class MockStageB(Stage): + name = "stage_b" + version = "1.0.0" + model_name = "mock_model_b" + model_version = "1.0.0" + dependencies = ["stage_a"] + + def get_inputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_a.txt"] + + def get_outputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_b.txt"] + + def run(self, ctx: PipelineContext) -> None: + in_text = (ctx.output_dir / "out_a.txt").read_text() + (ctx.output_dir / "out_b.txt").write_text(f"{in_text} -> B") + + +class MockStageFailing(Stage): + name = "stage_fail" + version = "1.0.0" + model_name = "mock_fail" + model_version = "1.0.0" + dependencies = ["stage_a"] + + def get_inputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_a.txt"] + + def get_outputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_fail.txt"] + + def run(self, ctx: PipelineContext) -> None: + raise RuntimeError("Stage failed intentionally") + + +class MockStageDepOnFail(Stage): + name = "stage_dep_on_fail" + version = "1.0.0" + model_name = "mock_dep" + model_version = "1.0.0" + dependencies = ["stage_fail"] + + def get_inputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_fail.txt"] + + def get_outputs(self, ctx: PipelineContext) -> list[Path]: + return [ctx.output_dir / "out_dep.txt"] + + def run(self, ctx: PipelineContext) -> None: + (ctx.output_dir / "out_dep.txt").write_text("should not run") + + +@pytest.fixture +def run_env(tmp_path: Path): + source = tmp_path / "song.mp3" + source.write_text("fake audio bytes") + out_dir = tmp_path / "song_pkg" + return source, out_dir + + +def test_runner_execution_and_caching(run_env): + source, out_dir = run_env + ctx = PipelineContext(source_file=source, output_dir=out_dir) + runner = PipelineRunner([MockStageA(), MockStageB()]) + + # First run: should execute both stages + meta = runner.run(ctx) + assert "stage_a" in meta.stages_done + assert "stage_b" in meta.stages_done + assert (out_dir / "out_a.txt").exists() + assert (out_dir / "out_b.txt").read_text() == "output A -> B" + assert (out_dir / ".cache" / "stage_a.json").exists() + assert (out_dir / ".cache" / "stage_b.json").exists() + + # Second run without changes: both should be skipped from cache + # Modify output file content to verify it is NOT overwritten + (out_dir / "out_b.txt").write_text("modified manually") + runner.run(ctx) + assert (out_dir / "out_b.txt").read_text() == "modified manually" + + # Run with force=True: should recalculate + ctx_force = PipelineContext(source_file=source, output_dir=out_dir, force=True) + runner.run(ctx_force) + assert (out_dir / "out_b.txt").read_text() == "output A -> B" + + +def test_target_stage_only_runs_prerequisites(run_env): + source, out_dir = run_env + ctx = PipelineContext(source_file=source, output_dir=out_dir, target_stage="stage_b") + runner = PipelineRunner([MockStageA(), MockStageB()]) + + stages = runner.get_stages_to_run(ctx) + stage_names = [s.name for s in stages] + assert stage_names == ["stage_a", "stage_b"] + + +def test_stage_failure_does_not_abort_independent_stages(run_env): + source, out_dir = run_env + ctx = PipelineContext(source_file=source, output_dir=out_dir) + # stage_b depends on stage_a (independent of stage_fail) + # stage_dep_on_fail depends on stage_fail + runner = PipelineRunner([MockStageA(), MockStageFailing(), MockStageDepOnFail(), MockStageB()]) + + meta = runner.run(ctx) + + # stage_a and stage_b succeeded + assert "stage_a" in meta.stages_done + assert "stage_b" in meta.stages_done + assert (out_dir / "out_b.txt").exists() + + # stage_fail recorded error + assert "stage_fail" in meta.stages_failed + assert "RuntimeError" in meta.stages_failed["stage_fail"] + + # stage_dep_on_fail was skipped due to failed dependency + assert "stage_dep_on_fail" in meta.stages_failed + assert "dependencies failed" in meta.stages_failed["stage_dep_on_fail"] + assert not (out_dir / "out_dep.txt").exists() diff --git a/tests/test_schema.py b/tests/test_schema.py new file mode 100644 index 0000000..aa7bd20 --- /dev/null +++ b/tests/test_schema.py @@ -0,0 +1,151 @@ +"""Unit tests for Song-Paket Pydantic schemas (Round-trip & validation).""" + +import json + +import pytest +from pydantic import ValidationError + +from songsplit.schema import ( + ChordsDocument, + MetaDocument, + ModelInfo, + SourceFileInfo, + StrummingDocument, + TempoAnchor, + TempoDocument, + VocalsDocument, + VocalSyllable, +) + + +def test_meta_document_roundtrip(): + doc = MetaDocument( + title="Test Song", + artist="Test Artist", + language="de", + duration_sec=180.5, + source_file=SourceFileInfo(path="/tmp/test.wav", sha256="abc123hash", size_bytes=1048576), + key="Am", + capo=2, + models_used=[ModelInfo(stage="s2_stems", name="htdemucs_ft", version="1.0.0")], + created_at="2026-11-02T10:00:00Z", + stages_done=["s1_extract", "s2_stems"], + stages_failed={"s3_lyrics": "Sample error"}, + ) + json_str = doc.model_dump_json() + loaded = MetaDocument.model_validate_json(json_str) + assert loaded == doc + assert loaded.schema_version == "1.0" + assert loaded.title == "Test Song" + assert loaded.stages_done == ["s1_extract", "s2_stems"] + + +def test_vocals_document_roundtrip_and_spec_example(): + spec_example = { + "schema_version": "1.0", + "generated_by": { + "stage": "s4_pitch", + "model": "torchcrepe-full", + "model_version": "1.0", + "params": {"hop": 10}, + }, + "lines": [ + { + "start": 12.34, + "end": 15.80, + "syllables": [ + { + "text": "Hel", + "start": 12.34, + "end": 12.61, + "midi": 64.0, + "golden": False, + "confidence": 0.88, + "source": "auto", + } + ], + } + ], + } + doc = VocalsDocument.model_validate(spec_example) + assert len(doc.lines) == 1 + syl = doc.lines[0].syllables[0] + assert syl.text == "Hel" + assert syl.midi == 64.0 + assert syl.confidence == 0.88 + assert syl.source == "auto" + + dumped = json.loads(doc.model_dump_json()) + assert dumped["lines"][0]["syllables"][0]["text"] == "Hel" + + +def test_vocals_validation_error(): + with pytest.raises(ValidationError): + # confidence > 1.0 is invalid + VocalSyllable(text="test", start=1.0, end=2.0, midi=60.0, confidence=1.5) + + +def test_tempo_document_roundtrip_and_spec_example(): + spec_example = { + "schema_version": "1.0", + "anchors": [{"sec": 0.52, "beat": 0.0, "bpm": 120.0}], + "time_signature": {"numerator": 4, "denominator": 4}, + "downbeat_offset": 0, + } + doc = TempoDocument.model_validate(spec_example) + assert len(doc.anchors) == 1 + assert doc.anchors[0].bpm == 120.0 + assert doc.time_signature.numerator == 4 + + dumped = json.loads(doc.model_dump_json()) + assert dumped["anchors"][0]["bpm"] == 120.0 + + +def test_tempo_invalid_bpm(): + with pytest.raises(ValidationError): + TempoAnchor(sec=0.0, beat=0.0, bpm=0.0) + + +def test_chords_document_roundtrip_and_spec_example(): + spec_example = { + "schema_version": "1.0", + "chords": [ + { + "start_beat": 0.0, + "end_beat": 4.0, + "label": "Am", + "root": "A", + "quality": "min", + "bass": None, + "confidence": 0.74, + "source": "auto", + } + ], + } + doc = ChordsDocument.model_validate(spec_example) + assert len(doc.chords) == 1 + chord = doc.chords[0] + assert chord.label == "Am" + assert chord.root == "A" + assert chord.quality == "min" + assert chord.confidence == 0.74 + + dumped = json.loads(doc.model_dump_json()) + assert dumped["chords"][0]["label"] == "Am" + + +def test_strumming_document_roundtrip_and_spec_example(): + spec_example = { + "schema_version": "1.0", + "events": [{"beat": 0.0, "direction": "down", "strength": 0.9, "confidence": 0.5, "source": "auto"}], + "patterns": [{"start_beat": 0.0, "end_beat": 16.0, "pattern": "D . D U . U D U", "grid": "8th"}], + } + doc = StrummingDocument.model_validate(spec_example) + assert len(doc.events) == 1 + assert doc.events[0].direction == "down" + assert doc.events[0].strength == 0.9 + assert len(doc.patterns) == 1 + assert doc.patterns[0].pattern == "D . D U . U D U" + + dumped = json.loads(doc.model_dump_json()) + assert dumped["events"][0]["direction"] == "down" diff --git a/tests/test_tempo.py b/tests/test_tempo.py new file mode 100644 index 0000000..cb82e8b --- /dev/null +++ b/tests/test_tempo.py @@ -0,0 +1,104 @@ +"""Unit tests for Tempo-Map conversion (sec_to_beat and beat_to_sec).""" + +import pytest + +from songsplit.schema.tempo import TempoAnchor, TempoDocument +from songsplit.tempo import beat_to_sec, sec_to_beat + + +def test_empty_tempo_map_raises_error(): + empty_doc = TempoDocument(anchors=[]) + with pytest.raises(ValueError, match="no anchors"): + sec_to_beat(1.0, empty_doc) + with pytest.raises(ValueError, match="no anchors"): + beat_to_sec(1.0, empty_doc) + + +def test_constant_tempo_single_anchor(): + # 120 bpm = 2 beats per second = 0.5s per beat + doc = TempoDocument(anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)]) + + # At anchor + assert sec_to_beat(0.5, doc) == pytest.approx(0.0) + assert beat_to_sec(0.0, doc) == pytest.approx(0.5) + + # 1 second later = 2 beats + assert sec_to_beat(1.5, doc) == pytest.approx(2.0) + assert beat_to_sec(2.0, doc) == pytest.approx(1.5) + + # 4 beats later = 2.0s duration -> 2.5s absolute + assert beat_to_sec(4.0, doc) == pytest.approx(2.5) + assert sec_to_beat(2.5, doc) == pytest.approx(4.0) + + # Before anchor (extrapolation) + # sec = 0.0 -> -0.5s -> -1.0 beat + assert sec_to_beat(0.0, doc) == pytest.approx(-1.0) + assert beat_to_sec(-1.0, doc) == pytest.approx(0.0) + + +def test_tempo_change_multiple_anchors(): + # Anchor 0: sec=1.0, beat=0.0, bpm=120 (0.5 sec/beat) + # -> 4 beats take 2.0s -> reaches sec=3.0 at beat=4.0 + # Anchor 1: sec=3.0, beat=4.0, bpm=60 (1.0 sec/beat) + # -> 4 beats take 4.0s -> reaches sec=7.0 at beat=8.0 + # Anchor 2: sec=7.0, beat=8.0, bpm=240 (0.25 sec/beat) + doc = TempoDocument( + anchors=[ + TempoAnchor(sec=1.0, beat=0.0, bpm=120.0), + TempoAnchor(sec=3.0, beat=4.0, bpm=60.0), + TempoAnchor(sec=7.0, beat=8.0, bpm=240.0), + ] + ) + + # Exact anchor points + assert sec_to_beat(1.0, doc) == pytest.approx(0.0) + assert sec_to_beat(3.0, doc) == pytest.approx(4.0) + assert sec_to_beat(7.0, doc) == pytest.approx(8.0) + + assert beat_to_sec(0.0, doc) == pytest.approx(1.0) + assert beat_to_sec(4.0, doc) == pytest.approx(3.0) + assert beat_to_sec(8.0, doc) == pytest.approx(7.0) + + # Inside section 1 (120 bpm) + # sec=2.0 -> beat=2.0 + assert sec_to_beat(2.0, doc) == pytest.approx(2.0) + assert beat_to_sec(2.0, doc) == pytest.approx(2.0) + + # Inside section 2 (60 bpm) + # sec=5.0 -> 2 seconds after sec=3.0 -> 2 beats -> beat=6.0 + assert sec_to_beat(5.0, doc) == pytest.approx(6.0) + assert beat_to_sec(6.0, doc) == pytest.approx(5.0) + + # Beyond last anchor (240 bpm) + # sec=8.0 -> 1 second after sec=7.0 -> 4 beats -> beat=12.0 + assert sec_to_beat(8.0, doc) == pytest.approx(12.0) + assert beat_to_sec(12.0, doc) == pytest.approx(8.0) + + +def test_roundtrip_identity_across_ranges(): + # Anchor 0: sec=0.2, beat=0.0, bpm=120.0 + # 18 beats at 120 bpm = 9.0s -> sec = 9.2, beat = 18.0 + # Anchor 1: sec=9.2, beat=18.0, bpm=150.0 + # 42 beats at 150 bpm = 16.8s -> sec = 26.0, beat = 60.0 + # Anchor 2: sec=26.0, beat=60.0, bpm=95.0 + doc = TempoDocument( + anchors=[ + TempoAnchor(sec=0.2, beat=0.0, bpm=120.0), + TempoAnchor(sec=9.2, beat=18.0, bpm=150.0), + TempoAnchor(sec=26.0, beat=60.0, bpm=95.0), + ] + ) + + # Test roundtrip for a wide range of seconds + test_seconds = [-5.0, 0.0, 0.2, 5.0, 9.199, 9.2, 15.0, 25.999, 26.0, 100.0, 300.0] + for s in test_seconds: + b = sec_to_beat(s, doc) + s_back = beat_to_sec(b, doc) + assert s_back == pytest.approx(s, rel=1e-7, abs=1e-7) + + # Test roundtrip for a wide range of beats + test_beats = [-10.0, 0.0, 5.0, 18.0, 35.0, 60.0, 150.0] + for b in test_beats: + s = beat_to_sec(b, doc) + b_back = sec_to_beat(s, doc) + assert b_back == pytest.approx(b, rel=1e-7, abs=1e-7)