返回 last30days-skill
test_devto.py
根目录 / tests / test_devto.py
1 """dev.to source: tag and search retrieval, relevance gating, comments."""
2
3 import datetime
4 import urllib.parse
5
6 import pytest
7
8 from lib import devto, normalize, pipeline
9
10
11 TODAY = datetime.date(2026, 10, 11)
12
13
14 @pytest.fixture(autouse=True)
15 def _fixed_today(monkeypatch):
16 monkeypatch.setattr(devto, "_today", lambda: TODAY)
17
18
19 @pytest.fixture(autouse=True)
20 def _fresh_cache():
21 devto.clear_cache()
22 yield
23 devto.clear_cache()
24
25
26 def _article(article_id, title, *, tags=("ai",), published="2026-10-05T12:00:00Z", reactions=5, comments=2):
27 return {
28 "id": article_id,
29 "title": title,
30 "description": f"About {title}",
31 "url": f"https://dev.to/someone/post-{article_id}",
32 "published_at": published,
33 "public_reactions_count": reactions,
34 "comments_count": comments,
35 "reading_time_minutes": 4,
36 "tag_list": list(tags),
37 "user": {"username": f"user{article_id}", "name": "Someone"},
38 "ai_disclosure_level": "not_disclosed",
39 }
40
41
42 class FakeApi:
43 def __init__(self, tags=None, search=None, comments=None, fail=()):
44 self.tags = tags or {}
45 self.search = search or []
46 self.comments = comments or {}
47 self.fail = set(fail)
48 self.calls = []
49
50 def __call__(self, method, url, headers=None, **kwargs):
51 self.calls.append(url)
52 parsed = urllib.parse.urlparse(url)
53 query = dict(urllib.parse.parse_qsl(parsed.query))
54 if parsed.path == "/api/articles":
55 if "tag" in self.fail:
56 raise OSError("tag feed down")
57 return self.tags.get(query["tag"], [])
58 if parsed.path == "/api/articles/search":
59 if "search" in self.fail:
60 raise OSError("search down")
61 assert headers and headers.get("Accept") == "application/vnd.forem.api-v1+json"
62 return self.search
63 if parsed.path == "/api/comments":
64 return self.comments.get(query["a_id"], [])
65 raise AssertionError(f"unexpected URL {url}")
66
67
68 def _install(monkeypatch, api):
69 monkeypatch.setattr(devto.http, "request", api)
70 return api
71
72
73 def test_devto_is_off_by_default():
74 assert "devto" not in pipeline.available_sources({}, None, x_pending=False)
75
76
77 def test_devto_tags_include_sources_and_search_each_activate_it():
78 assert "devto" in pipeline.available_sources({"_devto_tags": ["rust"]}, None, x_pending=False)
79 assert "devto" in pipeline.available_sources({"INCLUDE_SOURCES": "devto"}, None, x_pending=False)
80 assert "devto" in pipeline.available_sources({}, ["devto"], x_pending=False)
81
82
83 def test_search_alias_maps_dev_to():
84 assert pipeline.normalize_requested_sources(["dev.to"]) == ["devto"]
85
86
87 def test_resolve_tags_normalizes_dedupes_and_caps_by_depth():
88 assert devto.resolve_tags(None) == []
89 assert devto.resolve_tags(["#Rust", "async", "rust", "web dev"], depth="deep") == ["rust", "async", "webdev"]
90 assert devto.resolve_tags(["a", "b", "c"], depth="quick") == ["a"]
91
92
93 def test_without_tags_only_search_runs(monkeypatch):
94 api = _install(monkeypatch, FakeApi())
95 devto.search_devto("Claude Code", "2026-09-11", "2026-10-11")
96 assert not any("tag=" in url for url in api.calls)
97 assert sum("/search" in url for url in api.calls) == 1
98
99
100 def test_tag_feed_and_search_merge_dedupe_and_filter(monkeypatch):
101 shared = _article(1, "Kubernetes autoscaling in practice", tags=("kubernetes",))
102 api = _install(monkeypatch, FakeApi(
103 tags={"kubernetes": [shared, _article(2, "Kubernetes operators", tags=("kubernetes",))]},
104 search=[
105 dict(shared),
106 _article(3, "Debugging Kubernetes pods", tags=("kubernetes", "devops")),
107 _article(4, "My favourite sourdough recipe", tags=("cooking",)),
108 ],
109 ))
110 result = devto.search_devto("kubernetes", "2026-09-11", "2026-10-11", tags=["kubernetes"])
111 ids = sorted(article["id"] for article in result["articles"])
112 assert ids == [1, 2, 3]
113 assert "error" not in result
114 tag_call = next(url for url in api.calls if "tag=" in url)
115 assert "top=31" in tag_call
116
117
118 def test_articles_outside_the_window_are_dropped(monkeypatch):
119 _install(monkeypatch, FakeApi(tags={"rust": [
120 _article(1, "Rust async", tags=("rust",), published="2026-10-01T00:00:00Z"),
121 _article(2, "Rust async old", tags=("rust",), published="2026-08-01T00:00:00Z"),
122 ]}))
123 result = devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"], search_query="")
124 assert [article["id"] for article in result["articles"]] == [1]
125
126
127 @pytest.mark.parametrize("tags", [None, ["rust"]])
128 def test_historical_window_reaches_back_from_today_and_keeps_upper_bound(monkeypatch, tags):
129 historical = _article(1, "Rust async", tags=("rust",), published="2026-08-10T12:00:00Z")
130 recent = _article(2, "Rust async current", tags=("rust",), published="2026-10-10T12:00:00Z")
131 calls = []
132
133 def relative_window_api(method, url, headers=None, **kwargs):
134 query = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
135 days = int(query["top"])
136 calls.append(days)
137 assert (query["per_page"], query["page"]) == ("1000", "1")
138 cutoff = TODAY - datetime.timedelta(days=days)
139 return [row for row in (historical, recent)
140 if datetime.date.fromisoformat(row["published_at"][:10]) >= cutoff]
141
142 monkeypatch.setattr(devto.http, "request", relative_window_api)
143 result = devto.search_devto("rust async", "2026-08-01", "2026-08-31", tags=tags)
144 assert [row["id"] for row in result["articles"]] == [1]
145 assert calls and all(days == 72 for days in calls)
146 assert "error" not in result
147
148
149 @pytest.mark.parametrize("end", [None, "2026-10-11"])
150 def test_current_window_reach_covers_all_of_from_date(end):
151 assert devto._window_days("2026-09-11", end) == 31
152
153
154 def _paged_api(pages, calls, fail_page=None, path="/api/articles"):
155 def api(method, url, headers=None, **kwargs):
156 parsed = urllib.parse.urlparse(url)
157 if parsed.path != path:
158 return []
159 query = dict(urllib.parse.parse_qsl(parsed.query))
160 page = int(query.get("page", "1"))
161 calls.append(page)
162 if page == fail_page:
163 raise OSError("page down")
164 return pages[page - 1] if page <= len(pages) else []
165 return api
166
167
168 def _filler(start_id, count, published):
169 return [_article(start_id + i, f"Rust filler {i}", tags=("rust",), published=published) for i in range(count)]
170
171
172 @pytest.mark.parametrize("tags", [None, ["rust"]])
173 def test_historical_window_pages_past_newer_articles(monkeypatch, tags):
174 in_window = _article(1, "Rust async", tags=("rust",), published="2026-08-10T12:00:00Z")
175 calls = []
176 pages = [_filler(1000, devto.HISTORICAL_PER_PAGE, "2026-10-05T12:00:00Z"), [in_window]]
177 path = "/api/articles" if tags else "/api/articles/search"
178 monkeypatch.setattr(devto.http, "request", _paged_api(pages, calls, path=path))
179 result = devto.search_devto("rust async", "2026-08-01", "2026-08-31", tags=tags)
180 assert [row["id"] for row in result["articles"]] == [1]
181 assert calls == [1, 2]
182
183
184 def test_historical_paging_stops_at_the_page_cap(monkeypatch):
185 monkeypatch.setattr(devto, "HISTORICAL_MAX_PAGES", 3)
186 calls = []
187 pages = [_filler(1000 * n, devto.HISTORICAL_PER_PAGE, "2026-10-05T12:00:00Z") for n in range(1, 6)]
188 monkeypatch.setattr(devto.http, "request", _paged_api(pages, calls))
189 devto.search_devto("rust", "2026-08-01", "2026-08-31", tags=["rust"], search_query="")
190 assert calls == [1, 2, 3]
191
192
193 def test_historical_paging_stops_at_the_time_budget(monkeypatch):
194 monkeypatch.setattr(devto, "HISTORICAL_BUDGET_SECONDS", 0.0)
195 calls = []
196 pages = [_filler(1000 * n, devto.HISTORICAL_PER_PAGE, "2026-10-05T12:00:00Z") for n in range(1, 4)]
197 monkeypatch.setattr(devto.http, "request", _paged_api(pages, calls))
198 devto.search_devto("rust", "2026-08-01", "2026-08-31", tags=["rust"], search_query="")
199 assert calls == [1]
200
201
202 def test_one_paging_budget_covers_every_endpoint(monkeypatch):
203 clock = [0.0]
204 monkeypatch.setattr(devto.time, "monotonic", lambda: clock[0])
205 calls = []
206 full = _filler(1000, devto.HISTORICAL_PER_PAGE, "2026-10-05T12:00:00Z")
207 paged = _paged_api([full] * 5, calls)
208
209 def slow_api(method, url, **kwargs):
210 clock[0] += devto.HISTORICAL_BUDGET_SECONDS / 2 + 1
211 return paged(method, url, **kwargs)
212
213 monkeypatch.setattr(devto.http, "request", slow_api)
214 devto.search_devto("rust", "2026-08-01", "2026-08-31", depth="deep", tags=["rust", "go", "zig"], search_query="")
215 assert calls == [1, 2, 1, 1]
216
217
218 def test_later_page_failure_keeps_the_pages_already_fetched(monkeypatch):
219 calls = []
220 pages = [_filler(1000, devto.HISTORICAL_PER_PAGE, "2026-08-10T12:00:00Z")]
221 monkeypatch.setattr(devto.http, "request", _paged_api(pages, calls, fail_page=2))
222 result = devto.search_devto("rust", "2026-08-01", "2026-08-31", tags=["rust"], search_query="")
223 assert calls == [1, 2]
224 assert len(result["articles"]) == devto.TAG_PER_PAGE
225 assert "error" not in result
226
227
228 def test_historical_window_keeps_the_most_engaged_in_window_articles(monkeypatch):
229 rows = [
230 _article(i, f"Rust post {i}", tags=("rust",), published="2026-08-10T12:00:00Z", reactions=i)
231 for i in range(1, 51)
232 ]
233 rows.append(_article(99, "Rust hot but late", tags=("rust",), published="2026-09-10T12:00:00Z", reactions=500))
234 monkeypatch.setattr(devto.http, "request", _paged_api([rows], []))
235 result = devto.search_devto("rust", "2026-08-01", "2026-08-31", tags=["rust"], search_query="")
236 assert sorted(row["id"] for row in result["articles"]) == list(range(21, 51))
237
238
239 def test_unknown_tag_and_offtopic_search_stay_quiet(monkeypatch):
240 _install(monkeypatch, FakeApi(search=[_article(9, "Weekly frontend news", tags=("webdev",))]))
241 result = devto.search_devto("Taylor Swift", "2026-09-11", "2026-10-11")
242 assert result["articles"] == []
243 assert "error" not in result
244
245
246 def test_planner_quotes_are_stripped_from_the_search_query(monkeypatch):
247 api = _install(monkeypatch, FakeApi())
248 devto.search_devto("Claude Code", "2026-09-11", "2026-10-11", search_query='"Claude Code"')
249 search_call = next(url for url in api.calls if "/search" in url)
250 assert dict(urllib.parse.parse_qsl(urllib.parse.urlparse(search_call).query))["q"] == "Claude Code"
251
252
253 def test_partial_failure_keeps_results_and_total_failure_reports_error(monkeypatch):
254 _install(monkeypatch, FakeApi(search=[_article(1, "Rust async runtimes", tags=("rust",))], fail={"tag"}))
255 partial = devto.search_devto("rust async", "2026-09-11", "2026-10-11", tags=["rust"])
256 assert [a["id"] for a in partial["articles"]] == [1]
257 assert "error" not in partial
258
259 devto.clear_cache()
260 _install(monkeypatch, FakeApi(fail={"tag", "search"}))
261 failed = devto.search_devto("rust async", "2026-09-11", "2026-10-11", tags=["rust"])
262 assert failed["articles"] == []
263 assert "tag feed down" in failed["error"] and "search down" in failed["error"]
264
265
266 def test_identical_requests_are_fetched_once(monkeypatch):
267 api = _install(monkeypatch, FakeApi(tags={"rust": [_article(1, "Rust", tags=("rust",))]}))
268 devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"], search_query="")
269 devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"], search_query="")
270 assert sum("tag=rust" in url for url in api.calls) == 1
271
272
273 def test_parse_maps_engagement_and_metadata():
274 items = devto.parse_devto_response(
275 {"articles": [_article(7, "Rust async runtimes", tags=("rust",), reactions=40, comments=9)]},
276 query="rust async",
277 )
278 item = items[0]
279 assert item["id"] == "7"
280 assert item["engagement"] == {"reactions": 40, "comments": 9}
281 assert item["date"] == "2026-10-05"
282 assert item["author"] == "user7"
283 assert item["metadata"]["ai_disclosure_level"] == "not_disclosed"
284 assert 0 < item["relevance"] <= 1
285
286
287 def _source_items(articles):
288 parsed = devto.parse_devto_response({"articles": articles}, query="rust")
289 return normalize.normalize_source_items("devto", parsed, "2026-09-11", "2026-10-11")
290
291
292 def test_enrichment_targets_ranked_survivors_and_drops_spam(monkeypatch):
293 api = _install(monkeypatch, FakeApi(comments={
294 "1": [
295 {"body_html": "<p>Great &amp; useful</p>", "user": {"username": "alice"}, "children": [{}, {}]},
296 {"body_html": "<p>Official update tr.ee/dev-to</p>", "user": {"username": "bot"}, "children": []},
297 ],
298 "3": [{"body_html": "<p>Nice</p>", "user": {"username": "bob"}, "children": []}],
299 }))
300 items = _source_items([
301 _article(1, "Rust one", comments=4),
302 _article(2, "Rust two", comments=0),
303 _article(3, "Rust three", comments=1),
304 _article(4, "Rust four", comments=5),
305 ])
306 devto.enrich_source_items(items, top_k=2)
307
308 first = items[0].metadata["top_comments"]
309 assert [c["excerpt"] for c in first] == ["Great & useful"]
310 assert first[0]["score"] == 2 and first[0]["author"] == "alice"
311 assert not items[1].metadata.get("top_comments")
312 assert items[2].metadata["top_comments"][0]["excerpt"] == "Nice"
313 assert not items[3].metadata.get("top_comments")
314 assert not any("a_id=2" in url or "a_id=4" in url for url in api.calls)
315
316
317 def test_normalized_item_carries_comments_into_snippet_and_container():
318 parsed = devto.parse_devto_response({"articles": [_article(5, "Rust five")]}, query="rust")
319 parsed[0]["top_comments"] = [{"author": "c", "text": "Solid write-up", "replies": 1}]
320 item = normalize.normalize_source_items("devto", parsed, "2026-09-11", "2026-10-11")[0]
321 assert item.container == "dev.to"
322 assert item.metadata["top_comments"][0]["excerpt"] == "Solid write-up"
323 assert "Solid write-up" in item.body
324
325
326 def _diagnose_sources(argv, config=None):
327 import json
328
329 from tests.test_diagnose_compat import FAKE_KEYLESS_CONFIG, _run_cli
330
331 rc, out = _run_cli(["--diagnose", *argv], {**FAKE_KEYLESS_CONFIG, **(config or {})})
332 assert rc == 0
333 return json.loads(out)["available_sources"]
334
335
336 def test_cli_devto_tags_activate_the_source_through_diagnose():
337 assert "devto" not in _diagnose_sources([])
338 assert "devto" in _diagnose_sources(["--devto-tags", "rust"])
339
340
341 def test_cli_devto_tags_survive_an_explicit_search_list():
342 assert "devto" in _diagnose_sources(["--devto-tags", "rust", "--search", "reddit"])
343
344
345 def test_exclude_sources_beats_devto_tags():
346 assert "devto" not in _diagnose_sources(["--devto-tags", "rust"], {"EXCLUDE_SOURCES": "devto"})
347
348
349 def test_shortener_hidden_in_href_is_dropped(monkeypatch):
350 _install(monkeypatch, FakeApi(comments={"1": [
351 {"body_html": '<p><a href="https://tr.ee/dev-to">Official platform update</a></p>', "user": {"username": "bot"}, "children": []},
352 {"body_html": "<p>Real feedback</p>", "user": {"username": "dev"}, "children": []},
353 ]}))
354 assert [c["text"] for c in devto._fetch_comments("1")] == ["Real feedback"]
355
356
357 def test_concurrent_misses_fetch_a_url_once(monkeypatch):
358 import threading
359 import time
360 from concurrent.futures import ThreadPoolExecutor
361
362 calls = []
363 lock = threading.Lock()
364
365 def slow_request(method, url, headers=None, **kwargs):
366 with lock:
367 calls.append(url)
368 time.sleep(0.05)
369 return [_article(1, "Rust", tags=("rust",))]
370
371 monkeypatch.setattr(devto.http, "request", slow_request)
372 with ThreadPoolExecutor(max_workers=4) as pool:
373 results = list(pool.map(lambda _: devto._get_list("https://dev.to/api/articles?tag=rust"), range(4)))
374 assert len(calls) == 1
375 assert all(r[0]["id"] == 1 for r in results)
376
377
378 def test_doctor_reports_devto_as_opt_in_until_enabled():
379 from lib import doctor
380
381 assert doctor._devto_record({})["status"] == "opt-in"
382 assert doctor._devto_record({"INCLUDE_SOURCES": "devto"})["status"] == "ok"
383
384
385 def _plan(sources):
386 from lib import schema
387
388 return schema.QueryPlan(
389 intent="concept",
390 freshness_mode="balanced_recent",
391 cluster_mode="none",
392 raw_topic="claude code",
393 subqueries=[schema.SubQuery(label="primary", search_query="claude code",
394 ranking_query="q", sources=list(sources), weight=1.0)],
395 source_weights={source: 1.0 for source in sources},
396 )
397
398
399 def test_activated_devto_joins_a_host_plan_that_omits_it():
400 plan = _plan(["hackernews"])
401 pipeline._ensure_opt_in_source_in_plan(plan, ["hackernews", "devto"], "devto")
402 assert "devto" in plan.subqueries[0].sources
403 assert "devto" in plan.source_weights
404
405
406 def test_inactive_devto_is_not_added_to_a_plan():
407 plan = _plan(["hackernews"])
408 pipeline._ensure_opt_in_source_in_plan(plan, ["hackernews"], "devto")
409 assert plan.subqueries[0].sources == ["hackernews"]
410
411
412 def test_doctor_never_live_probes_devto():
413 from lib import doctor
414
415 assert "devto" not in doctor._probeable_sources()
416
417
418 def test_unexpected_response_shape_is_an_error_not_an_empty_result(monkeypatch):
419 calls = []
420
421 def object_response(method, url, headers=None, **kwargs):
422 calls.append(url)
423 return {"error": "changed"}
424
425 monkeypatch.setattr(devto.http, "request", object_response)
426 result = devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"])
427 assert result["articles"] == []
428 assert "unexpected dev.to response shape" in result["error"]
429 devto.search_devto("rust", "2026-09-11", "2026-10-11", tags=["rust"])
430 assert len(calls) == 4
431
432
433 def test_requests_carry_a_total_deadline(monkeypatch):
434 seen = {}
435
436 def capture(method, url, headers=None, **kwargs):
437 seen.update(kwargs)
438 return []
439
440 monkeypatch.setattr(devto.http, "request", capture)
441 devto._get_list("https://dev.to/api/articles?tag=rust")
442 assert seen["owned_get"] is True
443 assert seen["deadline_monotonic"] is not None
444
445
446 def test_enrichment_stops_waiting_at_its_time_limit(monkeypatch):
447 import threading
448 import time
449
450 release = threading.Event()
451
452 def stuck(article_id):
453 release.wait(5)
454 return [{"author": "a", "text": "late", "replies": 0}]
455
456 monkeypatch.setattr(devto, "_fetch_comments", stuck)
457 monkeypatch.setattr(devto, "ENRICH_WAIT_SECONDS", 0.2)
458 items = _source_items([_article(1, "Rust one", comments=3)])
459 started = time.monotonic()
460 devto.enrich_source_items(items)
461 elapsed = time.monotonic() - started
462 release.set()
463 assert elapsed < 2
464 assert not items[0].metadata.get("top_comments")
465
466
467 def test_existing_devto_route_is_left_alone():
468 from lib import schema
469
470 plan = _plan(["hackernews"])
471 plan.subqueries.append(schema.SubQuery(label="focused", search_query="claude code hooks",
472 ranking_query="q", sources=["devto"], weight=1.0))
473 pipeline._ensure_opt_in_source_in_plan(plan, ["hackernews", "devto"], "devto")
474 assert plan.subqueries[0].sources == ["hackernews"]
475 assert plan.subqueries[1].sources == ["devto"]
476
476 lines PYTHON