test: delete slow, timing-based and redundant tests

This commit is contained in:
imSp4rky
2026-12-05 15:20:05 -07:00
parent 783a2fc185
commit 3a0a74e694
292 changed files with 153 additions and 15174 deletions
-43
View File
@@ -89,11 +89,6 @@ def test_bad_style_fields_raise(fields):
sc.build_ass_style(fields)
def test_ass_field_names_are_accepted():
style = sc.build_ass_style({"Fontname": "My Font", "PrimaryColour": "&H0000FFFF", "MarginV": 40.0})
assert (style.fontname, style.primarycolor, style.marginv) == ("My Font", pysubs2.Color(255, 255, 0, 0), 40)
def test_the_look_goes_only_to_subtitles_that_are_not_already_ass(tmp_path):
style = sc.build_ass_style({})
vtt = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT)
@@ -107,22 +102,6 @@ def test_the_look_goes_only_to_subtitles_that_are_not_already_ass(tmp_path):
assert vtt.ass_video_size == ass.ass_video_size == (3840, 1600)
def test_a_stripped_styled_track_with_no_cues_left_stays_srt(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
sub = make_sub(tmp_path, "x.vtt", VTT.split("00:00:03")[0], Codec.WebVTT, sc.build_ass_style({}))
sub.convert(Codec.SubStationAlphav4)
sub.strip_hearing_impaired()
assert sub.codec == Codec.SubRip
def test_a_stripped_native_ass_track_is_not_restyled(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
sub = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4)
set_subtitle_look([sub], sc.build_ass_style({"fontname": "My Font"}), [])
sub.strip_hearing_impaired()
assert sub.codec == Codec.SubRip
def test_vtt_to_ass_gets_the_style_on_a_canvas_shaped_like_the_video(tmp_path):
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({"fontname": "My Font"}))
sub.convert(Codec.SubStationAlphav4)
@@ -134,15 +113,6 @@ def test_vtt_to_ass_gets_the_style_on_a_canvas_shaped_like_the_video(tmp_path):
assert subs.styles["Default"].fontsize == 72
def test_vtt_to_ass_without_a_style_is_left_as_converted(tmp_path):
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT)
sub.convert(Codec.SubStationAlphav4)
subs = pysubs2.load(str(sub.path))
assert "PlayResY" not in subs.info
assert subs.styles["Default"].fontname == "Arial"
@pytest.mark.parametrize("target", [Codec.SubStationAlphav4, Codec.SubStationAlpha])
def test_a_native_ass_track_is_never_restyled(tmp_path, target):
sub = make_sub(tmp_path, "x.ass", NATIVE_ASS, Codec.SubStationAlphav4, sc.build_ass_style({}))
@@ -167,14 +137,6 @@ def test_a_converter_canvas_is_kept_and_the_style_scales_to_it(tmp_path):
assert (top.fontname, top.alignment, top.italic) == ("My Font", pysubs2.Alignment.TOP_CENTER, True)
def test_restyling_twice_gives_the_same_file(tmp_path):
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({}))
sub.convert(Codec.SubStationAlphav4)
first = sub.path.read_text("utf8")
sc.style_substation(sub.path, sub.ass_style, sub.ass_video_size)
assert sub.path.read_text("utf8") == first
def test_a_stripped_styled_track_stays_styled_ass(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "auto"}, raising=False)
sub = make_sub(tmp_path, "x.vtt", VTT, Codec.WebVTT, sc.build_ass_style({"fontname": "My Font"}))
@@ -203,11 +165,6 @@ def test_subtitle_look_picks_the_format_and_style(sub_format, sub_font, fields,
assert (out_format, style.fontname if style else None) == expected
def test_a_typed_font_overrides_a_format_from_config():
out_format, style = subtitle_look(Codec.SubRip, "My Font", None, typed_format=False)
assert (out_format, style.fontname if style else None) == (Codec.SubStationAlphav4, "My Font")
def test_a_font_from_config_is_ignored_with_another_format():
assert subtitle_look(Codec.SubRip, "My Font", None, typed_font=False) == (Codec.SubRip, None)
assert subtitle_look("original", "My Font", {"fontsize": 60}, typed_font=False) == ("original", None)
-23
View File
@@ -106,22 +106,6 @@ def test_download_with_flag_bypasses_proxy(server, monkeypatch) -> None:
assert attachment.path is not None and attachment.path.read_bytes() == BODY
def test_download_with_proxy_download_uses_only_that_proxy(server, monkeypatch) -> None:
seen: dict = {}
def fake_direct(session, proxy=None):
seen["proxy"] = proxy
return Recorder()
monkeypatch.setattr(track_module, "direct_session", fake_direct)
proxied = Recorder(proxies={"https": "http://manifest-proxy:1"})
attachment = Attachment.from_url(url(server), name="thumbnail", session=proxied)
attachment.download(proxied, proxy_download="http://dl-proxy:2")
assert not proxied.got
assert seen["proxy"] == "http://dl-proxy:2"
assert proxied.proxies == {"https": "http://manifest-proxy:1"}
def test_no_proxy_download_wins_over_proxy_download(server, monkeypatch) -> None:
seen: dict = {}
monkeypatch.setattr(track_module, "direct_session", lambda s, proxy=None: seen.setdefault("p", proxy) or Recorder())
@@ -170,13 +154,6 @@ def test_direct_session_routes_through_the_given_proxy() -> None:
assert requests.utils.select_proxy("https://cdn.example.com/a", new.proxies) == "http://dl-proxy:2"
def test_direct_session_proxy_beats_environment(monkeypatch) -> None:
monkeypatch.setenv("HTTPS_PROXY", "http://env-proxy:9")
new = track_module.direct_session(requests.Session(), "http://dl-proxy:2")
settings = new.merge_environment_settings("https://cdn.example.com/a", {}, None, None, None)
assert settings["proxies"]["https"] == "http://dl-proxy:2"
def test_direct_session_copies_rnet_cookies_set_by_name() -> None:
from unshackle.core.session import RnetSession
-12
View File
@@ -22,18 +22,6 @@ def test_a_png_saved_as_jpg_is_image_png(tmp_path: Path) -> None:
assert Attachment(path=path).mime_type == "image/png"
def test_an_unknown_signature_falls_back_to_the_suffix(tmp_path: Path) -> None:
path = tmp_path / "font.ttf"
path.write_bytes(b"junk" * 8)
assert Attachment(path=path).mime_type == "application/x-truetype-font"
def test_a_given_mime_type_stays(tmp_path: Path) -> None:
path = tmp_path / "thumb.jpg"
path.write_bytes(PNG)
assert Attachment(path=path, mime_type="image/jpeg").mime_type == "image/jpeg"
@pytest.fixture
def png_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def fake_download(url: str, path: Path, **kwargs: object) -> Iterator[dict]:
@@ -13,11 +13,6 @@ from unshackle.core.tracks import Audio
from unshackle.core.wire import track_from_dict, track_to_dict
@pytest.mark.parametrize("layout", ["5.1.4", "7.1.2", "9.1.6"])
def test_an_immersive_layout_survives_construction(layout: str) -> None:
assert Audio(id_="a1", url="https://example.test/a", language="en", channels=layout).channels == layout
@pytest.mark.parametrize(
("value", "expected"),
[("5.1", 5.1), ("2ch", 2.0), ("2", 2.0), ("2.0", 2.0), ("A000", 2.0), ("F801", 5.1), (6, 6.0)],
-12
View File
@@ -2,7 +2,6 @@ import textwrap
import pytest
from unshackle.core.constants import SPACED_AUDIO_CODECS
from unshackle.core.manifests.hls import HLS
from unshackle.core.tracks.audio import Audio
@@ -36,11 +35,6 @@ def test_dts_hd_and_mpeg_h_sample_entries_map(mime: str, codec: Audio.Codec) ->
assert Audio.Codec.from_mime(mime) == codec
def test_unknown_mime_still_raises() -> None:
with pytest.raises(ValueError):
Audio.Codec.from_mime("dtsz")
@pytest.mark.parametrize(
("uri", "expected"),
[
@@ -80,12 +74,6 @@ def test_select_audio_codec_holds_a_single_declaration() -> None:
assert HLS.select_audio_codec(None, None) is None
def test_spaced_codec_constants_name_real_codecs() -> None:
"""The constant holds bare strings, so a rename must not silently stop matching."""
for value in SPACED_AUDIO_CODECS:
assert value in {c.value for c in Audio.Codec}, f"{value} is not an Audio.Codec value"
def test_a_short_ladder_rung_cannot_hide_a_group_codec() -> None:
"""
One GROUP-ID is reached from every variant that references it, and a low rung may
-19
View File
@@ -65,12 +65,6 @@ def test_surviving_senc_raises(tmp_path: Path) -> None:
assert_fragments_decrypted(f)
def test_surviving_cenc_senc_raises(tmp_path: Path) -> None:
f = write(tmp_path, "cenc.mp4", FTYP, MOOV, moof(senc()), MDAT)
with pytest.raises(ValueError, match=r"1/1 fragment"):
assert_fragments_decrypted(f)
def test_leftover_piff_uuid_after_senc_removed_does_not_raise(tmp_path: Path) -> None:
# live DASH shape: the traf shipped senc+saiz+saio plus a duplicate PIFF uuid. mp4decrypt
# consumed senc, detached senc/saiz/saio, and left the uuid on a fully decrypted fragment.
@@ -86,12 +80,6 @@ def test_stray_senc_bytes_in_mdat_ignored(tmp_path: Path) -> None:
assert_fragments_decrypted(f)
def test_senc_text_without_plausible_size_ignored(tmp_path: Path) -> None:
# "senc" inside a free-box string has no valid box size before it
f = write(tmp_path, "text.mp4", FTYP, MOOV, moof(box(b"free", b"presence sencoded here")), MDAT)
assert_fragments_decrypted(f)
def test_senc_bytes_inside_trun_payload_ignored(tmp_path: Path) -> None:
# a trun sample entry spelling "senc" after a size-looking duration; only a byte scan bites
trun = box(b"trun", b"\x00\x00\x03\x01" + struct.pack(">I", 2) + struct.pack(">I", 512) + b"senc")
@@ -125,13 +113,6 @@ def test_senc_outside_traf_ignored(tmp_path: Path) -> None:
assert_fragments_decrypted(f)
def test_senc_nested_under_non_traf_ignored(tmp_path: Path) -> None:
# senc two levels down under a non-traf container: only traf children count
meta = box(b"meta", senc())
f = write(tmp_path, "nested.mp4", FTYP, MOOV, box(b"moof", box(b"mfhd", b"\x00" * 8) + meta), MDAT)
assert_fragments_decrypted(f)
def test_undersized_largesize_box_does_not_desync_walk(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
# size==1 reads a 16-byte header, so a largesize of 12 clears the 8-byte floor but
# still stalls the cursor onto payload; only a header-aware floor catches it
-98
View File
@@ -64,12 +64,6 @@ def test_select_hybrid_picks_base_per_resolution_and_lowest_dv(ladder: list[Vide
assert ids(chosen) == {"hdr10p-2160", "hdr10p-1080", "dv-360"}
def test_select_hybrid_ingredient_is_lowest_dv_regardless_of_quality(ladder: list[Video]) -> None:
# Even when only 2160 is requested, the ingredient is the globally lowest DV.
chosen = list(filter(Tracks().select_hybrid(ladder, [2160]), ladder))
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
def test_select_hybrid_prefers_hdr10p_over_hdr10() -> None:
H = Video.Codec.HEVC
tracks = [
@@ -108,13 +102,6 @@ def test_select_hybrid_skips_a_base_that_is_not_hevc() -> None:
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
def test_select_hybrid_no_dv_selects_only_base() -> None:
H = Video.Codec.HEVC
tracks = [make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H)]
chosen = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
assert ids(chosen) == {"hdr10p-2160"}
def dv_hdr10p(track_id: str, height: int, bitrate: int) -> Video:
video = make_video(track_id, range_=Video.Range.DV, height=height, bitrate=bitrate, codec=Video.Codec.HEVC)
video.hdr10plus = True
@@ -147,17 +134,6 @@ def test_select_hybrid_builds_a_hybrid_only_where_no_dv_track_carries_hdr10p() -
assert {t.id for t in chosen if t.hybrid_base_only} == {"hdr10-1080", "dv-360"}
def test_a_dv_hdr10p_track_used_only_for_its_rpu_stays_an_ingredient() -> None:
H = Video.Codec.HEVC
tracks = [
make_video("hdr10-1080", range_=Video.Range.HDR10, height=1080, bitrate=8_000_000, codec=H),
dv_hdr10p("dvp-360", 360, 700_000),
]
chosen = list(filter(Tracks().select_hybrid(tracks, [1080]), tracks))
Tracks.flag_hybrid_ingredients(chosen, [])
assert all(t.hybrid_base_only for t in chosen) and ids(chosen) == {"hdr10-1080", "dvp-360"}
def dv_hdr10(track_id: str, height: int, bitrate: int, range_: Video.Range = Video.Range.HDR10) -> Video:
video = make_video(track_id, range_=range_, height=height, bitrate=bitrate, codec=Video.Codec.HEVC)
video.dv_compatible_bitstream = True
@@ -175,16 +151,6 @@ def test_select_hybrid_takes_a_dv_hdr10_track_and_no_profile_5_donor() -> None:
assert ids(chosen) == {"dvhdr-2160"} and chosen[0].native_hybrid
def test_select_hybrid_prefers_a_finished_hybrid_that_carries_hdr10p() -> None:
tracks = [
dv_hdr10("dvhdr-2160", 2160, 9_000_000),
dv_hdr10("dvhdrp-2160", 2160, 7_000_000, Video.Range.HDR10P),
dv_hdr10p("dvp-2160", 2160, 6_000_000),
]
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))) == {"dvhdrp-2160"}
assert ids(list(filter(Tracks().select_hybrid(tracks, [2160], worst=True), tracks))) == {"dvp-2160"}
def test_select_hybrid_picks_no_base_that_has_no_dv_track_to_take_an_rpu_from() -> None:
H = Video.Codec.HEVC
tracks = [
@@ -207,15 +173,6 @@ def test_merge_dedups_shared_ingredient_and_deliverable() -> None:
assert [t.id for t in merged] == ["hdr10p-2160", "dv-1080", "sdr-2160"]
def test_merge_preserves_order_and_keeps_distinct_dv() -> None:
H = Video.Codec.HEVC
ingredient = make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=H)
deliverable = make_video("dv-2160", range_=Video.Range.DV, height=2160, bitrate=25_000_000, codec=H)
merged = Tracks.merge_video_selections([ingredient], [deliverable])
assert [t.id for t in merged] == ["dv-360", "dv-2160"]
def test_merge_dedup_uses_track_identity_by_id() -> None:
# Tracks compare equal by id; merge must treat same-id tracks as one.
H = Video.Codec.HEVC
@@ -241,22 +198,6 @@ def test_partition_admits_hdr10p_to_pool_when_requested(ladder: list[Video]) ->
assert ids(candidates) == {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"}
def test_partition_admits_dv_and_hdr10p_when_both_requested(ladder: list[Video]) -> None:
"""`-r HYBRID,HDR10P,DV`: both ranges enter the deliverable pool."""
_, pool = Tracks.partition_hybrid_videos(ladder, [Video.Range.HDR10P, Video.Range.DV])
assert {"hdr10p-2160", "hdr10p-1080", "dv-2160", "dv-1080", "dv-360"} <= ids(pool)
def test_partition_hdr10_requested_does_not_admit_hdr10p() -> None:
H = Video.Codec.HEVC
tracks = [
make_video("hdr10-2160", range_=Video.Range.HDR10, height=2160, bitrate=20_000_000, codec=H),
make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H),
]
_, pool = Tracks.partition_hybrid_videos(tracks, [Video.Range.HDR10])
assert ids(pool) == {"hdr10-2160"}
def flagged(tracks: list[Video]) -> set[str]:
return {t.id for t in tracks if t.hybrid_base_only}
@@ -278,16 +219,6 @@ def test_flag_hybrid_plus_hdr10p_keeps_base_deliverable(ladder: list[Video]) ->
assert flagged(ladder) == {"dv-360"}
def test_flag_hybrid_plus_hdr10p_and_dv_keeps_both_deliverables(ladder: list[Video]) -> None:
"""`-r HYBRID,HDR10P,DV`: best DV is a deliverable, lowest DV stays
ingredient-only; hybrid + HDR10+ + DV are muxed."""
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, [1080]), ladder))
base = next(t for t in ladder if t.id == "hdr10p-1080")
best_dv = next(t for t in ladder if t.id == "dv-1080")
Tracks.flag_hybrid_ingredients(hybrid_selected, [base, best_dv])
assert flagged(ladder) == {"dv-360"}
def test_flag_single_dv_rendition_as_deliverable_stays_unflagged() -> None:
"""`-r HYBRID,DV` with one DV rendition: the same track is ingredient and
deliverable, so it must still be muxed standalone."""
@@ -300,32 +231,3 @@ def test_flag_single_dv_rendition_as_deliverable_stays_unflagged() -> None:
dv = next(t for t in tracks if t.id == "dv-1080")
Tracks.flag_hybrid_ingredients(hybrid_selected, [dv])
assert flagged(tracks) == {"hdr10p-1080"}
def test_hybrid_plus_dv_deliverable_end_state(ladder: list[Video]) -> None:
"""`-r SDR,HDR10P,DV,HYBRID -q 2160,1080`: hybrid base + lowest DV ingredient,
de-duplicated against the best-DV-per-resolution deliverables and SDR."""
quality = [2160, 1080]
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, quality), ladder))
# Deliverables: best DV and SDR per requested resolution (what the dl Cartesian picks).
def best_per_res(range_: Video.Range, codec: Video.Codec | None = None) -> list[Video]:
out = []
for res in quality:
cands = [t for t in ladder if t.range == range_ and t.height == res and (codec is None or t.codec == codec)]
if cands:
out.append(max(cands, key=lambda t: t.bitrate))
return out
dv_deliverable = best_per_res(Video.Range.DV)
sdr_deliverable = [t for t in ladder if t.range == Video.Range.SDR]
final = Tracks.merge_video_selections(hybrid_selected, dv_deliverable + sdr_deliverable)
# No duplicates, and the lowest DV ingredient coexists with the DV deliverables.
assert len(final) == len({t.id for t in final})
assert "dv-360" in ids(final) # ingredient retained for hybrid build
assert {"dv-2160", "dv-1080"} <= ids(final) # standalone DV deliverables
assert {"hdr10p-2160", "hdr10p-1080"} <= ids(final)
assert {"sdr-2160", "sdr-1080-avc", "sdr-1080-hevc"} <= ids(final)
-12
View File
@@ -5,7 +5,6 @@ from collections.abc import Callable
from pathlib import Path
import pytest
from langcodes import Language
from unshackle.core.config import config
from unshackle.core.tracks import Audio, Subtitle, Tracks
@@ -61,17 +60,6 @@ def test_default_subtitle_index(language: str | None, types: list[str], expected
assert Tracks.default_subtitle_index(subtitles, language, types) == expected
@pytest.mark.parametrize(
("audio", "expected"),
[("en", 1), ("ar", 0), ("fr", 2), (None, 2)],
)
def test_a_forced_default_with_no_language_follows_the_audio(audio: str | None, expected: int) -> None:
kinds = [("ar", "forced"), ("en", "forced"), ("en", "normal")]
subtitles = [subtitle(i, lang, kind) for i, (lang, kind) in enumerate(kinds)]
audio_language = Language.get(audio) if audio else None
assert Tracks.default_subtitle_index(subtitles, None, ["forced", "normal"], audio_language) == expected
def downloaded_tracks(tmp_path: Path, audio: list[tuple[str, bool]], subtitles: list[tuple[str, str]]) -> Tracks:
tracks = Tracks()
for i, (lang, original) in enumerate(audio):
@@ -1,11 +1,7 @@
import json
from types import SimpleNamespace
import pytest
from unshackle.core import binaries
from unshackle.core.tracks import Audio, Tracks, Video
from unshackle.core.tracks.tracks import file_track_ids
def make_video(track_id: str, **data) -> Video:
@@ -36,18 +32,6 @@ def mux_until_mkvmerge_check(tracks: Tracks) -> None:
tracks.mux("Test Title")
def test_names_undeclared_video(monkeypatch):
monkeypatch.setattr(binaries, "MKVToolNix", None)
video = make_video("v1")
tracks = Tracks(video)
mux_until_mkvmerge_check(tracks)
assert video.needs_repack
assert video.data["audio_language"] == "zh"
assert video.embedded_audio_name() == "Chinese"
def test_service_declaration_is_preserved(monkeypatch):
monkeypatch.setattr(binaries, "MKVToolNix", None)
declared = make_video("v1", audio_language="th", audio_language_name="Thai [Original]")
@@ -100,17 +84,3 @@ def test_an_audio_track_with_own_stream_only_muxes_without_its_video(tmp_path, m
args = mux_args(Tracks(audio), {"video": 0, "audio": 1})
assert ("--no-video" in args) == own
assert args[args.index("--language") + 1] == ("1:th" if own else "0:th")
def test_repack_and_mux_share_the_embedded_audio_name():
assert make_video("v1", audio_language="zh").embedded_audio_name() == "Chinese"
assert make_video("v1", audio_language="zh", audio_language_name="Mandarin").embedded_audio_name() == "Mandarin"
def test_file_track_ids_reads_the_first_id_of_each_type(monkeypatch, tmp_path):
tracks = [{"id": 0, "type": "audio"}, {"id": 1, "type": "video"}, {"id": 2, "type": "audio"}]
reply = SimpleNamespace(stdout=json.dumps({"tracks": tracks}))
monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.run", lambda *a, **k: reply)
assert file_track_ids(tmp_path / "v.ts") == {"audio": 0, "video": 1}
monkeypatch.setattr("unshackle.core.tracks.tracks.subprocess.run", lambda *a, **k: SimpleNamespace(stdout=""))
assert file_track_ids(tmp_path / "v.ts") == {"video": 0, "audio": 1}
-100
View File
@@ -79,23 +79,12 @@ def cue_count(path) -> int:
return len(re.findall(r"-->", path.read_text("utf8")))
def test_resolve_webvtt_to_srt_order():
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
assert chain == ["subby", "pysubs2", "pycaption"]
def test_resolve_ass_to_srt_only_pysubs2_without_subtitleedit():
# subby and pycaption cannot read ASS, so only pysubs2 remains.
chain = [b.name for b in sc.resolve_backends(Codec.SubStationAlphav4, Codec.SubRip)]
assert chain == ["pysubs2"]
def test_subtitleedit_ranks_first_when_available(monkeypatch):
monkeypatch.setattr(binaries, "SubtitleEdit", "/usr/bin/seconv")
chain = [b.name for b in sc.resolve_backends(Codec.WebVTT, Codec.SubRip)]
assert chain[0] == "subtitleedit"
def test_styled_ass_to_ttml_vtt_prefers_pysubs2_over_subtitleedit(monkeypatch):
# Measured: SE flattens ASS inline styling to TTML/VTT; pysubs2 keeps i/b/u.
monkeypatch.setattr(binaries, "SubtitleEdit", "/usr/bin/seconv")
@@ -183,14 +172,6 @@ def test_ass_to_ssa_keeps_file_order(tmp_path, monkeypatch):
assert text.index("Sign") < text.index("Hello")
def test_webvtt_to_srt_conversion(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.vtt", VTT_SAMPLE, Codec.WebVTT)
out = sub.convert(Codec.SubRip, forced=True)
assert sub.codec == Codec.SubRip
assert cue_count(out) == 2
SCC_SAMPLE = """Scenarist_SCC V1.0
00:00:00;00 9420 9152 9723 5bc2 4f43 49ce c120 c445 20c2 c152 434f 5d80 9420 942c 942f
@@ -205,11 +186,6 @@ SCC_SAMPLE = """Scenarist_SCC V1.0
"""
def test_scc_mime_maps_to_the_scc_codec():
assert Codec.from_mime("x-scc") is Codec.SCC
assert Codec.from_mime("scc") is Codec.SCC
@pytest.mark.parametrize(
"sub_format, expected",
[
@@ -231,44 +207,11 @@ def test_scc_converts_to_the_requested_format_or_srt(tmp_path, monkeypatch, sub_
assert "¿Te gusta, Blanca Flor?" in sub.path.read_text("utf8")
def test_scc_to_webvtt_keeps_the_caption_row(tmp_path, monkeypatch):
from unshackle.commands.dl import convert_scc
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
convert_scc(sub, Codec.WebVTT)
assert "line:" in sub.path.read_text("utf8")
def test_scc_as_srt_converts_on_to_ass(tmp_path, monkeypatch):
from unshackle.commands.dl import convert_scc
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
sub = make_sub(tmp_path, "x.scc", SCC_SAMPLE, Codec.SCC)
convert_scc(sub, Codec.SubStationAlphav4)
assert sub.convert(Codec.SubStationAlphav4, forced=True).read_text("utf8").count("Dialogue:") == 2
def test_scc_without_cc1_captions_warns(tmp_path, monkeypatch, caplog):
from unshackle.commands.dl import convert_scc
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
cc3 = "Scenarist_SCC V1.0\n\n00:00:01:00\t1520 1520 1552 1552 c8e5 ecec ef80 152f 152f\n\n00:00:03:00\t152c 152c\n"
convert_scc(make_sub(tmp_path, "x.scc", cc3, Codec.SCC), None)
assert "has no CC1 captions" in caplog.text
def test_scc_with_a_bad_timecode_is_a_syntax_error():
with pytest.raises(SyntaxError):
Subtitle.parse(b"Scenarist_SCC V1.0\n\n00:00:xx;00\t9420 942f\n", Codec.SCC)
def test_same_codec_is_noop(tmp_path):
sub = make_sub(tmp_path, "x.srt", "1\n00:00:01,000 --> 00:00:02,000\nHi\n", Codec.SubRip)
assert sub.convert(Codec.SubRip) == sub.path
assert sub.codec == Codec.SubRip
FONT_ASS = """[Script Info]
ScriptType: v4.00+
@@ -345,16 +288,6 @@ Hello there.
"""
def test_sdh_stripping_removes_effects_keeps_dialogue(tmp_path, monkeypatch):
# subby's SDHStripper runs on SRT without SubtitleEdit installed.
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"sdh_method": "subby"}, raising=False)
sub = make_sub(tmp_path, "x.srt", SDH_SRT, Codec.SubRip)
sub.strip_hearing_impaired()
out = sub.path.read_text("utf8")
assert "Hello there." in out # real dialogue kept
assert "door creaks" not in out # bracketed effect removed (subby SDHStripper)
SDH_ASS = """[Script Info]
ScriptType: v4.00+
@@ -457,30 +390,6 @@ def test_segmented_fttml_joins_a_cue_split_at_a_segment_boundary():
]
def test_segmented_fttml_parses_and_converts(tmp_path, monkeypatch):
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
frag = (
'<?xml version="1.0" encoding="utf-8"?>'
'<tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en"><body><div>'
'<p begin="00:00:0{a}.000" end="00:00:0{b}.000">Line {a}</p>'
"</div></body></tt>"
)
data = build_stpp_mp4(frag.format(a=1, b=2), frag.format(a=3, b=4))
caption_set = Subtitle.parse(data, Codec.fTTML)
assert caption_total(caption_set) == 2
seg = tmp_path / "seg.stpp"
seg.write_bytes(data)
sub = Subtitle(url="https://example.test/x", language="en", codec=Codec.fTTML)
sub.path = seg
# download() converts fTTML -> TTML (only pycaption can read fTTML); then -> SRT.
sub.convert(Codec.TimedTextMarkupLang)
assert sub.codec == Codec.TimedTextMarkupLang
out = sub.convert(Codec.SubRip, forced=True)
assert cue_count(out) == 2
def downloaded_subtitle(tmp_path, monkeypatch, codec, data: bytes, descriptor: Track.Descriptor, track_data: dict):
"""A Subtitle whose base download is a no-op, so download() runs only the post-processing on data."""
monkeypatch.setattr("unshackle.core.config.config.subtitle", {}, raising=False)
@@ -688,12 +597,3 @@ def test_ttml_parse_raises_no_bs4_warning(data, codec, cues):
with warnings.catch_warnings():
warnings.simplefilter("error", XMLParsedAsHTMLWarning)
assert caption_total(Subtitle.parse(data, codec)) == cues
def test_ttml_parse_keeps_a_declaration_inside_the_cue_text():
cue = ttml_fragment(("00:00:01.000", "00:00:02.000", "<![CDATA[Hi <?xml a?> there]]>"))
expected = pycaption.DFXPReader().read(cue)
caption_set = Subtitle.parse((TTML_DECLARATION + cue).encode(), Codec.TimedTextMarkupLang)
assert pycaption.DFXPWriter().write(caption_set) == pycaption.DFXPWriter().write(expected)
+1 -99
View File
@@ -12,7 +12,7 @@ from __future__ import annotations
import pytest
from unshackle.commands.dl import SkippedSubtitle, download_tracks_in_passes
from unshackle.commands.dl import download_tracks_in_passes
from unshackle.core import process_exit
from unshackle.core.constants import DOWNLOAD_CANCELLED, RunCancel
from unshackle.core.tracks import Audio, Subtitle, Video
@@ -77,28 +77,6 @@ class Harness:
self.skipped.append(track)
def test_ctrl_c_cancels_the_tracks_still_downloading():
seen = {}
def run_one(track, _index):
if track.id == "a":
raise KeyboardInterrupt
# a deadline, not a delay: without the cancel this waits it out and records False
seen[track.id] = DOWNLOAD_CANCELLED.wait(timeout=10)
with pytest.raises(KeyboardInterrupt):
download_tracks_in_passes(
[make_video(), make_audio()],
2,
run_one,
skip_subtitle_errors=False,
on_subtitle_skipped=lambda track: None,
)
assert seen == {"v": True}
assert DOWNLOAD_CANCELLED.is_set() and RunCancel.pressed
def test_a_failed_track_is_not_a_cancel_of_the_user():
"""A child process that the cancel of the failed track ends can look like Ctrl+C."""
@@ -155,23 +133,6 @@ def test_failed_subtitle_does_not_truncate_video_or_audio():
assert h.skipped == [sub] # the subtitle was recorded as skipped
def test_good_subtitle_kept_bad_subtitle_skipped():
video = make_video()
good, bad = make_subtitle("s-en", "en"), make_subtitle("s-fr", "fr")
h = Harness(fail_ids={"s-fr"})
download_tracks_in_passes(
[video, good, bad],
4,
h.run_one,
skip_subtitle_errors=True,
on_subtitle_skipped=h.on_subtitle_skipped,
)
assert "s-en" in h.completed # the available subtitle still downloaded
assert h.skipped == [bad] # only the failing one was skipped
def test_subtitle_failure_stays_fatal_without_flag():
"""Default behaviour (flag off) is unchanged: a subtitle failure aborts the title."""
video = make_video()
@@ -206,62 +167,3 @@ def test_cancel_event_is_reset_between_titles():
assert set(h.completed) == {"v", "a"}
assert h.early_returned == []
def test_cancel_event_cleared_after_failed_final_subtitle():
"""A subtitle failing in the last pass leaves the event clear on exit, not set."""
video = make_video()
sub = make_subtitle("s-he", "he")
h = Harness(fail_ids={"s-he"})
download_tracks_in_passes(
[video, sub],
4,
h.run_one,
skip_subtitle_errors=True,
on_subtitle_skipped=h.on_subtitle_skipped,
)
assert not DOWNLOAD_CANCELLED.is_set() # the helper clears it on exit for any later code
def test_all_subtitles_skipped_video_audio_kept():
"""Every subtitle failing must not stop the video/audio, and each is recorded."""
video, audio = make_video(), make_audio()
s1, s2 = make_subtitle("s-en", "en"), make_subtitle("s-he", "he")
h = Harness(fail_ids={"s-en", "s-he"})
download_tracks_in_passes(
[video, audio, s1, s2],
4,
h.run_one,
skip_subtitle_errors=True,
on_subtitle_skipped=h.on_subtitle_skipped,
)
assert set(h.completed) == {"v", "a"} # both fatal tracks survived
assert {t.id for t in h.skipped} == {"s-en", "s-he"} # every failing subtitle recorded
def test_duplicate_language_subtitles_distinguished_by_id():
"""Forced + SDH share a language; a failure of each must be distinguishable by track id -
the reason ``SkippedSubtitle`` carries ``id`` and not just ``language``."""
forced, sdh = make_subtitle("en-forced", "en"), make_subtitle("en-sdh", "en")
h = Harness(fail_ids={"en-forced", "en-sdh"})
download_tracks_in_passes(
[make_video(), forced, sdh],
4,
h.run_one,
skip_subtitle_errors=True,
on_subtitle_skipped=h.on_subtitle_skipped,
)
assert [t.id for t in h.skipped] == ["en-forced", "en-sdh"] # same language, distinct ids
def test_skipped_subtitle_contract():
"""Pin the public ``skipped_subtitles`` entry shape - #113 serializes it into the job, so a
field rename/removal here is a breaking change and must fail a test."""
assert set(SkippedSubtitle.__annotations__) == {"id", "language", "title"}
assert SkippedSubtitle.__required_keys__ == frozenset({"id", "language", "title"})
-42
View File
@@ -158,31 +158,12 @@ def many() -> Tracks:
return t
def test_priority_orders_listed_then_rest_alphabetically(many: Tracks) -> None:
many.sort_subtitles(by_language=["en", "es", "fr"], group_by="language")
assert langs(many) == ["en", "es", "fr", "ar", "bg", "ja"]
def test_priority_outranks_the_original_language(many: Tracks) -> None:
# "all" resolves to the original language (ja), which must stay below the named ones
many.sort_subtitles(by_language=["en", "es", "all"], group_by="language")
assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
def test_priority_matches_regional_variants() -> None:
t = Tracks()
t.add([sub("ar"), sub("en-US"), sub("es-419"), sub("ja")])
t.sort_subtitles(by_language=["en", "es"], group_by="language")
assert langs(t) == ["en-US", "es-419", "ar", "ja"]
def test_priority_overlapping_entries_are_harmless() -> None:
t = Tracks()
t.add([sub("ar"), sub("en-GB"), sub("en-US"), sub("es"), sub("ja")])
t.sort_subtitles(by_language=["en", "en-US", "es"], group_by="language")
assert langs(t) == ["en-US", "en-GB", "es", "ar", "ja"]
@pytest.mark.parametrize("group_by", ["language", "type"])
def test_a_regional_priority_outranks_its_sibling(group_by: str) -> None:
t = Tracks()
@@ -191,23 +172,12 @@ def test_a_regional_priority_outranks_its_sibling(group_by: str) -> None:
assert langs(t) == ["en-US", "en-GB", "fr"]
def test_no_priority_leaves_order_unchanged(many: Tracks) -> None:
many.sort_subtitles(by_language=[], group_by="language")
assert langs(many) == ["ar", "bg", "en", "es", "fr", "ja"]
@pytest.mark.parametrize("token", ["all", "best"])
def test_magic_token_alone_floats_the_original_language(many: Tracks, token: str) -> None:
many.sort_subtitles(by_language=[token], group_by="language")
assert langs(many) == ["ja", "ar", "bg", "en", "es", "fr"]
@pytest.mark.parametrize("token", ["all", "best"])
def test_priority_outranks_either_magic_token(many: Tracks, token: str) -> None:
many.sort_subtitles(by_language=["en", "es", token], group_by="language")
assert langs(many) == ["en", "es", "ja", "ar", "bg", "fr"]
@pytest.fixture
def regionals() -> Tracks:
t = Tracks()
@@ -215,11 +185,6 @@ def regionals() -> Tracks:
return t
def test_fuzzy_priority_floats_regional_variants(regionals: Tracks) -> None:
regionals.sort_subtitles(by_language=["en"], group_by="language")
assert langs(regionals) == ["en", "en-GB", "en-US", "ar", "ja"]
def test_exact_priority_floats_only_the_named_tag(regionals: Tracks) -> None:
# CLDR rates en/en-US at distance 0, so exact mode needs the RFC 4647 string preference
# to hold en-US back; without it en-US floats and en-GB does not.
@@ -234,13 +199,6 @@ def test_exact_priority_still_falls_back_when_no_tag_is_string_equal() -> None:
assert langs(t) == ["cmn", "ar", "ja"]
@pytest.mark.parametrize("exact", [False, True])
def test_unparseable_priority_entry_is_ignored(many: Tracks, exact: bool) -> None:
# a config typo in language_priority must not crash the sort
many.sort_subtitles(by_language=["en", "engrish", "f", ""], group_by="language", exact_match=exact)
assert langs(many) == ["en", "ar", "bg", "es", "fr", "ja"]
def test_a_bare_audio_priority_sorts_the_meant_variant_then_its_other_forms() -> None:
from unshackle.core.tracks import Audio
+1 -82
View File
@@ -7,7 +7,7 @@ from rich.text import Text
from unshackle.core.config import config
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.utilities import language_name, multi_script_languages, with_script
from unshackle.core.utilities import with_script
def sub(lang: str, name: str | None = None, sdh: bool = False, original: bool = False) -> Subtitle:
@@ -22,11 +22,6 @@ def sub(lang: str, name: str | None = None, sdh: bool = False, original: bool =
)
def test_multi_script_languages_come_from_cldr() -> None:
assert {"zh", "yue", "sr"} <= multi_script_languages()
assert not {"en", "pt", "ja"} & multi_script_languages()
@pytest.mark.parametrize(
("tag", "expected"),
[
@@ -50,66 +45,6 @@ def test_with_script(tag: str, expected: str) -> None:
assert str(with_script(Language.get(tag))) == expected
@pytest.mark.parametrize(
("tag", "expected"),
[
("zh-Hant-TW", "Chinese (Traditional)"),
("zh-Hans-CN", "Chinese (Simplified)"),
("zh-Hant-HK", "Chinese (Traditional, Hong Kong)"),
("zh-TW", "Chinese (Taiwan)"),
("pt-BR", "Portuguese"),
("pt-PT", "Portuguese (Portugal)"),
("en-US", "English"),
("en-GB", "English (United Kingdom)"),
("ja-JP", "Japanese"),
("fr-CA", "French (Canada)"),
("ar-001", "Arabic"),
("es-419", "Spanish (Latin America)"),
("en", "English"),
("de-DE", "German"),
("en-ZZ", "English"),
("en-XA", "English"),
("en-Zzzz", "English"),
("sq-XK", "Albanian (Kosovo)"),
("mn-Mong-CN", "Mongolian (China)"),
("und", None),
("qaa", None),
("x-foo", None),
],
)
def test_language_name(tag: str, expected: str | None) -> None:
assert language_name(Language.get(tag)) == expected
@pytest.mark.parametrize(
("tag", "expected"),
[
("zh-Hant-TW", "中文(繁體)"),
("zh-Hans-CN", "中文(简体)"),
("zh-Hant-HK", "中文(繁體,香港)"),
("zh-Hans-MO", "中文(简体,澳门)"),
("zh-TW", "中文(台灣)"),
("zh-HK", "中文(香港)"),
("cmn-Hant", "中文(繁體)"),
("yue-Hant", "粵語(繁體)"),
("sr-ME", "Srpski (Crna Gora)"),
("ka", "ქართული"),
("hy", "Հայերեն"),
("pt-BR", "Português"),
("pt-PT", "Português (Portugal)"),
("es-419", "Español (Latinoamérica)"),
("sr-Latn-ME", "Srpski (latinica, Crna Gora)"),
("ja-JP", "日本語"),
("en-GB", "English (United Kingdom)"),
("en-HK", "English (Hong Kong)"),
("qaa", None),
],
)
def test_native_language_name(tag: str, expected: str | None, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"track_names": "native"})
assert language_name(Language.get(tag)) == expected
def test_native_subtitle_name_keeps_the_flag(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"track_names": "native"})
assert sub("zh-TW", sdh=True).get_track_name() == "中文(繁體) (SDH)"
@@ -147,12 +82,6 @@ def test_original_label_is_not_added_twice(name: str, monkeypatch: pytest.Monkey
assert sub("ja", name=name, original=True).get_track_name() == name
@pytest.mark.parametrize("label", [True, 1, ["Original"], " "])
def test_original_label_that_is_not_text_is_ignored(label: object, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": label, "track_names": "none"})
assert sub("ja", sdh=True, original=True).get_track_name() == "SDH"
def test_embedded_audio_takes_the_original_label(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"original_label": "[Original]"})
video = Video(id_="v", url="https://x/v", codec=Video.Codec.AVC, language="ja", is_original_lang=True)
@@ -175,10 +104,6 @@ def test_subtitle_names_and_tags_the_script_but_keeps_its_language() -> None:
assert str(track.language) == "zh-TW"
def test_subtitle_flag_follows_the_default_name() -> None:
assert sub("zh-CN", sdh=True).get_track_name() == "Chinese (Simplified) (SDH)"
def test_audio_gets_no_script() -> None:
track = Audio(id_="a", url="https://x/a", codec=Audio.Codec.AAC, language="zh-TW", bitrate=1)
assert track.get_track_name() == "Chinese (Taiwan)"
@@ -209,12 +134,6 @@ def test_mkvmerge_gets_the_subtitle_script_and_name(tmp_path: Path, mux_args: Ca
assert last_option("a.mp4", "--language") == "0:zh-TW"
def test_the_default_name_follows_a_later_language_change() -> None:
track = sub("yue")
track.language = Language.get("zh-Hant")
assert track.get_track_name() == "Chinese (Traditional)"
def test_a_language_assigned_as_text_later_is_parsed() -> None:
track = sub("pt")
track.language = "pt-PT"
-19
View File
@@ -1,19 +0,0 @@
from langcodes import Language
from unshackle.core.tracks import Audio, Tracks
def audio(lang: str, bitrate: int, id_: str) -> Audio:
return Audio(url=f"http://x/{id_}", id_=id_, language=lang, codec=Audio.Codec.AAC, bitrate=bitrate, channels=2.0)
def test_naming_a_track_keeps_its_region() -> None:
track = audio("fr-FR", 128000, "a1")
assert track.name is None
assert track.language.territory == "FR"
assert Language.get("fr-FR").territory == "FR"
def test_a_regional_request_picks_its_own_variant_over_a_higher_bitrate_sibling() -> None:
tracks = [audio("fr-FR", 128000, "a1"), audio("fr-CA", 192000, "a2")]
assert [str(t.language) for t in Tracks.by_language(tracks, ["fr-FR"])] == ["fr-FR"]
-12
View File
@@ -113,13 +113,6 @@ def test_merge_dedupes_repeated_style_blocks_before_cues():
assert out.index("STYLE") < out.index("-->")
def test_merge_skips_malformed_timing_line():
vtt = "WEBVTT\n\ngarbage --> not-a-time\nBroken\n\n00:00:01.000 --> 00:00:02.000\nGood\n"
out = merge_segmented_webvtt(vtt)
assert "Good" in out
assert "Broken" not in out
def test_rebase_moves_live_clock_cues_to_zero():
vtt = "WEBVTT\n\n498024:05:44.300 --> 498024:05:44.829 line:0.01%\nText\n"
out = rebase_webvtt(vtt, timestamp_ms("498024:00:14.700"))
@@ -133,11 +126,6 @@ def test_rebase_moves_cues_when_the_first_is_carried_over_from_before_the_offset
assert "00:03:48.598 --> 00:03:48.698\nNext" in out
def test_rebase_leaves_a_later_period_with_a_small_offset_alone():
vtt = "WEBVTT\n\n00:00:05.000 --> 00:00:12.000\nText\n"
assert rebase_webvtt(vtt, 10_000, 2000) == vtt
def test_rebase_leaves_presentation_time_cues_alone():
# a second pass, or a VOD period with a non-zero offset, must not shift again
vtt = "WEBVTT\n\n00:05:29.600 --> 00:05:30.129\nText\n"
@@ -9,14 +9,6 @@ def test_strips_timestamp_map_keeps_cues():
assert out.startswith("WEBVTT\n")
def test_strips_lowercase_timestamp_map():
# SubtitleEdit honours the header case-insensitively, so the strip must too
text = "WEBVTT\nx-timestamp-map=MPEGTS:900000,LOCAL:00:00:00.000\n\n00:00:22.690 --> 00:00:24.710\nHi\n"
out = Subtitle.strip_webvtt_timestamp_map(text)
assert "x-timestamp-map" not in out.lower()
assert "00:00:22.690 --> 00:00:24.710" in out
def test_no_timestamp_map_is_untouched():
text = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nHi\n"
assert Subtitle.strip_webvtt_timestamp_map(text) == text