-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_templates.py
More file actions
1851 lines (1480 loc) · 63.6 KB
/
Copy pathtest_templates.py
File metadata and controls
1851 lines (1480 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for searchfetch templates: JSON validity, URL matching, extraction.
Run with: uv run --extra dev pytest test_templates.py -v
"""
import json
import re
from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
# Helpers: lightweight reimplementations of template-loading internals so we
# can test without spawning a browser or importing the MCP server.
# ---------------------------------------------------------------------------
TEMPLATES_DIR = Path(__file__).resolve().parent / "templates"
def load_all_templates():
"""Load every *.json template from the templates/ directory."""
json_files = sorted(TEMPLATES_DIR.glob("*.json"))
if not json_files:
pytest.fail(f"No template JSON files found in '{TEMPLATES_DIR}'")
templates = []
for filepath in json_files:
data = json.loads(filepath.read_text(encoding="utf-8"))
name = data.get("name")
if not name or not isinstance(name, str):
pytest.fail(f"Template '{filepath}' is missing a valid 'name' field")
templates.append(data)
templates.sort(key=lambda t: t.get("order", 999))
return templates
ALL_TEMPLATES = load_all_templates()
TEMPLATES_BY_NAME = {t["name"]: t for t in ALL_TEMPLATES}
# ---------------------------------------------------------------------------
# 1. JSON validity & required fields
# ---------------------------------------------------------------------------
class TestTemplateJsonValidity:
def test_all_files_are_valid_json(self):
json_files = sorted(TEMPLATES_DIR.glob("*.json"))
assert len(json_files) >= 18 # originals + new templates
for fp in json_files:
data = json.loads(fp.read_text(encoding="utf-8"))
assert isinstance(data, dict), f"{fp.name}: not a JSON object"
def test_every_template_has_name(self):
for t in ALL_TEMPLATES:
assert "name" in t, f"Template {t} missing 'name'"
assert isinstance(t["name"], str) and t["name"], (
f"Template 'name' must be a non-empty string, got {t['name']!r}"
)
def test_every_template_has_order(self):
for t in ALL_TEMPLATES:
assert "order" in t, f"Template '{t['name']}' missing 'order'"
assert isinstance(t["order"], (int, float)), (
f"Template '{t['name']}' order must be a number"
)
def test_no_duplicate_names(self):
names = [t["name"] for t in ALL_TEMPLATES]
assert len(names) == len(set(names)), f"Duplicate template names: {names}"
def test_no_duplicate_orders(self):
orders = [t["order"] for t in ALL_TEMPLATES]
duplicates = [o for o in orders if orders.count(o) > 1]
assert not set(duplicates), (
f"Duplicate order values (templates with same order): {set(duplicates)}"
)
def test_sections_is_list(self):
for t in ALL_TEMPLATES:
if "sections" in t:
assert isinstance(t["sections"], list), (
f"Template '{t['name']}': sections must be a list"
)
# ---------------------------------------------------------------------------
# 2. URL pattern matching
# ---------------------------------------------------------------------------
DOCS_RS_URLS = [
"https://docs.rs/ladon/latest/ladon/",
"https://docs.rs/ladon/latest/ladon/struct.KeyInfo.html",
"https://docs.rs/solana/latest/solana/",
"https://docs.rs/solana/latest/solana/broadcast_stage/index.html",
"https://docs.rs/tokio/latest/tokio/",
"https://docs.rs/serde/latest/serde/enum.Result.html",
"https://docs.rs/syn/2.0.0/syn/struct.ItemFn.html",
"https://docs.rs/clap/latest/clap/",
"https://docs.rs/reqwest/latest/reqwest/",
"https://docs.rs/axum/latest/axum/",
]
DOCKER_HUB_URLS = [
"https://hub.docker.com/_/postgres",
"https://hub.docker.com/_/postgres/",
"https://hub.docker.com/r/nginxinc/nginx-unprivileged",
"https://hub.docker.com/r/nginxinc/nginx-unprivileged/",
"https://hub.docker.com/_/node",
"https://hub.docker.com/r/library/python/",
]
DOCS_PAGE_URLS = [
"https://example.readthedocs.io/en/latest/",
"https://docs.mintlify.com/introduction",
"https://example.mintlify.dev/",
"https://viem.sh/docs/clients/public",
"https://docs.example.com/getting-started",
"https://solana.com/docs/rpc/http/getslot",
"https://docs.python.org/3/library/os.html",
"https://nextjs.org/docs/app/building-your-application/routing",
"https://docs.solidjs.com/concepts/intro-to-reactivity",
"https://htmx.org/docs/",
"https://docs.astro.build/en/guides/deploy/",
"https://go.dev/doc/",
"https://docs.deno.com/runtime/manual/",
"https://svelte.dev/docs/introduction",
"https://tailwindcss.com/docs/installation",
]
DOCS_PAGE_NONMATCH_URLS = [
"https://fastapi.tiangolo.com/tutorial/first-steps/",
"https://react.dev/reference/react/useState",
"https://elixir-lang.org/getting-started/introduction.html",
]
CRATES_IO_URLS = [
"https://crates.io/crates/serde",
"https://crates.io/crates/tokio/1.0.0",
]
NPM_URLS = [
"https://www.npmjs.com/package/react",
"https://npmjs.com/package/lodash",
]
PYPI_URLS = [
"https://pypi.org/project/requests/",
"https://pypi.org/project/django/3.2/",
]
GITHUB_REPO_URLS = [
"https://github.com/maxylev/searchfetch",
"https://github.com/wevm/viem/",
]
GITHUB_ISSUE_URLS = [
"https://github.com/maxylev/searchfetch/issues/1",
"https://github.com/wevm/viem/pull/42",
]
WIKIPEDIA_URLS = [
"https://en.wikipedia.org/wiki/Rust_(programming_language)",
"https://de.wikipedia.org/wiki/Rust_(Programmiersprache)",
"https://fr.wikipedia.org/wiki/Python_(langage)",
"https://ja.wikipedia.org/wiki/Linux",
]
WIKIPEDIA_NONMATCH_URLS = [
"https://en.wikipedia.org/wiki/Special:Search?search=Rust",
"https://en.wikipedia.org/wiki/Wikipedia:About",
"https://en.wikipedia.org/wiki/File:Example.jpg",
"https://en.wikipedia.org/wiki/Category:Programming_languages",
]
REDDIT_URLS = [
"https://www.reddit.com/r/rust/comments/1ujqvqx/rust_1961_is_out/",
"https://old.reddit.com/r/python/comments/abc123/some_post/",
"https://reddit.com/r/programming/comments/xyz789/interesting/",
]
MDN_URLS = [
"https://developer.mozilla.org/en-US/docs/Web/JavaScript",
"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div",
"https://developer.mozilla.org/en-US/docs/Web/CSS/color",
]
GITLAB_URLS = [
"https://gitlab.com/gitlab-org/gitlab",
"https://gitlab.com/gitlab-org/gitlab/",
"https://gitlab.com/gitlab-org/gitaly/-/tree/main/",
]
YOUTUBE_URLS = [
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"https://youtube.com/watch?v=abcdefghijk",
"https://youtu.be/dQw4w9WgXcQ",
]
DEVTO_URLS = [
"https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke",
"https://dev.to/someuser/some-article-123abc",
]
GO_PKG_URLS = [
"https://pkg.go.dev/fmt",
"https://pkg.go.dev/net/http",
"https://pkg.go.dev/encoding/json/",
]
GO_PKG_NONMATCH_URLS = [
"https://pkg.go.dev/", # root — not a package
]
JAVADOC_URLS = [
"https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ArrayList.html",
"https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html",
"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html",
]
class TestUrlPatternMatching:
@pytest.mark.parametrize("url", DOCS_RS_URLS)
def test_docs_rs_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["docs-rs"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match docs-rs patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", DOCKER_HUB_URLS)
def test_docker_hub_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["docker-hub"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match docker-hub patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", DOCS_PAGE_URLS)
def test_docs_page_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["docs-page"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match docs-page patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", DOCS_PAGE_NONMATCH_URLS)
def test_docs_page_does_not_match_non_docs_urls(self, url):
"""These are docs-adjacent URLs but don't use /docs/ path or docs. subdomain.
They correctly fall through to generic fallback."""
t = TEMPLATES_BY_NAME["docs-page"]
assert not any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should NOT match docs-page (no /docs/ or docs. pattern)"
)
@pytest.mark.parametrize("url", CRATES_IO_URLS)
def test_crates_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["crates-package"]
assert any(re.search(pat, url) for pat in t["url_patterns"])
@pytest.mark.parametrize("url", NPM_URLS)
def test_npm_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["npm-package"]
assert any(re.search(pat, url) for pat in t["url_patterns"])
@pytest.mark.parametrize("url", PYPI_URLS)
def test_pypi_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["pypi-package"]
assert any(re.search(pat, url) for pat in t["url_patterns"])
@pytest.mark.parametrize("url", GITHUB_REPO_URLS)
def test_github_repo_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["github-repo"]
assert any(re.search(pat, url) for pat in t["url_patterns"])
@pytest.mark.parametrize("url", GITHUB_ISSUE_URLS)
def test_github_issue_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["github-issue"]
assert any(re.search(pat, url) for pat in t["url_patterns"])
@pytest.mark.parametrize("url", WIKIPEDIA_URLS)
def test_wikipedia_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["wikipedia"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match wikipedia patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", WIKIPEDIA_NONMATCH_URLS)
def test_wikipedia_does_not_match_special_pages(self, url):
t = TEMPLATES_BY_NAME["wikipedia"]
assert not any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should NOT match wikipedia (not an article)"
)
@pytest.mark.parametrize("url", REDDIT_URLS)
def test_reddit_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["reddit"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match reddit patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", MDN_URLS)
def test_mdn_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["mdn-web-docs"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match mdn-web-docs patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", GITLAB_URLS)
def test_gitlab_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["gitlab"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match gitlab patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", YOUTUBE_URLS)
def test_youtube_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["youtube"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match youtube patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", DEVTO_URLS)
def test_devto_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["devto"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match devto patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", GO_PKG_URLS)
def test_go_pkg_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["go-pkg"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match go-pkg patterns: {t['url_patterns']}"
)
@pytest.mark.parametrize("url", GO_PKG_NONMATCH_URLS)
def test_go_pkg_does_not_match_root(self, url):
t = TEMPLATES_BY_NAME["go-pkg"]
assert not any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should NOT match go-pkg (root, not a package)"
)
@pytest.mark.parametrize("url", JAVADOC_URLS)
def test_javadoc_matches_expected_urls(self, url):
t = TEMPLATES_BY_NAME["javadoc"]
assert any(re.search(pat, url) for pat in t["url_patterns"]), (
f"URL '{url}' should match javadoc patterns: {t['url_patterns']}"
)
# ---------------------------------------------------------------------------
# 3. Template ordering (docs-rs before docs-page, etc.)
# ---------------------------------------------------------------------------
class TestTemplateOrdering:
def test_github_before_others(self):
"""GitHub templates should have lowest orders (matched first)."""
gh_repo = TEMPLATES_BY_NAME["github-repo"]
gh_issue = TEMPLATES_BY_NAME["github-issue"]
for name, t in TEMPLATES_BY_NAME.items():
if name in ("github-repo", "github-issue"):
continue
if "url_patterns" not in t:
continue
assert gh_repo["order"] < t["order"], (
f"github-repo (order={gh_repo['order']}) should precede "
f"'{name}' (order={t['order']})"
)
assert gh_issue["order"] < t["order"], (
f"github-issue (order={gh_issue['order']}) should precede "
f"'{name}' (order={t['order']})"
)
def test_crates_before_docs_rs(self):
"""crates.io is a specific site, docs.rs is broader — match crates first."""
crates = TEMPLATES_BY_NAME["crates-package"]
docs_rs = TEMPLATES_BY_NAME["docs-rs"]
assert crates["order"] < docs_rs["order"], (
f"crates-package ({crates['order']}) should be before docs-rs ({docs_rs['order']})"
)
def test_docs_rs_before_docs_page(self):
"""docs.rs is more specific than the generic docs-page template."""
docs_rs = TEMPLATES_BY_NAME["docs-rs"]
docs_page = TEMPLATES_BY_NAME["docs-page"]
assert docs_rs["order"] < docs_page["order"], (
f"docs-rs ({docs_rs['order']}) should be before docs-page ({docs_page['order']})"
)
def test_package_templates_before_search(self):
"""Package templates (npm, pypi, crates) should be before search templates."""
search_orders = [
TEMPLATES_BY_NAME["duckduckgo-search"]["order"],
TEMPLATES_BY_NAME["google-search"]["order"],
]
for name in ("npm-package", "pypi-package", "crates-package"):
pkg_order = TEMPLATES_BY_NAME[name]["order"]
for so in search_orders:
assert pkg_order < so, (
f"{name} ({pkg_order}) should be before search templates ({so})"
)
def test_auto_detection_order_is_stable(self):
"""Sorted templates should be in ascending order."""
for i in range(len(ALL_TEMPLATES) - 1):
assert ALL_TEMPLATES[i]["order"] <= ALL_TEMPLATES[i + 1]["order"], (
f"Templates not sorted: '{ALL_TEMPLATES[i]['name']}' "
f"(order={ALL_TEMPLATES[i]['order']}) vs "
f"'{ALL_TEMPLATES[i + 1]['name']}' "
f"(order={ALL_TEMPLATES[i + 1]['order']})"
)
def test_docs_rs_not_matched_by_docs_page(self):
"""A docs.rs URL should match docs-rs first, not docs-page (ensuring ordering works)."""
url = "https://docs.rs/solana/latest/solana/"
matched = None
for t in ALL_TEMPLATES:
if "url_patterns" not in t:
continue
for pat in t["url_patterns"]:
if re.search(pat, url):
matched = t["name"]
break
if matched:
break
assert matched == "docs-rs", f"Expected docs-rs to match first for '{url}', got '{matched}'"
def test_wikipedia_before_mdn(self):
"""Wikipedia is more specific (domain-based) than MDN."""
wiki = TEMPLATES_BY_NAME["wikipedia"]
mdn = TEMPLATES_BY_NAME["mdn-web-docs"]
assert wiki["order"] < mdn["order"], (
f"wikipedia ({wiki['order']}) should be before mdn-web-docs ({mdn['order']})"
)
def test_gitlab_after_github(self):
"""GitLab template should come after GitHub (lower priority)."""
gh_issue = TEMPLATES_BY_NAME["github-issue"]
gitlab = TEMPLATES_BY_NAME["gitlab"]
assert gh_issue["order"] < gitlab["order"], (
f"github-issue ({gh_issue['order']}) should be before gitlab ({gitlab['order']})"
)
def test_specific_templates_before_docs_page(self):
"""Specific templates that overlap with docs-page should precede it."""
docs_page_order = TEMPLATES_BY_NAME["docs-page"]["order"]
for name in ("docs-rs", "javadoc"):
t = TEMPLATES_BY_NAME[name]
assert t["order"] < docs_page_order, (
f"{name} ({t['order']}) should be before docs-page ({docs_page_order})"
)
def test_new_content_templates_not_overlap_search_patterns(self):
"""Content templates' URL patterns must not accidentally match search engine URLs."""
content_templates = [
"wikipedia",
"reddit",
"mdn-web-docs",
"gitlab",
"devto",
"go-pkg",
"javadoc",
"youtube",
]
for name in content_templates:
t = TEMPLATES_BY_NAME[name]
for ct_pat in t.get("url_patterns", []):
# A content template pattern should NOT match search engine URLs
assert not re.search(ct_pat, "https://www.google.com/search?q=test"), (
f"{name} pattern '{ct_pat}' incorrectly matches Google search URL"
)
assert not re.search(ct_pat, "https://duckduckgo.com/?q=test"), (
f"{name} pattern '{ct_pat}' incorrectly matches DuckDuckGo search URL"
)
def test_wikipedia_not_matched_by_docs_page(self):
"""Wikipedia URL should match wikipedia first, not docs-page."""
url = "https://en.wikipedia.org/wiki/Python_(programming_language)"
matched = None
for t in ALL_TEMPLATES:
if "url_patterns" not in t:
continue
for pat in t["url_patterns"]:
if re.search(pat, url):
matched = t["name"]
break
if matched:
break
assert matched == "wikipedia", (
f"Expected wikipedia to match first for '{url}', got '{matched}'"
)
def test_go_pkg_not_matched_by_docs_page(self):
"""pkg.go.dev should match go-pkg first, not docs-page."""
url = "https://pkg.go.dev/fmt"
matched = None
for t in ALL_TEMPLATES:
if "url_patterns" not in t:
continue
for pat in t["url_patterns"]:
if re.search(pat, url):
matched = t["name"]
break
if matched:
break
assert matched == "go-pkg", f"Expected go-pkg to match first for '{url}', got '{matched}'"
def test_javadoc_not_matched_by_docs_page(self):
"""javadoc URL should match javadoc first, not docs-page."""
url = (
"https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ArrayList.html"
)
matched = None
for t in ALL_TEMPLATES:
if "url_patterns" not in t:
continue
for pat in t["url_patterns"]:
if re.search(pat, url):
matched = t["name"]
break
if matched:
break
assert matched == "javadoc", f"Expected javadoc to match first for '{url}', got '{matched}'"
# ---------------------------------------------------------------------------
# 4. Section structure validation
# ---------------------------------------------------------------------------
class TestSectionStructure:
def test_docs_rs_sections(self):
t = TEMPLATES_BY_NAME["docs-rs"]
section_names = {s["name"] for s in t["sections"]}
assert "Crate" in section_names
assert "Title" in section_names
assert "Content" in section_names
content_section = next(s for s in t["sections"] if s["name"] == "Content")
assert content_section["format"] == "markdown"
def test_docker_hub_sections(self):
t = TEMPLATES_BY_NAME["docker-hub"]
section_names = {s["name"] for s in t["sections"]}
assert "Image" in section_names
assert "Description" in section_names
assert "Content" in section_names
desc_section = next(s for s in t["sections"] if s["name"] == "Description")
assert desc_section["format"] == "attribute"
assert desc_section["attribute"] == "content"
def test_docs_page_has_source_url(self):
t = TEMPLATES_BY_NAME["docs-page"]
assert "source_url" in t
assert "{url}" in t["source_url"]
@pytest.mark.parametrize("name", ["docs-rs", "docker-hub", "docs-page"])
def test_template_has_remove_selectors(self, name):
t = TEMPLATES_BY_NAME[name]
assert "remove" in t
assert isinstance(t["remove"], list)
assert len(t["remove"]) > 0
def test_docs_rs_remove_excludes_sidebar_nav(self):
t = TEMPLATES_BY_NAME["docs-rs"]
remove = t["remove"]
assert "nav.sidebar" in remove or "nav" in remove
assert "footer" in remove
# --- New template section structure tests ---
def test_wikipedia_sections(self):
t = TEMPLATES_BY_NAME["wikipedia"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Content" in section_names
title_section = next(s for s in t["sections"] if s["name"] == "Title")
assert title_section["required"] is True
content_section = next(s for s in t["sections"] if s["name"] == "Content")
assert content_section["format"] == "markdown"
assert content_section["required"] is True
def test_reddit_sections(self):
t = TEMPLATES_BY_NAME["reddit"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Author" in section_names
assert "Content" in section_names
assert "Link" in section_names
assert "Subreddit" in section_names
title_section = next(s for s in t["sections"] if s["name"] == "Title")
assert title_section["required"] is True
link_section = next(s for s in t["sections"] if s["name"] == "Link")
assert link_section["format"] == "attribute"
assert link_section["attribute"] == "href"
def test_mdn_sections(self):
t = TEMPLATES_BY_NAME["mdn-web-docs"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Content" in section_names
content_section = next(s for s in t["sections"] if s["name"] == "Content")
assert content_section["format"] == "markdown"
def test_gitlab_sections(self):
t = TEMPLATES_BY_NAME["gitlab"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Description" in section_names
assert "README" in section_names
desc_section = next(s for s in t["sections"] if s["name"] == "Description")
assert desc_section["format"] == "attribute"
assert desc_section["attribute"] == "content"
def test_youtube_sections(self):
t = TEMPLATES_BY_NAME["youtube"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Channel" in section_names
assert "Description" in section_names
title_section = next(s for s in t["sections"] if s["name"] == "Title")
assert title_section["format"] == "attribute"
assert title_section["attribute"] == "content"
assert title_section["required"] is True
def test_devto_sections(self):
t = TEMPLATES_BY_NAME["devto"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Author" in section_names
assert "Content" in section_names
content_section = next(s for s in t["sections"] if s["name"] == "Content")
assert content_section["format"] == "markdown"
assert content_section["required"] is True
def test_go_pkg_sections(self):
t = TEMPLATES_BY_NAME["go-pkg"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Overview" in section_names
assert "Documentation" in section_names
def test_javadoc_sections(self):
t = TEMPLATES_BY_NAME["javadoc"]
section_names = {s["name"] for s in t["sections"]}
assert "Title" in section_names
assert "Content" in section_names
content_section = next(s for s in t["sections"] if s["name"] == "Content")
assert content_section["format"] == "markdown"
@pytest.mark.parametrize(
"name",
[
"wikipedia",
"reddit",
"mdn-web-docs",
"gitlab",
"youtube",
"devto",
"go-pkg",
"javadoc",
],
)
def test_new_template_has_remove_selectors(self, name):
t = TEMPLATES_BY_NAME[name]
assert "remove" in t
assert isinstance(t["remove"], list)
assert len(t["remove"]) > 0
def test_wikipedia_header_not_removed(self):
"""Wikipedia h1 is inside <header> in Vector 2022 skin — ensure it's preserved."""
t = TEMPLATES_BY_NAME["wikipedia"]
assert "header" not in t["remove"], (
"Wikipedia template must NOT remove <header> (h1 lives inside it)"
)
def test_devto_header_not_removed(self):
"""Dev.to article h1 may be inside a <header> element."""
t = TEMPLATES_BY_NAME["devto"]
assert "header" not in t["remove"], (
"devto template must NOT remove <header> (h1 may live inside it)"
)
def test_raw_template_has_empty_remove(self):
"""Raw template must have empty remove list (not null, to avoid default removes)."""
t = TEMPLATES_BY_NAME["raw"]
assert "remove" in t
assert t["remove"] == [], "raw template must have empty remove list to avoid any filtering"
def test_raw_template_has_body_section(self):
"""Raw template extracts the full body as markdown."""
t = TEMPLATES_BY_NAME["raw"]
section_names = {s["name"] for s in t["sections"]}
assert "Content" in section_names
content = next(s for s in t["sections"] if s["name"] == "Content")
assert content["selector"] == "body"
assert content["format"] == "markdown"
assert content["required"] is False # graceful on empty pages
def test_raw_template_high_order(self):
"""Raw template should have highest order (only used by explicit name)."""
t = TEMPLATES_BY_NAME["raw"]
assert t["order"] > 100, (
"raw template should have high order (>= 100) to not interfere with auto-detection"
)
# ---------------------------------------------------------------------------
# 5. Source URL resolution
# ---------------------------------------------------------------------------
class TestSourceUrlResolution:
@staticmethod
def resolve_source_url(source_template: str, url: str) -> str:
if source_template == "{url}.md":
return f"{url.rstrip('/')}.md"
return source_template.replace("{url}", url)
def test_docs_page_source_url_format(self):
t = TEMPLATES_BY_NAME["docs-page"]
url = "https://solana.com/docs/rpc/http/getslot"
source = self.resolve_source_url(t["source_url"], url)
assert source == "https://solana.com/docs/rpc/http/getslot.md"
def test_source_url_resolution_with_trailing_slash(self):
t = TEMPLATES_BY_NAME["docs-page"]
url = "https://example.com/docs/api/"
source = self.resolve_source_url(t["source_url"], url)
assert source == "https://example.com/docs/api.md"
def test_no_source_url_for_docs_rs(self):
t = TEMPLATES_BY_NAME["docs-rs"]
assert "source_url" not in t, "docs.rs does not have raw markdown endpoints"
def test_no_source_url_for_docker_hub(self):
t = TEMPLATES_BY_NAME["docker-hub"]
assert "source_url" not in t, "Docker Hub does not have raw markdown endpoints"
# ---------------------------------------------------------------------------
# 6. Markdown content detection (unit tests for _is_markdown_content)
# ---------------------------------------------------------------------------
# Minimal standalone reimplementation of _is_markdown_content for testing
def _is_markdown_content(text: str) -> bool:
if not text:
return False
html_tags = len(re.findall(r"<\w+[^>]*>", text))
if html_tags > 3:
return False
patterns = [
r"^#{1,6}\s+\S",
r"\[.+?\]\(.+?\)",
r"```\w*\n",
r"^\s*[-*+]\s+\S",
r"\*\*[^*]+\*\*",
r"^>\s+\S",
]
for pat in patterns:
if re.search(pat, text, re.MULTILINE):
return True
return False
def _strip_source_markdown(content: str) -> str:
content = re.sub(r"^@twoslash-cache:.*$", "", content, flags=re.MULTILINE)
content = re.sub(r"\n{3,}", "\n\n", content)
return content.strip()
class TestMarkdownDetection:
def test_detects_heading(self):
assert _is_markdown_content("# Hello World")
def test_detects_link(self):
assert _is_markdown_content("See [docs](https://example.com) for more.")
def test_detects_code_fence(self):
assert _is_markdown_content("```python\nprint('hello')\n```")
def test_detects_unordered_list(self):
assert _is_markdown_content("- item 1\n- item 2")
def test_rejects_html(self):
assert not _is_markdown_content("<html><body><h1>Hello</h1></body></html>")
def test_rejects_empty_string(self):
assert not _is_markdown_content("")
def test_rejects_plain_text(self):
assert not _is_markdown_content("Just some plain text without any markdown syntax.")
def test_detects_bold(self):
assert _is_markdown_content("This is **bold** text.")
def test_detects_blockquote(self):
assert _is_markdown_content("> This is a quote")
def test_accepts_mixed_markdown(self):
text = "# Hello\n\nThis is **bold** and [a link](https://example.com)."
assert _is_markdown_content(text)
class TestTwoslashStripping:
def test_strips_twoslash_cache_lines(self):
content = (
"# Title\n\nSome text\n@twoslash-cache: abcdef1234567890abcdef1234567890\nMore text"
)
result = _strip_source_markdown(content)
assert "@twoslash-cache:" not in result
assert "# Title" in result
assert "More text" in result
def test_strips_multiple_twoslash_lines(self):
content = (
"# Title\n"
"@twoslash-cache: hash1\n"
"content\n"
"@twoslash-cache: hash2\n"
"@twoslash-cache: hash3\n"
"footer\n"
)
result = _strip_source_markdown(content)
assert "@twoslash-cache:" not in result
assert "# Title\n\ncontent\n\nfooter" == result
def test_no_twoslash_unchanged(self):
content = "# Title\n\nNormal content here."
result = _strip_source_markdown(content)
assert result == content
def test_collapses_excess_blank_lines(self):
content = "# Title\n\n\n\n\n\nContent\n\n\n\n\n\nFooter"
result = _strip_source_markdown(content)
assert "\n\n\n\n" not in result
assert result == "# Title\n\nContent\n\nFooter"
# ---------------------------------------------------------------------------
# 7. Extraction from sample HTML (using BeautifulSoup, no browser)
# ---------------------------------------------------------------------------
def _has_bs4():
try:
import bs4 # noqa: F401
return True
except ImportError:
return False
class TestHtmlExtraction:
"""Test template extraction against static HTML snippets."""
DOCS_RS_STRUCT_HTML = """<!DOCTYPE html>
<html>
<head><title>KeyInfo in ladon - Rust</title></head>
<body>
<nav class="sidebar">
<div class="sidebar-crate"><h2>ladon</h2></div>
<ul class="sidebar-items"><li><a href="#">Modules</a></li></ul>
</nav>
<nav class="sub"><a href="#">Platform</a></nav>
<div id="main-content">
<h1 class="fqn">
<span class="in-band">Struct ladon::KeyInfo</span>
</h1>
<div class="docblock">
<p>A single derived key / address tuple.</p>
</div>
<h2 id="fields">Fields</h2>
<span>index: u32</span>
<span>path: String</span>
<span>private_key: String</span>
<span>public_key: String</span>
<span>address: String</span>
</div>
<footer>docs.rs footer</footer>
</body>
</html>"""
DOCS_RS_CRATE_HTML = """<!DOCTYPE html>
<html>
<head><title>solana - Rust</title></head>
<body>
<nav class="sidebar"><!-- sidebar content --></nav>
<div id="main-content">
<h1 class="crate-title">Crate solana</h1>
<div class="docblock"><p>Blockchain, Rebuilt for Scale</p></div>
<h2>Modules</h2>
<ul><li>broadcast_stage</li><li>cluster_info</li></ul>
</div>
<footer>footer</footer>
</body>
</html>"""
DOCKER_HUB_HTML = """<!DOCTYPE html>
<html>
<head>
<title>postgres - Docker Hub</title>
<meta name="description"
content="PostgreSQL object-relational database with reliability and data integrity.">
</head>
<body>
<header><!-- nav --></header>
<main>
<h1>postgres Docker official image overview</h1>
<article>
<h3>Quick reference</h3>
<p>Maintained by the PostgreSQL Docker Community.</p>
<h3>Supported tags</h3>
<ul><li>18.4, 18, latest</li><li>17.10, 17</li></ul>
<h2>How to use this image</h2>
<pre><code>docker run postgres</code></pre>
</article>
</main>
<footer>footer</footer>
</body>
</html>"""
def _apply_remove(self, soup, template):
for sel in template.get("remove", []):
try:
for tag in soup.select(sel):
if hasattr(tag, "decompose"):
tag.decompose()
except Exception:
pass
def test_docs_rs_struct_extraction(self):
from bs4 import BeautifulSoup
soup = BeautifulSoup(self.DOCS_RS_STRUCT_HTML, "html.parser")
t = TEMPLATES_BY_NAME["docs-rs"]
self._apply_remove(soup, t)
h1 = soup.select_one("h1.fqn, .in-band h1")
assert h1 is not None
assert "KeyInfo" in h1.get_text()
main = soup.select_one("#main-content")
assert main is not None
assert "key / address" in main.get_text()
footer = soup.select_one("footer")
assert footer is None or footer.decomposed
def test_docs_rs_crate_extraction(self):
from bs4 import BeautifulSoup
soup = BeautifulSoup(self.DOCS_RS_CRATE_HTML, "html.parser")
t = TEMPLATES_BY_NAME["docs-rs"]
self._apply_remove(soup, t)
h1 = soup.select_one("h1.crate-title")
assert h1 is not None
assert "solana" in h1.get_text()
main = soup.select_one("#main-content")
assert main is not None
sidebar = soup.select_one("nav.sidebar")
assert sidebar is None or sidebar.decomposed
def test_docker_hub_extraction(self):
from bs4 import BeautifulSoup
soup = BeautifulSoup(self.DOCKER_HUB_HTML, "html.parser")
t = TEMPLATES_BY_NAME["docker-hub"]
self._apply_remove(soup, t)
h1 = soup.select_one("h1")
assert h1 is not None
assert "postgres" in h1.get_text()