From 284bb0b058c8e9d243f5146ed039a41640dd8e47 Mon Sep 17 00:00:00 2001 From: Alan Date: Thu, 1 Oct 2026 08:28:45 +0800 Subject: [PATCH] Handle missing subtitle indexes when sorting equal timestamps --- srt.py | 4 ++-- tests/test_srt.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/srt.py b/srt.py index 905e334..38b4e9a 100755 --- a/srt.py +++ b/srt.py @@ -129,10 +129,10 @@ def __eq__(self, other): return isinstance(other, Subtitle) and vars(self) == vars(other) def __lt__(self, other): - return (self.start, self.end, self.index) < ( + return (self.start, self.end, self.index or 0) < ( other.start, other.end, - other.index, + other.index or 0, ) def __repr__(self): diff --git a/tests/test_srt.py b/tests/test_srt.py index 5e403c4..7b44459 100644 --- a/tests/test_srt.py +++ b/tests/test_srt.py @@ -411,6 +411,39 @@ def test_sort_and_reindex_handles_no_index(input_subs): assert not reindexed_subs +@pytest.mark.parametrize( + "indices", + [(None, 1), (1, None), (-1, None), (None, -1), (None, None), (0, None), (None, 0)], +) +def test_sort_and_reindex_same_times_with_missing_indices(indices): + subs = [ + CONTENTLESS_SUB(index=index, content=str(position)) + for position, index in enumerate(indices) + ] + expected = sorted(subs, key=lambda sub: sub.index or 0) + + result = list(srt.sort_and_reindex(subs)) + + assert [sub.content for sub in result] == [sub.content for sub in expected] + assert [sub.index for sub in result] == [1, 2] + assert [sub.index for sub in subs] == list(indices) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_compose_parsed_same_times_with_missing_index(reverse): + blocks = [ + "00:00:01,000 --> 00:00:02,000\nUnindexed\n\n", + "1\n00:00:01,000 --> 00:00:02,000\nIndexed\n\n", + ] + if reverse: + blocks.reverse() + + result = list(srt.parse(srt.compose(srt.parse("".join(blocks))))) + + assert [sub.content for sub in result] == ["Unindexed", "Indexed"] + assert [sub.index for sub in result] == [1, 2] + + @given(st.lists(subtitles(), min_size=1)) def test_sort_and_reindex_same_start_time_uses_end(input_subs): for sub in input_subs: