diff --git a/ffmpeg_handling/src/ffmpeg_handling/run_test.py b/ffmpeg_handling/src/ffmpeg_handling/run_test.py new file mode 100755 index 0000000..d856b8f --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/run_test.py @@ -0,0 +1,22 @@ +#!/home/lucas/scripts/ffmpeg_handling/.venv/bin/python +# """Discover and run the ffmpeg_handling unittest suite.""" + +import sys +import unittest +from pathlib import Path + +PROJECT_DIR = Path(__file__).resolve().parents[2] +TEST_DIR = PROJECT_DIR / "tests" +sys.path.insert(0, str(PROJECT_DIR)) + + +def run_tests(verbosity: int = 2) -> bool: + suite = unittest.defaultTestLoader.discover( + str(TEST_DIR), pattern="test_*.py", top_level_dir=str(PROJECT_DIR) + ) + result = unittest.TextTestRunner(verbosity=verbosity).run(suite) + return result.wasSuccessful() + + +if __name__ == "__main__": + sys.exit(0 if run_tests() else 1) diff --git a/ffmpeg_handling/tests/__init__.py b/ffmpeg_handling/tests/__init__.py new file mode 100644 index 0000000..e386396 --- /dev/null +++ b/ffmpeg_handling/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the ffmpeg_handling command-line tool.""" diff --git a/ffmpeg_handling/tests/test_cli.py b/ffmpeg_handling/tests/test_cli.py new file mode 100644 index 0000000..8ddffa7 --- /dev/null +++ b/ffmpeg_handling/tests/test_cli.py @@ -0,0 +1,60 @@ +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from ffmpeg_handling import build_parser, main + +ASSET_DIR = Path(__file__).resolve().parents[1] / "testfiles" + + +class CliTests(unittest.TestCase): + def test_test_command_is_not_registered(self): + with self.assertRaises(SystemExit) as error: + build_parser().parse_args(["test"]) + self.assertEqual(error.exception.code, 2) + + def test_short_command_alias_resolves_to_canonical_name(self): + args = build_parser().parse_args(["i", str(ASSET_DIR / "test_auto.mp4")]) + self.assertEqual(args.command, "info") + + def test_missing_ffmpeg_logs_error_and_returns_failure(self): + with patch("ffmpeg_handling.cli.shutil.which", return_value=None), \ + patch("ffmpeg_handling.cli.setup_logging"), \ + self.assertLogs("ffmpeg_handling", level="ERROR") as captured: + result = main(["info", str(ASSET_DIR / "test_auto_no_subs.mkv")]) + + self.assertEqual(result, 1) + self.assertIn("FFmpeg is not installed", captured.output[0]) + + def test_non_output_command_returns_success(self): + with patch("ffmpeg_handling.cli.setup_logging"), \ + self.assertLogs("ffmpeg_handling", level="INFO"): + self.assertEqual( + main(["info", str(ASSET_DIR / "test_auto_no_subs.mkv")]), 0 + ) + + def test_cli_dry_run_uses_requested_output_and_creates_nothing(self): + with tempfile.TemporaryDirectory() as temp_dir: + output = Path(temp_dir) / "dry_run.mkv" + with patch("ffmpeg_handling.cli.setup_logging"), \ + self.assertLogs("ffmpeg_handling", level="INFO"): + result = main([ + "downsize", + str(ASSET_DIR / "test_auto_no_subs.mkv"), + "-o", + str(output), + "--dry-run", + "-w", + "320", + "-he", + "180", + "-c", + "30", + ]) + self.assertEqual(result, 0) + self.assertFalse(output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/ffmpeg_handling/tests/test_helpers.py b/ffmpeg_handling/tests/test_helpers.py new file mode 100644 index 0000000..c47d794 --- /dev/null +++ b/ffmpeg_handling/tests/test_helpers.py @@ -0,0 +1,122 @@ +import argparse +import subprocess +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +from ffmpeg_handling.helpers import ( + get_scodec, + get_vcodec, + is_russian_track, + move_overwrite_file, + natural_sort_key, + parse_time_to_seconds, + run_ffmpeg, + translate_audio_tracks, + video_files, +) + + +class TimeParsingTests(unittest.TestCase): + def test_seconds_and_compact_time_formats(self): + cases = { + "100s": 100, + "1m20s": 80, + "2h10m5s": 7805, + "0:1:5": 65, + "01:20": 80, + "12.5": 12.5, + } + for value, expected in cases.items(): + with self.subTest(value=value): + self.assertEqual(parse_time_to_seconds(value), expected) + + def test_invalid_time_is_rejected(self): + for value in ("", "abc", "1x", "1:2:3:4"): + with self.subTest(value=value), self.assertRaises( + argparse.ArgumentTypeError + ): + parse_time_to_seconds(value) + + def test_none_is_preserved(self): + self.assertIsNone(parse_time_to_seconds(None)) + + +class MediaHelperTests(unittest.TestCase): + def test_codec_selection_is_case_insensitive(self): + self.assertEqual(get_scodec(Path("movie.MP4")), "mov_text") + self.assertEqual(get_scodec(Path("movie.mkv")), "copy") + self.assertEqual(get_vcodec(Path("movie.MP4")), "libx264") + self.assertEqual(get_vcodec(Path("movie.mkv")), "copy") + + def test_natural_sort_orders_numeric_segments(self): + files = [Path("part10.mkv"), Path("part2.mkv"), Path("part1.mkv")] + self.assertEqual( + sorted(files, key=natural_sort_key), + [Path("part1.mkv"), Path("part2.mkv"), Path("part10.mkv")], + ) + + def test_russian_detection_and_translation(self): + self.assertTrue(is_russian_track({"language": "rus"})) + self.assertFalse(is_russian_track({"language": "eng"})) + translated = translate_audio_tracks( + [{"description": "Дубляж (AlexFilm)", "number": 1}] + ) + self.assertEqual(translated[0]["description"], "Dubbed (AlexFilm)") + + def test_unknown_cyrillic_translation_is_reported(self): + with self.assertRaisesRegex(ValueError, "unidentified Cyrillic"): + translate_audio_tracks([{"description": "Неизвестный перевод"}]) + + def test_video_files_filters_supported_extensions_and_recurses_on_request(self): + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + nested = root / "nested" + nested.mkdir() + (root / "video.mkv").touch() + (root / "audio.mp3").touch() + (root / "readme.txt").touch() + (nested / "nested.mp4").touch() + self.assertEqual( + {path.name for path in video_files(root, recursive=False)}, + {"video.mkv", "audio.mp3"}, + ) + self.assertEqual( + {path.name for path in video_files(root, recursive=True)}, + {"video.mkv", "audio.mp3", "nested.mp4"}, + ) + + def test_overwrite_moves_old_content_to_backup(self): + with tempfile.TemporaryDirectory() as temp_dir: + target = Path(temp_dir) / "media.mkv" + output = Path(temp_dir) / "media_overwrite.mkv" + target.write_text("original", encoding="utf-8") + output.write_text("converted", encoding="utf-8") + args = SimpleNamespace(backup=True, loud=False) + self.assertTrue(move_overwrite_file([output], [target], args)) + self.assertEqual(target.read_text(encoding="utf-8"), "converted") + backup = Path(temp_dir) / "media_backup.mkv" + self.assertEqual(backup.read_text(encoding="utf-8"), "original") + + +class FfmpegRunnerTests(unittest.TestCase): + @patch("ffmpeg_handling.helpers.subprocess.run") + def test_dry_run_does_not_start_a_process(self, run): + self.assertTrue(run_ffmpeg(["ffmpeg", "-version"], dry_run=True)) + run.assert_not_called() + + @patch("ffmpeg_handling.helpers.subprocess.run") + def test_process_failure_keeps_stderr_and_exit_code(self, run): + run.return_value.returncode = 2 + run.return_value.stdout = "" + run.return_value.stderr = "encoder failed" + with self.assertRaises(subprocess.CalledProcessError) as error: + run_ffmpeg(["ffmpeg", "-i", "bad.mkv"]) + self.assertEqual(error.exception.returncode, 2) + self.assertIn("encoder failed", error.exception.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/ffmpeg_handling/tests/test_media_commands.py b/ffmpeg_handling/tests/test_media_commands.py new file mode 100644 index 0000000..4fb3fef --- /dev/null +++ b/ffmpeg_handling/tests/test_media_commands.py @@ -0,0 +1,315 @@ +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +from ffmpeg_handling.audio_commands import ( + cmd_extract_audio_track, + cmd_filter_audio, + cmd_remove_audio_track, + cmd_remove_russian_from_db, + cmd_set_primary_audio, +) +from ffmpeg_handling.helpers import probe_media +from ffmpeg_handling.metadata_commands import cmd_apply_chapters, cmd_set_metadata +from ffmpeg_handling.video_commands import ( + cmd_convert_audio, + cmd_convert_av, + cmd_convert_av_all_suffix, + cmd_convert_video, + cmd_cut_segment, + cmd_downsize, + cmd_info, + cmd_remove_subs, +) + +ASSET_DIR = Path(__file__).resolve().parents[1] / "testfiles" + + +def command_args(input_path: Path, output_path: Path, **values): + defaults = { + "input": input_path, + "output": output_path, + "dry_run": False, + "loud": False, + "audio_index": [], + "kidflag": False, + "backup": False, + } + defaults.update(values) + return SimpleNamespace(**defaults) + + +class MediaCommandIntegrationTests(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory(prefix="ffmpeg_handling_test_") + self.output_dir = Path(self.temp_dir.name) + + def tearDown(self): + self.temp_dir.cleanup() + + def output(self, name): + return self.output_dir / name + + def assert_stream_counts(self, path, *, audio=None, subtitles=None, video=None): + streams = probe_media(path).get("streams", []) + counts = { + kind: sum(stream.get("codec_type") == kind for stream in streams) + for kind in ("video", "audio", "subtitle") + } + if audio is not None: + self.assertEqual(counts["audio"], audio) + if subtitles is not None: + self.assertEqual(counts["subtitle"], subtitles) + if video is not None: + self.assertEqual(counts["video"], video) + + def test_info_and_all_supported_fixture_assets_probe(self): + fixtures = sorted( + path for path in ASSET_DIR.glob("test_auto*") + if path.suffix.lower() in {".avi", ".m4b", ".mkv", ".mp4"} + ) + self.assertGreaterEqual(len(fixtures), 7) + for fixture in fixtures: + with self.subTest(fixture=fixture.name): + self.assertTrue(probe_media(fixture).get("streams")) + self.assertEqual( + cmd_info(command_args(ASSET_DIR / "test_auto.mp4", self.output("unused"))), + (False, "nooutputneeded"), + ) + + def test_remove_subtitles_and_audio_preserves_other_streams(self): + source = ASSET_DIR / "test_auto.mkv" + no_subtitles = self.output("no_subtitles.mkv") + self.assertTrue(cmd_remove_subs(command_args(source, no_subtitles))[0]) + self.assert_stream_counts(no_subtitles, audio=2, subtitles=0) + + source_without_subtitles = ASSET_DIR / "test_auto_no_subs.mkv" + copied_without_subtitles = self.output("still_no_subtitles.mkv") + self.assertTrue( + cmd_remove_subs( + command_args(source_without_subtitles, copied_without_subtitles) + )[0] + ) + self.assert_stream_counts(copied_without_subtitles, audio=2, subtitles=0) + + one_subtitle_removed = self.output("one_subtitle_removed.mkv") + args = command_args(source, one_subtitle_removed, num=[3]) + self.assertTrue(cmd_remove_subs(args)[0]) + self.assert_stream_counts(one_subtitle_removed, subtitles=2) + + one_audio = self.output("one_audio.mkv") + args = command_args(source, one_audio, audio_index=[1]) + self.assertTrue(cmd_remove_audio_track(args)[0]) + self.assert_stream_counts(one_audio, audio=1, subtitles=3) + + def test_refusing_to_remove_the_last_audio_and_invalid_index(self): + source = ASSET_DIR / "test_auto_only_russian.mkv" + args = command_args(source, self.output("empty_audio.mkv"), audio_index=[1]) + self.assertFalse(cmd_remove_audio_track(args)[0]) + + args.audio_index = [99] + with self.assertRaisesRegex(ValueError, "not present"): + cmd_remove_audio_track(args) + + def test_audio_extraction_and_segment_cut(self): + source = ASSET_DIR / "test_auto.mkv" + extracted = self.output("extracted.mp3") + self.assertTrue( + cmd_extract_audio_track( + command_args(source, extracted, audio_index=[1]) + )[0] + ) + self.assertEqual(probe_media(extracted)["streams"][0]["codec_type"], "audio") + chapter_titles = self.output("audio_chapters.txt") + chapter_titles.write_text("Extracted track\n", encoding="utf-8") + chapter_args = command_args( + extracted, + self.output("renamed.mp3"), + chapter_file=chapter_titles, + file_counter=0, + ) + self.assertTrue(cmd_apply_chapters(chapter_args)[0]) + tagged_audio = self.output("001 - Extracted track.mp3") + self.assertEqual( + probe_media(tagged_audio)["format"]["tags"]["title"], "Extracted track" + ) + multiple_args = command_args( + source, self.output("multiple.mp3"), audio_index=[1, 2] + ) + self.assertTrue(cmd_extract_audio_track(multiple_args)[0]) + for index in (1, 2): + output = self.output(f"multiple_stream_{index}.mp3") + self.assertTrue(output.is_file()) + self.assertEqual( + probe_media(output)["streams"][0]["codec_type"], "audio" + ) + + cut = self.output("cut.mkv") + args = command_args(source, cut, start="1s", duration="3s") + self.assertTrue(cmd_cut_segment(args)[0]) + self.assertLess(float(probe_media(cut)["format"]["duration"]), 8) + self.assertGreater(float(probe_media(cut)["format"]["duration"]), 2) + + def test_audio_video_transcodes_and_downsize(self): + source = ASSET_DIR / "test_auto.mkv" + audio = self.output("audio_aac.mkv") + self.assertTrue( + cmd_convert_audio( + command_args(source, audio, audio_codec="aac") + )[0] + ) + self.assertTrue( + all( + stream["codec_name"] == "aac" + for stream in probe_media(audio)["streams"] + if stream.get("codec_type") == "audio" + ) + ) + + video = self.output("video_h264.mkv") + self.assertTrue( + cmd_convert_video( + command_args(source, video, video_codec="libx264") + )[0] + ) + self.assert_stream_counts(video, audio=2, subtitles=3) + self.assertTrue( + all( + stream["codec_name"] == "h264" + for stream in probe_media(video)["streams"] + if stream.get("codec_type") == "video" + ) + ) + + smaller = self.output("smaller.mkv") + args = command_args(source, smaller, width=320, height=180, crf=32) + self.assertTrue(cmd_downsize(args)[0]) + first_video = next( + stream for stream in probe_media(smaller)["streams"] + if stream.get("codec_type") == "video" + ) + self.assertEqual((first_video["width"], first_video["height"]), (320, 180)) + + def test_full_reencode_and_suffix_filter(self): + source = ASSET_DIR / "test_auto.mkv" + output = self.output("full.mp4") + args = command_args( + source, output, video_codec="libx264", audio_codec="aac", + preset="ultrafast", quality=30, new_suffix=None, + ) + self.assertTrue(cmd_convert_av(args)[0]) + converted_streams = probe_media(output)["streams"] + self.assertTrue(converted_streams) + self.assertTrue( + all( + stream["codec_name"] == "h264" + for stream in converted_streams + if stream.get("codec_type") == "video" + ) + ) + self.assertTrue( + all( + stream["codec_name"] == "aac" + for stream in converted_streams + if stream.get("codec_type") == "audio" + ) + ) + + args.suffix = ".mp4" + self.assertFalse(cmd_convert_av_all_suffix(args)[0]) + args.suffix = ".mkv" + args.new_suffix = ".mp4" + args.output = self.output("filtered.mkv") + self.assertTrue(cmd_convert_av_all_suffix(args)[0]) + self.assertTrue(self.output("filtered.mp4").is_file()) + + def test_audio_filter_and_primary_stream_order(self): + source = ASSET_DIR / "test_auto.mkv" + filtered = self.output("filtered_audio.mkv") + args = command_args(source, filtered, audio_index=[2]) + self.assertTrue(cmd_filter_audio(args)[0]) + self.assert_stream_counts(filtered, audio=3) + self.assertTrue( + all( + stream["codec_name"] == "vorbis" + for stream in probe_media(filtered)["streams"] + if stream.get("codec_type") == "audio" + ) + ) + + primary = self.output("primary.mkv") + args.output = primary + self.assertTrue(cmd_set_primary_audio(args)[0]) + audio_streams = [ + stream for stream in probe_media(primary)["streams"] + if stream.get("codec_type") == "audio" + ] + self.assertEqual(audio_streams[0].get("tags", {}).get("language"), "ger") + self.assertEqual(audio_streams[0].get("disposition", {}).get("default"), 1) + + def test_metadata_and_chapter_operations(self): + source = ASSET_DIR / "test_auto.m4b" + metadata = self.output("metadata.m4b") + args = command_args( + source, metadata, key="artist", value="Unit Test", chapter_file=None + ) + self.assertTrue(cmd_set_metadata(args)[0]) + self.assertEqual( + probe_media(metadata)["format"]["tags"]["artist"], "Unit Test" + ) + + chapter_output = self.output("chapters.m4b") + args.output = chapter_output + args.chapter_file = ASSET_DIR / "test_auto_chapters.txt" + self.assertTrue(cmd_apply_chapters(args)[0]) + chapter_info = probe_media(chapter_output) + expected_titles = [ + line for line in args.chapter_file.read_text(encoding="utf-8").splitlines() + if line + ] + self.assertEqual( + [chapter["tags"]["title"] for chapter in chapter_info["chapters"]], + expected_titles, + ) + + def test_chapter_count_mismatch_fails_clearly(self): + source = ASSET_DIR / "test_auto.m4b" + titles = self.output("too_many_chapters.txt") + titles.write_text("Only one title\n", encoding="utf-8") + args = command_args( + source, self.output("bad_chapters.m4b"), chapter_file=titles + ) + with self.assertRaisesRegex(ValueError, "Chapter count mismatch"): + cmd_apply_chapters(args) + + def test_russian_track_removal_leaves_non_russian_streams(self): + source = ASSET_DIR / "test_auto.mkv" + output = self.output("no_russian.mkv") + args = command_args(source, output) + self.assertTrue(cmd_remove_russian_from_db(args)[0]) + media = probe_media(output) + self.assertEqual( + sum(stream.get("codec_type") == "audio" for stream in media["streams"]), + 1, + ) + self.assertFalse( + any( + stream.get("tags", {}).get("language") == "rus" + for stream in media["streams"] + if stream.get("codec_type") in {"audio", "subtitle"} + ) + ) + + def test_dry_run_does_not_create_output(self): + output = self.output("dry_run.mkv") + args = command_args( + ASSET_DIR / "test_auto.mkv", output, dry_run=True, width=320, + height=180, crf=30, + ) + self.assertTrue(cmd_downsize(args)[0]) + self.assertFalse(output.exists()) + + +if __name__ == "__main__": + unittest.main()