Files
Server-scripts/audiobook_library/test/test_audiobook.py
T

221 lines
8.4 KiB
Python
Raw Normal View History

2026-11-21 15:20:39 +01:00
import json
import os
import shutil
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from audiobook_library import Audiobook
from audiobook_library import audiobook as audiobook_module
from audiobook_library import audiobook_helpers as helpers
class AudiobookTests(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.TemporaryDirectory()
self.root = Path(self.tempdir.name)
def tearDown(self):
self.tempdir.cleanup()
def make_book(self):
book_dir = self.root / "Artist" / "Book"
book_dir.mkdir(parents=True)
files = [book_dir / "02 - track.mp3", book_dir / "01 - track.mp3"]
for file in files:
file.touch()
book = Audiobook(book_dir, self.root)
book.files = files
book.firstFile = files[0]
book.fileConunt = 2
book.singleFile = False
book.metadata = {
"artist": "Artist",
"album": "Book",
"composer": "Reader",
"comment": "comment",
"genre": "Fantasy",
"grouping": "Series #1",
"albumartist": "",
"description": "description",
"title": "Book",
}
book.write_fields_from_metadata()
return book
def test_helper_functions(self):
self.assertEqual(
helpers.ffmpeg_escape(Path("a'b")),
str(Path("a'b").resolve()).replace("'", r"'\''"),
)
self.assertEqual(helpers.clean_genre(" audio books "), "audio books")
self.assertEqual(helpers.clean_genre("Sci-Fi"), "Science Fiction")
self.assertEqual(
helpers.ffmetadata_escape(r"a\=b;c#d\n"),
r"a\\\=b\;c\#d\\n",
)
self.assertEqual(helpers._to_str(None), "")
self.assertEqual(helpers._to_str(["a", "b"]), "a; b")
self.assertEqual(helpers.cleanup("a, , b c"), "a, b c")
self.assertEqual(helpers.get_empty_keys({"a": "", "b": "x"}), "Empty: a")
self.assertEqual(helpers.get_empty_keys({"a": "x"}), "")
self.assertEqual(
helpers.normalize_name("Series - Book 2 - Title", "Series"), "Title"
)
result = SimpleNamespace(stdout=json.dumps({"chapters": [{"title": "x"}]}))
with patch.object(helpers.subprocess, "run", return_value=result):
self.assertEqual(
helpers.get_chapters(self.root / "book.mp3"), [{"title": "x"}]
)
with patch.object(helpers.subprocess, "check_output", return_value="12.5"):
self.assertEqual(helpers.get_duration_ms(self.root / "book.mp3"), 12500)
with patch.object(
helpers.subprocess,
"check_output",
return_value=json.dumps(
{"streams": [{"codec_name": "MP3", "bit_rate": "96000"}]}
),
):
self.assertEqual(
helpers.get_codec_bitrate(self.root / "book.mp3"), ("mp3", "96k")
)
with self.assertRaises(ValueError):
helpers.get_codec_bitrate(None)
def test_metadata_read_write_boundaries(self):
class Tags:
def __init__(self):
self.saved = False
def save(self, *args):
self.saved = True
def delall(self, _):
pass
def add(self, _):
pass
tags = Tags()
with patch.object(helpers, "ID3", return_value=tags), patch.object(
helpers, "File", return_value=None
):
self.assertEqual(
helpers.get_metadata_all(self.root / "x.mp3")["title"], ""
)
helpers.write_metadata(
self.root / "x.mp3", ["title"], ["Book"], dry_run=True
)
helpers.write_metadata(self.root / "x.mp3", ["title"], ["Book"])
self.assertTrue(tags.saved)
def test_metadata_and_track_methods(self):
book = self.make_book()
self.assertEqual(book.get_first_file(), book.files[0])
self.assertEqual(book.extract_track_number(Path("CD2-03.mp3")), 1003)
self.assertEqual(book.extract_track_number(Path("Track 07.mp3")), 7)
self.assertEqual(book.extract_track_number(Path("unknown.mp3")), 0)
self.assertIn("Book", repr(book))
book.write_metadata_from_fields()
self.assertEqual(book.metadata["albumartist"], "Artist")
book.metadata["grouping"] = "Series #2"
book.write_fields_from_metadata()
self.assertEqual((book.series, book.series_num), ("Series", "2"))
with patch.object(audiobook_module, "get_metadata_all", return_value=book.metadata):
book.load_metadata()
book.fix_artist_from_comment()
book.comment = "Narrated by Reader, extra"
book.fix_composer_from_comment()
self.assertEqual(book.composer, "Reader")
book.fix_composer_from_path()
book.fix_composer_from_narrator()
book.name = ""
book.fix_name()
book.genre = "Sci-Fi"
book.fix_genre()
self.assertEqual(book.genre, "Science Fiction")
book.title = ""
book.singleFile = True
book.fix_title()
self.assertEqual(book.title, book.name)
book.series_and_num = ""
book.fix_series()
self.assertTrue(book.generate_dir_from_metadata()[0].is_relative_to(self.root))
def test_fix_series_from_series_number_title_path(self):
examples = [
("Jack Reacher 10: The Hard Way (by Dick Hill)", "10"),
("Jack Reacher 1: Killing Floor (by Dick Hill)", "1"),
("Jack Reacher 28: The Secret (by Jeff Harding)", "28"),
("Jack Reacher 10 - The Hard Way", "10"),
("Jack Reacher #10: The Hard Way", "10"),
("Jack Reacher - #10 - The Hard Way", "10"),
("Jack Reacher - 10 - The Hard Way", "10"),
("Jack Reacher - Book 10 - The Hard Way", "10"),
("Jack Reacher Book 10 - The Hard Way", "10"),
("Jack Reacher: Book 10: The Hard Way", "10"),
("Jack Reacher - Band 10 - The Hard Way", "10"),
("Jack Reacher - Volume 10 - The Hard Way", "10"),
("Jack Reacher - Vol 10 - The Hard Way", "10"),
("Jack Reacher - Book 10", "10"),
("10 - The Hard Way", "10"),
("Jack Reacher - 10", "10"),
]
for path_name, number in examples:
with self.subTest(path_name=path_name):
book_dir = self.root / "Author" / path_name
book_dir.mkdir(parents=True)
book = Audiobook(book_dir, self.root)
book.series_and_num = "Jack Reacher"
book.fix_series()
self.assertEqual(book.series, "Jack Reacher")
self.assertEqual(book.series_num, number)
self.assertEqual(book.series_and_num, f"Jack Reacher #{number}")
2026-11-21 15:20:39 +01:00
def test_file_operations(self):
book = self.make_book()
destination = self.root / "new"
book.move(destination, "Artist - Book", dry_run=True)
self.assertEqual(book.bookPath, destination)
self.assertTrue(book.files[0].exists())
book.action_required = True
book.create_m4b_from_book()
book.write_metadata()
book.action_required = False
with patch.object(audiobook_module, "write_metadata"):
book.changed = True
book.write_metadata(keys=["title"], dry_run=True)
book.fix_artist_dir()
book.fix_artist_from_path(False)
def test_create_m4b_from_audio_assets(self):
2026-11-21 15:42:16 +01:00
assets = Path(os.environ.get("AUDIOBOOK_TEST_ASSETS", Path(__file__).resolve().parents[2] /\
"testassets" / "audiobook_library"))
2026-11-21 15:20:39 +01:00
source_book = next(assets.glob("*/*"))
expected_track_count = len(list(source_book.glob("*.mp3")))
self.assertGreater(expected_track_count, 0)
book_dir = self.root / source_book.name
shutil.copytree(source_book, book_dir)
book = Audiobook(book_dir, self.root)
book.init_book()
book.create_m4b_from_book(creat_m4b_no_delete=True)
output = book_dir / f"{book_dir.name}.m4b"
self.assertTrue(output.is_file())
self.assertEqual(len(list(book_dir.glob("*.mp3"))), expected_track_count)
self.assertEqual(book.files, [output])
self.assertTrue(book.singleFile)
if __name__ == "__main__":
unittest.main()