返回 last30days-skill
test_comment_excerpt.py
根目录 / tests / test_comment_excerpt.py
1 """Stored Reddit comment text ends at a sentence or a word, not mid-word.
2
3 Real run, 2026-11-10: comments were stored cut at 200 characters
4 ("...thinking everyone now wants to be a progressive socialist. Th",
5 "...Giving it away also li") and those strings become quote lines.
6 """
7
8 from unittest import mock
9
10 import pytest
11
12 from lib import reddit, reddit_arctic, reddit_enrich, reddit_shreddit, snippet
13
14 SENTENCES = (
15 "The people who built these companies took real risks for decades and it paid off. "
16 "A lot of the commentary pretends that never happened and that wealth simply appears. "
17 "Politicians read one poll and start thinking everyone now wants to be a progressive socialist. "
18 "That is not what the numbers say when you look at who actually turns out to vote in off years. "
19 "Giving it away also limits what the next round of founders can raise from the same investors. "
20 "None of this means the current arrangement is fair, only that the alternatives are not free."
21 )
22 RUN_ON = " ".join(["supercalifragilistic"] * 40) # no sentence end anywhere
23
24
25 def test_short_text_is_returned_whole():
26 assert snippet.cut_quote(" Why lie about it more? ") == "Why lie about it more?"
27
28
29 def test_long_text_ends_at_a_sentence_within_the_limit():
30 cut = snippet.cut_quote(SENTENCES)
31
32 assert 200 < len(cut) <= 400
33 assert cut.endswith("off years.")
34 assert SENTENCES.startswith(cut)
35 assert not cut.endswith("...")
36
37
38 def test_no_sentence_end_cuts_at_a_word_boundary():
39 cut = snippet.cut_quote(RUN_ON)
40
41 assert len(cut) <= 400
42 assert cut.split()[-1] == "supercalifragilistic"
43 assert RUN_ON[len(cut)] == " "
44
45
46 def test_sentence_end_far_from_the_limit_is_not_used():
47 text = "Short opener. " + RUN_ON
48
49 cut = snippet.cut_quote(text)
50
51 assert len(cut) > 300 and cut.split()[-1] == "supercalifragilistic"
52
53
54 def test_one_unbroken_token_is_cut_hard():
55 assert snippet.cut_quote("x" * 900) == "x" * 400
56
57
58 def test_decimal_points_and_urls_are_not_sentence_ends():
59 text = ("word " * 70) + "the price moved 3.5 percent on example.com today and kept going " + ("more " * 30)
60
61 cut = snippet.cut_quote(text)
62
63 assert not cut.endswith("3.") and not cut.endswith("example.")
64
65
66 def test_shreddit_comments_are_stored_cut_cleanly():
67 html = f"""
68 <shreddit-comment-tree-stats total-comments="1" sort="TOP"></shreddit-comment-tree-stats>
69 <shreddit-comment created="2026-11-09T12:45:51+0000" author="reader" thingid="t1_aaa"
70 permalink="/r/elonmusk/comments/x1/comment/aaa/" score="56" depth="0">
71 <div id="t1_aaa-post-rtjson-content"><div><p>{SENTENCES}</p></div></div>
72 </shreddit-comment>
73 """
74 comment = reddit_shreddit.parse_comments(html)[0]
75
76 assert comment["excerpt"].endswith("off years.")
77 assert len(comment["excerpt"]) > 200
78
79
80 @pytest.fixture
81 def _no_arctic_network():
82 # Overrides conftest's stub so the real archive adapter runs (http.get mocked).
83 reddit_arctic.reset_memo()
84 yield
85 reddit_arctic.reset_memo()
86
87
88 def test_arctic_comments_are_stored_cut_cleanly(_no_arctic_network):
89 row = {"author": "reader", "body": SENTENCES, "score": 7,
90 "permalink": "/r/elonmusk/comments/abc/x/c1/", "created_utc": 1794268800}
91 with mock.patch.object(reddit_arctic.http, "get", return_value={"data": [{"kind": "t1", "data": row}]}):
92 comment = reddit_arctic.fetch_post_comments("abc")[0]
93
94 assert comment["excerpt"].endswith("off years.")
95
96
97 def test_scrapecreators_search_enrichment_stores_clean_excerpts():
98 raw = [{"body": SENTENCES, "ups": 9, "author": f"a{i}", "permalink": f"/c{i}/"} for i in range(2)]
99 items = [{"id": "R1", "url": "https://www.reddit.com/r/elonmusk/comments/abc/x/",
100 "engagement": {"score": 10}}]
101
102 with mock.patch.object(reddit, "fetch_post_comments", return_value=raw):
103 out = reddit.enrich_with_comments(items, "dummy-key", budget_seconds=5)
104
105 excerpts = [comment["excerpt"] for comment in out[0]["top_comments"]]
106 assert len(excerpts) == 2 and all(text.endswith("off years.") for text in excerpts)
107
108
109 @pytest.mark.parametrize("position", [0, 1])
110 def test_scrapecreators_enrichment_stores_clean_excerpts(position):
111 raw = [{"body": SENTENCES, "ups": 9, "author": f"a{i}", "permalink": f"/c{i}/"} for i in range(2)]
112 item = {"url": "https://www.reddit.com/r/elonmusk/comments/abc/x/"}
113
114 with mock.patch.object(reddit, "fetch_post_comments", return_value=raw):
115 out = reddit_enrich.enrich_reddit_item_sc(item, "dummy-key")
116
117 assert out["top_comments"][position]["excerpt"].endswith("off years.")
118
119
120 def test_newline_or_tab_is_a_word_boundary_too():
121 # A long list pasted on separate lines: the only boundaries near the
122 # limit are newlines, and the cut must not fall inside a word.
123 lines = "intro words\n" + "\n".join(f"item{n:03d}" for n in range(60))
124 cut = snippet.cut_quote(lines, limit=100)
125 assert len(cut) <= 100
126 assert cut.endswith(tuple(f"item{n:03d}" for n in range(60)))
127 assert len(cut) > 80
128 tabbed = "alpha\t" + "b" * 30 + "\t" + "c" * 30
129 assert snippet.cut_quote(tabbed, limit=50) == "alpha\t" + "b" * 30
130
130 lines PYTHON