返回 last30days-skill
test_dedupe_v3.py
根目录 / tests / test_dedupe_v3.py
1 """Unit tests for dedupe.py: text normalization, similarity metrics, and deduplication."""
2
3 import unittest
4
5 from lib import dedupe
6 from lib.schema import SourceItem
7
8
9 def _item(
10 title: str,
11 body: str = "",
12 source: str = "reddit",
13 item_id: str = "t1",
14 url: str | None = None,
15 ) -> SourceItem:
16 return SourceItem(
17 item_id=item_id, source=source, title=title, body=body,
18 url=f"https://example.com/{item_id}" if url is None else url,
19 engagement={}, metadata={},
20 )
21
22 # ---------------------------------------------------------------------------
23 # normalize_text
24 # ---------------------------------------------------------------------------
25
26
27 class TestNormalizeText(unittest.TestCase):
28
29 def test_lowercases(self):
30 self.assertEqual(dedupe.normalize_text("Hello World"), "hello world")
31
32 def test_strips_punctuation(self):
33 self.assertEqual(dedupe.normalize_text("it's a test!"), "it s a test")
34
35 def test_collapses_whitespace(self):
36 self.assertEqual(dedupe.normalize_text("a b\t\nc"), "a b c")
37
38 def test_empty_string(self):
39 self.assertEqual(dedupe.normalize_text(""), "")
40
41 # ---------------------------------------------------------------------------
42 # get_ngrams
43 # ---------------------------------------------------------------------------
44
45
46 class TestGetNgrams(unittest.TestCase):
47
48 def test_simple_trigrams(self):
49 ngrams = dedupe.get_ngrams("abcde")
50 self.assertEqual(ngrams, {"abc", "bcd", "cde"})
51
52 def test_short_text_returns_whole(self):
53 ngrams = dedupe.get_ngrams("ab")
54 self.assertEqual(ngrams, {"ab"})
55
56 def test_empty_returns_empty_set(self):
57 self.assertEqual(dedupe.get_ngrams(""), set())
58
59 def test_normalizes_before_ngrams(self):
60 # "A!B" -> "a b" after normalization -> {"a b"}
61 ngrams = dedupe.get_ngrams("A!B")
62 self.assertEqual(ngrams, {"a b"})
63
64 # ---------------------------------------------------------------------------
65 # jaccard_similarity
66 # ---------------------------------------------------------------------------
67
68
69 class TestJaccardSimilarity(unittest.TestCase):
70
71 def test_identical_sets(self):
72 self.assertAlmostEqual(dedupe.jaccard_similarity({"a", "b"}, {"a", "b"}), 1.0)
73
74 def test_disjoint_sets(self):
75 self.assertAlmostEqual(dedupe.jaccard_similarity({"a"}, {"b"}), 0.0)
76
77 def test_partial_overlap(self):
78 result = dedupe.jaccard_similarity({"a", "b", "c"}, {"b", "c", "d"})
79 self.assertAlmostEqual(result, 2.0 / 4.0)
80
81 def test_empty_left(self):
82 self.assertAlmostEqual(dedupe.jaccard_similarity(set(), {"a"}), 0.0)
83
84 def test_both_empty(self):
85 self.assertAlmostEqual(dedupe.jaccard_similarity(set(), set()), 0.0)
86
87 # ---------------------------------------------------------------------------
88 # token_jaccard
89 # ---------------------------------------------------------------------------
90
91
92 class TestTokenJaccard(unittest.TestCase):
93
94 def test_identical_texts(self):
95 self.assertAlmostEqual(dedupe.token_jaccard("hello world", "hello world"), 1.0)
96
97 def test_completely_different(self):
98 self.assertAlmostEqual(dedupe.token_jaccard("alpha beta", "gamma delta"), 0.0)
99
100 def test_filters_stopwords(self):
101 # "the" and "a" are stopwords, so "big cat" vs "big dog" should compare on {big, cat} vs {big, dog}
102 result = dedupe.token_jaccard("the big cat", "a big dog")
103 self.assertAlmostEqual(result, 1.0 / 3.0) # {big} / {big, cat, dog}
104
105 def test_filters_single_char_tokens(self):
106 self.assertAlmostEqual(
107 dedupe.token_jaccard("x shared alpha", "x shared beta"), 1.0 / 3.0
108 )
109 self.assertEqual(dedupe.token_jaccard("x alpha", "x beta"), 0.0)
110
111 # ---------------------------------------------------------------------------
112 # hybrid_similarity
113 # ---------------------------------------------------------------------------
114
115
116 class TestHybridSimilarity(unittest.TestCase):
117
118 def test_identical_texts(self):
119 self.assertAlmostEqual(dedupe.hybrid_similarity("same text", "same text"), 1.0)
120
121 def test_completely_different(self):
122 result = dedupe.hybrid_similarity("aaaaaa", "zzzzzz")
123 self.assertLess(result, 0.1)
124
125 def test_takes_max_of_both_methods(self):
126 text_a = "OpenClaw security issues discussion"
127 text_b = "OpenClaw security issues thread"
128 ngram_sim = dedupe.jaccard_similarity(
129 dedupe.get_ngrams(text_a), dedupe.get_ngrams(text_b)
130 )
131 token_sim = dedupe.token_jaccard(text_a, text_b)
132 self.assertAlmostEqual(
133 dedupe.hybrid_similarity(text_a, text_b),
134 max(ngram_sim, token_sim),
135 )
136
137 # ---------------------------------------------------------------------------
138 # item_text
139 # ---------------------------------------------------------------------------
140
141
142 class TestItemText(unittest.TestCase):
143
144 def test_combines_fields(self):
145 item = _item("My Title", "My Body")
146 text = dedupe.item_text(item)
147 self.assertIn("My Title", text)
148 self.assertIn("My Body", text)
149
150 def test_skips_none_fields(self):
151 item = _item("Title", "")
152 item.author = None
153 item.container = None
154 text = dedupe.item_text(item)
155 self.assertEqual(text, "Title")
156
157 def test_includes_author_and_container(self):
158 item = _item("Title", "Body")
159 item.author = "john"
160 item.container = "r/python"
161 text = dedupe.item_text(item)
162 self.assertIn("john", text)
163 self.assertIn("r/python", text)
164
165 # ---------------------------------------------------------------------------
166 # dedupe_items
167 # ---------------------------------------------------------------------------
168
169
170 class TestDedupeItems(unittest.TestCase):
171
172 def test_keeps_unique_items(self):
173 items = [
174 _item("OpenClaw is amazing", item_id="a"),
175 _item("NanoClaw security review", item_id="b"),
176 _item("IronClaw Rust architecture", item_id="c"),
177 ]
178 result = dedupe.dedupe_items(items)
179 self.assertEqual(len(result), 3)
180
181 def test_removes_near_duplicates(self):
182 items = [
183 _item("OpenClaw vs NanoClaw comparison review", item_id="a"),
184 _item("OpenClaw vs NanoClaw comparison review thread", item_id="b"),
185 ]
186 result = dedupe.dedupe_items(items)
187 self.assertEqual(len(result), 1)
188 self.assertEqual(result[0].item_id, "a") # keeps first
189
190 def test_keeps_first_of_duplicates(self):
191 items = [
192 _item("Same title here", item_id="first"),
193 _item("Same title here", item_id="second"),
194 ]
195 result = dedupe.dedupe_items(items)
196 self.assertEqual(result[0].item_id, "first")
197
198 def test_empty_body_items_kept(self):
199 item = SourceItem(
200 item_id="empty", source="reddit", title="", body="",
201 url="", engagement={}, metadata={},
202 )
203 result = dedupe.dedupe_items([item])
204 self.assertEqual(len(result), 1)
205
206 def test_threshold_respected(self):
207 items = [
208 _item("OpenClaw security analysis", item_id="a"),
209 _item("OpenClaw security review", item_id="b"),
210 ]
211 # With threshold=1.0, only exact matches are removed
212 result = dedupe.dedupe_items(items, threshold=1.0)
213 self.assertEqual(len(result), 2)
214 # With threshold=0.3, these similar items collapse
215 result_loose = dedupe.dedupe_items(items, threshold=0.3)
216 self.assertEqual(len(result_loose), 1)
217
218 if __name__ == "__main__":
219 unittest.main()
220
221
222 class TestPolymarketMatchedEvents(unittest.TestCase):
223
224 @staticmethod
225 def _market(event_id, title, question, matched=True):
226 metadata = {"event_id": event_id}
227 if matched:
228 metadata["matched_market"] = {"label": "San Francisco 49ers", "question": question}
229 return SourceItem(
230 item_id=event_id, source="polymarket", title=title,
231 body=f"{title}\n{question}", url=f"https://polymarket.com/event/{event_id}",
232 container="Polymarket", engagement={}, metadata=metadata,
233 )
234
235 def _champions(self, matched=True):
236 return [
237 self._market("1", "Pro Football: 2027 Champion",
238 "Will the San Francisco 49ers win the 2027 NFL championship?", matched),
239 self._market("2", "Pro Football: 2027 NFC Champion",
240 "Will the San Francisco 49ers win the 2027 NFC championship?", matched),
241 ]
242
243 def test_distinct_matched_events_are_both_kept(self):
244 items = self._champions()
245 self.assertGreaterEqual(
246 dedupe.hybrid_similarity(dedupe.item_text(items[0]), dedupe.item_text(items[1])), 0.7,
247 )
248 self.assertEqual([item.item_id for item in dedupe.dedupe_items(items)], ["1", "2"])
249
250 def test_the_same_matched_event_twice_is_kept_once(self):
251 first, _second = self._champions()
252 again = self._market("1", first.title, "Will the San Francisco 49ers win?")
253 self.assertEqual([item.item_id for item in dedupe.dedupe_items([first, again])], ["1"])
254
255 def test_unmatched_polymarket_items_still_dedupe_by_text(self):
256 self.assertEqual(len(dedupe.dedupe_items(self._champions(matched=False))), 1)
257
257 lines PYTHON