diff --git a/AGENTS.md b/AGENTS.md index 7ca7c464c0b..ba8b6075829 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ Much of the site is generated from Google Sheets and Docs, and the generated fil Run both against a build (`hugo -d `), as `deploy.yaml` does: -- `python3 scripts/check_seo_html.py `. Add a regression check here when you fix a template. +- `python3 scripts/check_seo_html.py `. When you fix a template, add a regression check as a new module in `scripts/seo_checks/` (a docstring and `check(site)`), with tests in `scripts/tests/test_seo_.py`; the runner finds it, so no shared file changes. - `python3 scripts/check_sitemap_lastmod.py /sitemap.xml [--compare-source]` (needs full Git history). Unit tests: `python3 -m unittest discover -s scripts/tests` and `python3 -m unittest discover -s scripts -p 'test_parse_disciplines_gdoc.py'`; `script-tests.yaml` runs both on every PR. diff --git a/content/resources/resource.py b/content/resources/resource.py index eceb15fa07e..dddd167f0ce 100644 --- a/content/resources/resource.py +++ b/content/resources/resource.py @@ -103,7 +103,7 @@ def wrangle_data(df): # Titles and abstracts pasted from publisher pages can carry HTML entities such as # "“". Hugo escapes the "&" again, so pages showed "“" as text and the -# meta description failed check 10 of scripts/check_seo_html.py. Only complete +# meta description failed scripts/seo_checks/description_entities.py. Only complete # entities ending in ";" are decoded, so a bare "&" stays as it is, and a name is # decoded only if the whole name is an HTML entity. "<" and ">" stay encoded: # abstracts are rendered as Markdown with raw HTML allowed, so decoding them diff --git a/layouts/sitemap.xml b/layouts/sitemap.xml index 4f851301afd..ac7c9eb6ee5 100644 --- a/layouts/sitemap.xml +++ b/layouts/sitemap.xml @@ -1,8 +1,8 @@ {{/* Override of Hugo's built-in sitemap template, kept deliberately close to it so it stays easy to diff against upstream. It leaves out author profiles that custom_head.html marks noindex (same condition there), so the sitemap never - lists a page it asks search engines not to index (check 14 in - scripts/check_seo_html.py). It also appends data/external_sitemap.yaml. */ -}} + lists a page it asks search engines not to index + (scripts/seo_checks/sitemap_noindex.py). It also appends data/external_sitemap.yaml. */ -}} {{ printf "" | safeHTML }} {{- range .Pages }} diff --git a/scripts/check_seo_html.py b/scripts/check_seo_html.py index 6618207605e..fe7868099d7 100644 --- a/scripts/check_seo_html.py +++ b/scripts/check_seo_html.py @@ -3,912 +3,67 @@ Run: python3 scripts/check_seo_html.py public -Hard checks (exit 1 if any fails): - 1. No page carries an

whose text is exactly "Search". - 2. The homepage loads no Mermaid or highlight.js script or stylesheet. - 3. highlight.min.js is loaded exactly on pages with a
 block in
-     their content (the cite modal's  on every page does
-     not count; language-mermaid blocks belong to Mermaid), and mermaid.min.js
-     exactly on pages with a language-mermaid block.
-  4. Every  carries an alt attribute (a bare `alt` counts as present).
-  5. Every homepage  carries both width and height, so the browser reserves
-     its box before the file loads (#869).
-  6. The homepage share image (og:image, twitter:image) is a 1200x630 PNG or
-     JPEG (per og:image:width/height), and twitter:card is summary_large_image.
-     X and LinkedIn show no preview for WebP (#870).
-  8. Every curated-resource page carries exactly one LearningResource JSON-LD
-     block that parses, has a name and url, and holds no empty or placeholder
-     values (#863). Every JSON-LD block on those pages must parse.
-  7. Breadcrumb JSON-LD (#867): at most one BreadcrumbList per page; every
-     itemListElement is a non-empty list of objects; every ListItem has a
-     non-empty item URL; positions run 1..n; the page has a canonical link and
-     the last item is that URL; no name repeats, except that the current page
-     may share the root's name (an author or glossary term called "FORRT").
-  9. Every indexable page (no robots noindex, not a meta-refresh redirect) has a
-     non-empty meta description (#864).
-  10. No meta description contains a double-escaped entity such as `&ldquo;`
-     (#864). Text that merely looks like an entity (`&name;`) is not one.
-  11. No page has more than one 

(#928). - 12. Numbered resource subsets have unique, self-canonical metadata and - CollectionPage data matching their HTML cards (#868). - 13. PNG/JPEG social images have matching Open Graph/Twitter URLs, type and - positive dimensions (#927). Unsupported formats remain report-only. - 14. No page inlines more than 200 KB in one ' - '

Resource

') % (name, url, url, name, number, json.dumps(data), resource) - pages.append(page_from_html(text, relative + "index.html")) - return pages - - def test_self_canonical_numbered_subsets_pass_with_preview_prefix(self): - for prefix in ("", "/rebrand-doors"): - with self.subTest(prefix=prefix): - self.assertEqual(seo.check_resource_pagination(self.pages(prefix)), []) - - def test_staging_noindex_applies_to_directory_and_subsets(self): - pages = self.pages("/rebrand-doors") - for page in pages: - page.noindex = True - self.assertEqual(seo.check_resource_pagination(pages), []) - - def test_repeated_first_page_metadata_fails(self): - pages = self.pages() - pages[1].canonical = pages[0].canonical - pages[1].title = pages[0].title - pages[1].descriptions = pages[0].descriptions - failures = seo.check_resource_pagination(pages) - self.assertEqual(len(failures), 1) - for text in ("not self-canonical", "repeated title", "repeated description", "omits page number"): - self.assertIn(text, failures[0]) - - def test_wrong_structured_subset_fails(self): - pages = self.pages() - pages[1].resource_links = pages[0].resource_links - self.assertIn("subset does not match HTML cards", seo.check_resource_pagination(pages)[0]) - - def test_query_canonical_is_never_used_for_subsets(self): - pages = self.pages() - pages[1].canonical += "?type=reading" - self.assertIn("not self-canonical", seo.check_resource_pagination(pages)[0]) - - -class InlineScriptCheck(unittest.TestCase): - def failures(self, body): - with tempfile.TemporaryDirectory() as public: - (Path(public) / "index.html").write_text("%s" % body, encoding="utf-8") - return seo.check_inline_scripts(seo.load_pages(public)) - - def test_small_inline_and_external_scripts_pass(self): - self.assertEqual(self.failures(""), []) - - def test_inline_data_over_the_limit_fails(self): - data = "x" * (seo.MAX_INLINE_SCRIPT + 1) - self.assertEqual(self.failures("" % data), ["index.html (200 KB)"]) - - def test_unclosed_inline_data_fails(self): - data = "x" * (seo.MAX_INLINE_SCRIPT + 1) - self.assertEqual(self.failures("'): - with self.subTest(html=html): - self.assertEqual(self.check(html), ["summaries/open-reproducible/index.html: raw summary author marker"]) - - def test_missing_page_fails(self): - self.assertEqual(self.check("", missing="diversity-equity-inclusion"), - ["summaries/diversity-equity-inclusion/index.html: missing page"]) - - def test_no_credit_needed_for_data_without_author_markers(self): - self.assertEqual(self.check("

Paper ◈ ⌺

", summaries={"summary_1": {"Title": "Paper ◈ ⌺"}}), []) - self.assertTrue(self.check(self.credit)) - - def test_requires_credits_matching_each_collections_data(self): - self.assertEqual(self.check(self.credit * 2, dei_html=self.credit, summaries=self.marked), []) - failures = self.check(self.credit, dei_html=self.credit.replace("Tamara", "Other"), summaries=self.marked) - self.assertEqual(failures, [ - "summaries/open-reproducible/index.html: expected 2 written credits, found 1 matching out of 1 credit lines", - "summaries/diversity-equity-inclusion/index.html: expected 1 written credits, found 0 matching out of 1 credit lines", - ]) - - def test_minified_credit_followed_by_heading(self): - html = self.credit.replace('class="summary-credit"', 'class=summary-credit').removesuffix("

") - self.assertEqual(self.check(html + "

Main takeaways

", summaries={"summary_1": {"Title": "Paper ⬦"}}), []) - - -class CitationTargetCheck(unittest.TestCase): - def check(self, html): - parser = seo.PageParser() - parser.feed(html) - return seo.check_citation_targets([seo.Page("example/index.html", parser)]) - - def test_reference_after_citation(self): - self.assertEqual(self.check('Author, 2020' - '
  • Reference
  • '), []) - - def test_missing_data_reference_or_mismatched_key_fails(self): - self.assertTrue(self.check('Author, 2020' - '
  • Reference
  • ')) - self.assertTrue(self.check('Author, 2020' - '
  • Reference
  • ')) - - def test_missing_reference_or_nonlocal_link(self): - for href in ('#ref-Unknown', '/other/#ref-Key', '#Key', ''): - with self.subTest(href): - self.assertTrue(self.check('Citation' - '
  • Reference
  • ' % href)) - - def test_other_links_are_ignored(self): - self.assertEqual(self.check('Link'), []) - - def test_truncated_parenthetical_doi_in_data_source_fails(self): - self.assertEqual(self.check('
  • Ref DOI
  • '), []) - self.assertTrue(self.check('
  • Ref
  • ')) - self.assertTrue(self.check('
  • Ref DOI
  • ')) - self.assertTrue(self.check('
  • Ref https://doi.org/10.1002/(SICI)1099
  • ')) - - -class GlossaryTitleMarkdownCheck(unittest.TestCase): - def check(self, title, h1, path="glossary/english/term/index.html"): - html = "%s

    %s

    " % (title, h1) - return seo.check_glossary_title_markdown([page_from_html(html, path)]) - - def test_rendered_emphasis_and_lone_asterisk_pass(self): - self.assertEqual(self.check("Research Contribution Metric (p) | FORRT", - "Research Contribution Metric (p)"), []) - self.assertEqual(self.check("G*Power | FORRT", "G*Power"), []) - self.assertEqual(self.check("G*Power and P*Hack | FORRT", "G*Power and P*Hack"), []) - - def test_literal_emphasis_fails_on_glossary_pages_only(self): - self.assertEqual(len(self.check("Research Contribution Metric (*p*) | FORRT", "x")), 1) - self.assertEqual(len(self.check("x", "Research Contribution Metric (*p*)")), 1) - self.assertEqual(len(self.check("x", "*p*-value")), 1) - self.assertEqual(self.check("x", "*p*", path="post/x/index.html"), []) - - -class GlossaryLinkCheck(unittest.TestCase): - def check_links(self, hrefs, base="https://forrt.org/"): - with tempfile.TemporaryDirectory() as public: - root = Path(public) - term = root / "glossary/english/preregistration/index.html" - term.parent.mkdir(parents=True) - term.write_text('' % base) - links = "".join('term' % href for href in hrefs) - (root / "index.html").write_text('%s' % (base, links)) - return seo.check_glossary_links(seo.load_pages(public)) - - def test_existing_term_and_preview_base_pass(self): - for base in ("https://forrt.org/", "https://forrt.org/rebrand-doors/"): - with self.subTest(base=base): - self.assertEqual(self.check_links([ - base + "glossary/english/preregistration/", - "glossary/english/preregistration/#definition", - ], base), []) - - def test_missing_non_english_external_and_empty_links_fail(self): - links = ["/glossary/english/missing/", "/glossary/german/preregistration/", - "https://example.org/glossary/english/preregistration/", ""] - self.assertEqual(len(self.check_links(links)), len(links)) - - -class BreadcrumbLinks(unittest.TestCase): - def test_crumb_links_need_a_target(self): - good = page_from_html('') - bad = page_from_html('x') - self.assertEqual(good.crumb_links, ["/", "/about/"]) - self.assertEqual(bad.crumb_links, ["/", ""]) - - -class ClusterTitleMarkupCheck(unittest.TestCase): - def check(self, body): - with tempfile.TemporaryDirectory() as public: - page = Path(public) / "clusters" / "cluster-1" / "index.html" - page.parent.mkdir(parents=True) - page.write_text("
    %s
    " % body, encoding="utf-8") - return seo.check_cluster_title_markup(public) - - def test_rendered_markup_passes(self): - self.assertEqual(self.check("In Africa at Cognition (p < .05)"), []) - - def test_literal_or_unrendered_markup_fails(self): - for body in ("at <i>Cognition</i>", "in Africa", "<em>AIMS</em>", - "at &lt;i&gt;Cognition&lt;/i&gt;"): - self.assertEqual(self.check(body), ["clusters/cluster-1/index.html"], body) - - def test_missing_cluster_pages_fail(self): - with tempfile.TemporaryDirectory() as public: - self.assertEqual(seo.check_cluster_title_markup(public), ["clusters/ (no cluster pages found)"]) - - -def clusters_map_failures(page): - with tempfile.TemporaryDirectory() as public: - (Path(public) / "clusters").mkdir() - (Path(public) / "clusters" / "index.html").write_text(page, encoding="utf-8") - return seo.check_clusters_map(public) - - -class ClustersMapCheck(unittest.TestCase): - MAP = ('
    ' - '
    1. One
    ' - '
    not in the map') - - def test_named_counted_names_hidden_drawing_closed_panels_and_targets_pass(self): - self.assertEqual(clusters_map_failures(self.MAP), []) - - def test_each_fault_fails_once(self): - for change in (('class="clusters-map__ring" aria-hidden="true">', 'class="clusters-map__ring">'), - ('aria-hidden="true">', 'aria-hidden="true">'), - ('id="c1-a"', 'id="c1-b"'), (" inert>", ">"), - ('clusters-map__tag" href="/clusters/cluster-1/"', 'clusters-map__tag" href=""'), - ('class="clusters-map__tag"', 'class="other"'), ('One', ''), - ('class="clusters-map__tag" href', 'class="clusters-map__tag" aria-hidden="true" href'), - ('
  • One
  • ', '
  • One
  • Two
  • ')): - with self.subTest(change): - self.assertEqual(len(clusters_map_failures(self.MAP.replace(*change))), 1) - - def test_page_without_the_drawing_fails(self): - self.assertTrue(clusters_map_failures("

    No map

    ")) - - -def flora_failures(html): - """Check 22 on a FLoRA page with this HTML (None: no page).""" - with tempfile.TemporaryDirectory() as public: - if html is not None: - page = Path(public) / seo.FLORA_PAGE - page.parent.mkdir(parents=True) - page.write_text(html, encoding="utf-8") - return seo.check_flora_citation(public) - - -class FloraCitationCheck(unittest.TestCase): - TITLE = "Azevedo, F. (2026). FORRT Library of Reproduction and Replication Attempts (FLoRA) [Data set]. " - OSF = 'OSF. https://doi.org/10.17605/OSF.IO/9R62X' - ZENODO = 'Zenodo. https://doi.org/10.5281/zenodo.24461022' - - def test_citation_passes_whichever_doi_it_links(self): - for doi in (self.OSF, self.ZENODO): - with self.subTest(doi): - self.assertEqual(flora_failures("

    Wallrich, L.*, ... %s%s

    " % (self.TITLE, doi)), []) - - def test_missing_citation_or_page_fails(self): - self.assertIn("DOI", flora_failures("

    How to cite:

    ")[0]) - self.assertIn("DOI", flora_failures("

    %sOSF.

    other

    " % self.TITLE.replace("(FLoRA)", "(FLoRA)" + " x" * 200))[0]) - self.assertIn("DOI", flora_failures("

    See https://doi.org/10.5281/zenodo.24461022

    ")[0]) - self.assertIn("not found", flora_failures(None)[0]) - - -def related_language_failures(target_alternates, prefix=""): - """Check 23: a Turkish page links its related term to the English Paywall page.""" - with tempfile.TemporaryDirectory() as public: - english = Path(public) / "glossary/english/paywall" - turkish = Path(public) / "glossary/turkish/abstract" - english.mkdir(parents=True) - turkish.mkdir(parents=True) - links = "".join("" % h for h in target_alternates) - (english / "index.html").write_text("%s" % links, encoding="utf-8") - (turkish / "index.html").write_text( - "" - "

    elsewhere

    " % prefix, encoding="utf-8") - return seo.check_glossary_related_language(seo.load_pages(public)) - - -class GlossaryRelatedLanguageCheck(unittest.TestCase): - def test_preview_prefix_is_ignored(self): - failures = related_language_failures(["https://forrt.org/rebrand-doors/glossary/turkish/odeme_duvar%C4%B1_paywall_/"], - prefix="/rebrand-doors") - self.assertEqual(len(failures), 1) - - def test_link_to_english_when_no_translation_exists_passes(self): - self.assertEqual(related_language_failures(["https://forrt.org/glossary/german/bezahlschranke/"]), []) - - def test_link_to_english_when_translation_exists_fails(self): - failures = related_language_failures(["https://forrt.org/glossary/turkish/odeme_duvar%C4%B1_paywall_/"]) - self.assertEqual(len(failures), 1) - self.assertIn("glossary/turkish/abstract", failures[0]) - - -class GlossaryAkaFilterCheck(unittest.TestCase): - HUB = ('
  • \n Type I error
  • ' - '
  • p-hacking
  • ') - - def page(self, names): - return '

    T

    Also known as: %s

    ' % names - - def test_names_in_the_hub_filter_pass(self): - pages = {"/glossary/english/type_i_error/": self.page("False-positive, Alpha error"), - "/glossary/english/p_hacking/": self.page("Fishing, p-value fishing"), - "/glossary/english/other/": "

    No other names

    "} - self.assertEqual(seo.glossary_aka_failures(self.HUB, pages), []) - - def test_preview_prefix_on_hub_links_is_ignored(self): - hub = self.HUB.replace('href="/glossary/', 'href="/rebrand-doors/glossary/') - pages = {"/glossary/english/type_i_error/": self.page("Alpha error")} - self.assertEqual(seo.glossary_aka_failures(hub, pages), []) - - def test_missing_hub_fails(self): - with tempfile.TemporaryDirectory() as public: - self.assertEqual(seo.check_glossary_aka_filter(public), ["%s (page not found)" % seo.GLOSSARY_HUB]) - - def test_name_missing_from_the_hub_filter_fails(self): - pages = {"/glossary/english/type_i_error/": self.page("Alpha error, Type 1 error"), - "/glossary/english/missing/": self.page("Lost")} - self.assertEqual(seo.glossary_aka_failures(self.HUB, pages), - ["/glossary/english/missing/ (Lost)", "/glossary/english/type_i_error/ (Type 1 error)"]) - - -class ClusterLinkPunctuationCheck(unittest.TestCase): - def test_trailing_sentence_punctuation_in_cluster_href_fails(self): - with tempfile.TemporaryDirectory() as public: - cluster = Path(public) / "clusters" / "cluster-1" - cluster.mkdir(parents=True) - (cluster / "index.html").write_text( - '
    ' - 'a ' - 'b ' - 'c' - '
    ', - encoding="utf-8", - ) - failures = seo.check_cluster_link_punctuation(public) - self.assertEqual( - failures, - ["clusters/cluster-1/index.html (https://example.org/article., https://example.org/bracket], https://example.org/paren))"], - ) - - def test_clean_and_balanced_cluster_href_passes(self): - with tempfile.TemporaryDirectory() as public: - cluster = Path(public) / "clusters" / "cluster-1" - cluster.mkdir(parents=True) - (cluster / "index.html").write_text( - '
    ' - 'See https://example.org/article. ' - 'And wiki.' - '
    ', - encoding="utf-8", - ) - self.assertEqual(seo.check_cluster_link_punctuation(public), []) - - -def card_failures(alt): - """Check 30 on one listing page holding the post's card image.""" - with tempfile.TemporaryDirectory() as public: - html = "%s" - page = html % (seo.ALT_TEXT_CARD_IMAGE, alt) - (Path(public) / "index.html").write_text(page, encoding="utf-8") - return seo.check_card_alt_text(seo.load_pages(public)) - - -class CardAltTextCheck(unittest.TestCase): - def test_supplied_alt_text_passes(self): - self.assertEqual(card_failures("Bronfenbrenner ecological systems model"), []) - - def test_fallback_alt_text_fails(self): - for alt in ("Featured image for From Awareness to Action", "From Awareness to Action"): - with self.subTest(alt): - self.assertEqual(card_failures(alt), ["index.html"]) - - -NOINDEX = "" -INDEXED = "" -URLSET = ("%s") - - -def sitemap_failures(sitemap_locs, index=False, write_sitemap=True): - """Check 31 on a site with an indexed home page and a noindexed /authors/stub/. - With index=True, sitemap.xml is an index of en/sitemap.xml, which write_sitemap=False - leaves out; otherwise write_sitemap=False leaves out sitemap.xml itself.""" - with tempfile.TemporaryDirectory() as public: - root = Path(public) - (root / "authors" / "stub").mkdir(parents=True) - (root / "index.html").write_text(INDEXED, encoding="utf-8") - (root / "authors" / "stub" / "index.html").write_text(NOINDEX, encoding="utf-8") - urls = "".join("https://forrt.org%s" % loc for loc in sitemap_locs) - if index: - (root / "sitemap.xml").write_text( - "" - "https://forrt.org/en/sitemap.xml" - "", encoding="utf-8") - if write_sitemap: - (root / "en").mkdir() - (root / "en" / "sitemap.xml").write_text(URLSET % urls, encoding="utf-8") - elif write_sitemap: - (root / "sitemap.xml").write_text(URLSET % urls, encoding="utf-8") - return seo.check_sitemap_noindex(public, seo.load_pages(public)) - - -class SitemapNoindexCheck(unittest.TestCase): - def test_indexed_pages_pass(self): - self.assertEqual(sitemap_failures(["/"]), []) - - def test_noindexed_page_fails(self): - self.assertEqual(sitemap_failures(["/", "/authors/stub/"]), ["/authors/stub/"]) - - def test_sitemap_index_is_followed(self): - self.assertEqual(sitemap_failures(["/authors/stub/"], index=True), ["/authors/stub/"]) - - def test_missing_sitemap_fails(self): - self.assertEqual(sitemap_failures([], write_sitemap=False), ["sitemap.xml (not found)"]) - - def test_empty_sitemap_fails(self): - for index in (False, True): - with self.subTest(index=index): - self.assertEqual(sitemap_failures([], index=index), ["sitemap.xml (lists no URLs)"]) - - def test_missing_child_sitemap_fails(self): - self.assertEqual(sitemap_failures([], index=True, write_sitemap=False), - ["en/sitemap.xml (not found)"]) - - -class BulgarianGlossaryCheck(unittest.TestCase): - def page(self, path, body): - parser = seo.PageParser() - parser.feed(body) - return seo.Page(path, parser) - - def term(self, language="bg", heading='

    Термин [Term]

    ', links=""): - metadata = {"@type":"DefinedTerm", "inLanguage":language, - "inDefinedTermSet":{"inLanguage":language}} - return self.page("glossary/bulgarian/термин/index.html", - heading + '' + links) - - def test_correct_language_and_unquoted_span_pass(self): - self.assertEqual(seo.check_bulgarian_glossary([self.term()]), []) - - def test_emphasized_statistic_in_english_suffix_passes(self): - term = self.term(heading='

    p-стойност [p-value]

    ') - self.assertEqual(seo.check_bulgarian_glossary([term]), []) - - def test_english_structured_data_fails(self): - self.assertIn("language is not bg", seo.check_bulgarian_glossary([self.term(language="en")])[0]) - - def test_unmarked_english_heading_fails(self): - self.assertIn("suffix lacks lang=en", seo.check_bulgarian_glossary([self.term(heading='

    Термин [Term]

    ')])[0]) - - def test_minified_missing_link_is_detected(self): - term = self.term(links='Term') - self.assertIn("missing glossary link", seo.check_bulgarian_glossary([term])[0]) - - def test_encoded_existing_route_and_alias_pass(self): - target = self.term() - target.path = "glossary/bulgarian/друг/index.html" - alias = self.page("glossary/old_term/index.html", '') - term = self.term(links='ДругOld') - self.assertEqual(seo.check_bulgarian_glossary([term,target,alias]), []) - - def test_missing_defined_term_fails(self): - page = self.page("glossary/bulgarian/термин/index.html", '

    Термин

    ') - self.assertIn("missing valid DefinedTerm", seo.check_bulgarian_glossary([page])[0]) - - def test_invalid_or_unrelated_jsonld_does_not_replace_defined_term(self): - for block in ('{broken', 'null', '[]', '{"@type":"WebPage"}'): - with self.subTest(block=block): - page = self.page("glossary/bulgarian/термин/index.html", - '') - self.assertIn("missing valid DefinedTerm", seo.check_bulgarian_glossary([page])[0]) - - def test_non_object_term_set_reports_failure_without_crashing(self): - for value in (None, [], "bg", 42, True): - with self.subTest(value=value): - page = self.term() - metadata = json.loads(page.jsonld[0]) - metadata["inDefinedTermSet"] = value - page.jsonld = [json.dumps(metadata)] - self.assertIn("inDefinedTermSet is not an object", seo.check_bulgarian_glossary([page])[0]) - - def doors_term(self, heading): - metadata = {"@type": "DefinedTerm", "inLanguage": "bg", "name": "*p*-стойност [p-value]", - "inDefinedTermSet": {"inLanguage": "bg"}} - return self.page("glossary/bulgarian/p_стойност/index.html", - heading + '') - - def test_doors_heading_marks_english_line_without_brackets(self): - term = self.doors_term('

    p-стойност p-value

    ') - self.assertEqual(seo.check_bulgarian_glossary([term]), []) - - def test_doors_heading_without_lang_en_fails(self): - term = self.doors_term('

    p-стойност p-value

    ') - self.assertIn("suffix lacks lang=en", seo.check_bulgarian_glossary([term])[0]) - - def test_doors_heading_with_another_english_name_fails(self): - term = self.doors_term('

    p-стойност p-hacking

    ') - self.assertIn("suffix lacks lang=en", seo.check_bulgarian_glossary([term])[0]) - - def test_english_links_still_count_as_gloss_terms(self): - parser = seo.PageParser() - parser.feed('

    Термин Term

    x') - self.assertEqual(parser.gloss_terms, ["/glossary/english/x/"]) - self.assertEqual(parser.anchors, ["/glossary/english/x/"]) - self.assertEqual(parser.h1_english_texts, ["Term"]) - - def test_landing_and_redirect_pages_do_not_need_defined_term(self): - landing = self.page("glossary/bulgarian/index.html", '

    Речник

    ') - redirect = self.page("glossary/bulgarian/old/index.html", '') - self.assertEqual(seo.check_bulgarian_glossary([landing,redirect]), []) - - -class GlossaryHubLettersCheck(unittest.TestCase): - def test_repeated_cyrillic_letter_fails(self): - hub = '' - self.assertEqual(seo.glossary_letter_failures("glossary/bulgarian/index.html", hub), - ["glossary/bulgarian/index.html (letter О listed more than once)"]) - - def test_unique_letters_and_non_hubs_pass(self): - hub = '' - self.assertEqual(seo.glossary_letter_failures("glossary/english/index.html", hub), []) - self.assertEqual(seo.glossary_letter_failures("glossary/english/x/index.html", "

    A A

    "), []) - - def test_build_without_hubs_fails(self): - with tempfile.TemporaryDirectory() as root: - self.assertEqual(seo.check_glossary_hub_letters(root), - ["glossary/*/index.html (no glossary hub with letters found)"]) - - -def visitors_failures(links, existing=("tags",), base_prefix=""): - """Check 34 on a Visitors page whose most-read list holds the given (href, text) links.""" - with tempfile.TemporaryDirectory() as public: - for name in existing: - (Path(public) / name).mkdir(parents=True) - (Path(public) / name / "index.html").write_text("", encoding="utf-8") - if links is not None: - page = Path(public) / "about" / "visitors" - page.mkdir(parents=True) - items = "".join('
  • %s9
  • ' % link for link in links) - (page / "index.html").write_text('
      %s
    ' % items, encoding="utf-8") - return seo.check_visitors_page_titles(public, base_prefix=base_prefix) - - -class VisitorsPageTitlesCheck(unittest.TestCase): - def test_titles_pass(self): - self.assertEqual(visitors_failures([("/tags/", "Tags"), ("/", "Home page")]), []) - - def test_path_for_an_existing_page_fails(self): - self.assertEqual(len(visitors_failures([("/tags/", "forrt.org/tags/")])), 1) - self.assertEqual(len(visitors_failures([("/tags/", "/tags/")])), 1) - - def test_subfolder_preview_prefix_still_catches_raw_path(self): - self.assertEqual(len(visitors_failures([("/rebrand-doors/tags/", "/tags/")], base_prefix="/rebrand-doors")), 1) - self.assertEqual(visitors_failures([("/rebrand-doors/tags/", "Tags")], base_prefix="/rebrand-doors"), []) - - def test_path_for_a_missing_page_passes(self): - self.assertEqual(visitors_failures([("/gone/", "/gone/")]), []) - - def test_missing_list_fails_and_empty_fallback_passes(self): - with tempfile.TemporaryDirectory() as public: - page = Path(public) / "about" / "visitors" - page.mkdir(parents=True) - (page / "index.html").write_text("

    No list

    ", encoding="utf-8") - self.assertIn("no list", seo.check_visitors_page_titles(public)[0]) - (page / "index.html").write_text('

    No page views reported for this period yet.

    ', encoding="utf-8") - self.assertEqual(seo.check_visitors_page_titles(public), []) - self.assertEqual(visitors_failures(None), []) - - -class EmptyNetworkIconCheck(unittest.TestCase): - def test_empty_network_icon_is_flagged(self): - page = page_from_html('
      ') - self.assertTrue(page.empty_network_icons) - - def test_populated_network_icon_passes(self): - page = page_from_html('') - self.assertFalse(page.empty_network_icons) - - def test_no_network_icon_passes(self): - page = page_from_html('

      Hello

      ') - self.assertFalse(page.empty_network_icons) + self.assertEqual(self.report("See https://example.org", exclusion), []) if __name__ == "__main__": diff --git a/scripts/tests/test_seo_breadcrumb_jsonld.py b/scripts/tests/test_seo_breadcrumb_jsonld.py new file mode 100644 index 00000000000..324f0b90b7e --- /dev/null +++ b/scripts/tests/test_seo_breadcrumb_jsonld.py @@ -0,0 +1,32 @@ +import json +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import breadcrumb_jsonld # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + +URL = "https://forrt.org/about/" + + +def failures(name): + """The check on a page whose last breadcrumb has this name.""" + data = {"@type": "BreadcrumbList", "itemListElement": [ + {"position": 1, "name": "FORRT", "item": "https://forrt.org/"}, {"position": 2, "name": name, "item": URL}]} + html = '' % (URL, json.dumps(data)) + return breadcrumb_jsonld.check(Site("", [page_from_html(html, "about/index.html")])) + + +class BreadcrumbJsonldCheck(unittest.TestCase): + def test_valid_list_passes(self): + self.assertEqual(failures("About"), []) + + def test_malformed_name_fails_without_crashing(self): + for name in ([], {"@value": "About"}): + with self.subTest(name=name): + self.assertEqual(failures(name), ["about/index.html (invalid name)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_breadcrumb_links.py b/scripts/tests/test_seo_breadcrumb_links.py new file mode 100644 index 00000000000..8c7f07cad7f --- /dev/null +++ b/scripts/tests/test_seo_breadcrumb_links.py @@ -0,0 +1,19 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import breadcrumb_links # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +class BreadcrumbLinkCheck(unittest.TestCase): + def test_empty_crumb_link_fails_and_links_outside_the_trail_are_ignored(self): + good = page_from_html('x', + "good/index.html") + bad = page_from_html('', "bad/index.html") + self.assertEqual(breadcrumb_links.check(Site("", [good, bad])), ["bad/index.html"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_bulgarian_glossary.py b/scripts/tests/test_seo_bulgarian_glossary.py new file mode 100644 index 00000000000..db9a9a0470e --- /dev/null +++ b/scripts/tests/test_seo_bulgarian_glossary.py @@ -0,0 +1,100 @@ +import json +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import bulgarian_glossary # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def bulgarian_failures(pages): + return bulgarian_glossary.check(Site("", pages)) + + +class BulgarianGlossaryCheck(unittest.TestCase): + def page(self, path, body): + return page_from_html(body, path) + + def term(self, language="bg", heading='

      Термин [Term]

      ', links=""): + metadata = {"@type":"DefinedTerm", "inLanguage":language, + "inDefinedTermSet":{"inLanguage":language}} + return self.page("glossary/bulgarian/термин/index.html", + heading + '' + links) + + def test_correct_language_and_unquoted_span_pass(self): + self.assertEqual(bulgarian_failures([self.term()]), []) + + def test_emphasized_statistic_in_english_suffix_passes(self): + term = self.term(heading='

      p-стойност [p-value]

      ') + self.assertEqual(bulgarian_failures([term]), []) + + def test_english_structured_data_fails(self): + self.assertIn("language is not bg", bulgarian_failures([self.term(language="en")])[0]) + + def test_unmarked_english_heading_fails(self): + self.assertIn("suffix lacks lang=en", bulgarian_failures([self.term(heading='

      Термин [Term]

      ')])[0]) + + def test_minified_missing_link_is_detected(self): + term = self.term(links='Term') + self.assertIn("missing glossary link", bulgarian_failures([term])[0]) + + def test_encoded_existing_route_and_alias_pass(self): + target = self.term() + target.path = "glossary/bulgarian/друг/index.html" + alias = self.page("glossary/old_term/index.html", '') + term = self.term(links='ДругOld') + self.assertEqual(bulgarian_failures([term,target,alias]), []) + + def test_missing_defined_term_fails(self): + page = self.page("glossary/bulgarian/термин/index.html", '

      Термин

      ') + self.assertIn("missing valid DefinedTerm", bulgarian_failures([page])[0]) + + def test_invalid_or_unrelated_jsonld_does_not_replace_defined_term(self): + for block in ('{broken', 'null', '[]', '{"@type":"WebPage"}'): + with self.subTest(block=block): + page = self.page("glossary/bulgarian/термин/index.html", + '') + self.assertIn("missing valid DefinedTerm", bulgarian_failures([page])[0]) + + def test_non_object_term_set_reports_failure_without_crashing(self): + for value in (None, [], "bg", 42, True): + with self.subTest(value=value): + page = self.term() + metadata = json.loads(page.jsonld[0]) + metadata["inDefinedTermSet"] = value + page.jsonld = [json.dumps(metadata)] + self.assertIn("inDefinedTermSet is not an object", bulgarian_failures([page])[0]) + + def doors_term(self, heading): + metadata = {"@type": "DefinedTerm", "inLanguage": "bg", "name": "*p*-стойност [p-value]", + "inDefinedTermSet": {"inLanguage": "bg"}} + return self.page("glossary/bulgarian/p_стойност/index.html", + heading + '') + + def test_doors_heading_marks_english_line_without_brackets(self): + term = self.doors_term('

      p-стойност p-value

      ') + self.assertEqual(bulgarian_failures([term]), []) + + def test_doors_heading_without_lang_en_fails(self): + term = self.doors_term('

      p-стойност p-value

      ') + self.assertIn("suffix lacks lang=en", bulgarian_failures([term])[0]) + + def test_doors_heading_with_another_english_name_fails(self): + term = self.doors_term('

      p-стойност p-hacking

      ') + self.assertIn("suffix lacks lang=en", bulgarian_failures([term])[0]) + + def test_english_links_still_count_as_gloss_terms(self): + page = page_from_html('

      Термин Term

      x') + self.assertEqual(page.gloss_terms, ["/glossary/english/x/"]) + self.assertEqual(page.anchors, ["/glossary/english/x/"]) + self.assertEqual(page.h1_english_texts, ["Term"]) + + def test_landing_and_redirect_pages_do_not_need_defined_term(self): + landing = self.page("glossary/bulgarian/index.html", '

      Речник

      ') + redirect = self.page("glossary/bulgarian/old/index.html", '') + self.assertEqual(bulgarian_failures([landing,redirect]), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_card_alt_text.py b/scripts/tests/test_seo_card_alt_text.py new file mode 100644 index 00000000000..2e46241fc0b --- /dev/null +++ b/scripts/tests/test_seo_card_alt_text.py @@ -0,0 +1,27 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import card_alt_text # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def card_failures(alt): + """The check on one listing page holding the post's card image.""" + html = "%s" % (card_alt_text.ALT_TEXT_CARD_IMAGE, alt) + return card_alt_text.check(Site("", [page_from_html(html)])) + + +class CardAltTextCheck(unittest.TestCase): + def test_supplied_alt_text_passes(self): + self.assertEqual(card_failures("Bronfenbrenner ecological systems model"), []) + + def test_fallback_alt_text_fails(self): + for alt in ("Featured image for From Awareness to Action", "From Awareness to Action"): + with self.subTest(alt): + self.assertEqual(card_failures(alt), ["index.html"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_citation_targets.py b/scripts/tests/test_seo_citation_targets.py new file mode 100644 index 00000000000..b7c57ad6695 --- /dev/null +++ b/scripts/tests/test_seo_citation_targets.py @@ -0,0 +1,45 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import citation_targets # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +class CitationTargetCheck(unittest.TestCase): + def check(self, html): + return citation_targets.check(Site("", [page_from_html(html, "example/index.html")])) + + def test_reference_after_citation(self): + self.assertEqual(self.check('Author, 2020' + '
    • Reference
    • '), []) + + def test_missing_data_reference_or_mismatched_key_fails(self): + self.assertTrue(self.check('Author, 2020' + '
    • Reference
    • ')) + self.assertTrue(self.check('Author, 2020' + '
    • Reference
    • ')) + + def test_missing_reference_or_nonlocal_link(self): + for href in ('#ref-Unknown', '/other/#ref-Key', '#Key', ''): + with self.subTest(href): + self.assertTrue(self.check('Citation' + '
    • Reference
    • ' % href)) + + def test_bare_attributes_do_not_crash(self): + self.assertEqual(self.check('Link

      Heading

      '), []) + self.assertEqual(self.check('Citation'), ["example/index.html (missing href)"]) + + def test_other_links_are_ignored(self): + self.assertEqual(self.check('Link'), []) + + def test_truncated_parenthetical_doi_in_data_source_fails(self): + self.assertEqual(self.check('
    • Ref DOI
    • '), []) + self.assertTrue(self.check('
    • Ref
    • ')) + self.assertTrue(self.check('
    • Ref DOI
    • ')) + self.assertTrue(self.check('
    • Ref https://doi.org/10.1002/(SICI)1099
    • ')) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_cluster_link_punctuation.py b/scripts/tests/test_seo_cluster_link_punctuation.py new file mode 100644 index 00000000000..1cb46d877f0 --- /dev/null +++ b/scripts/tests/test_seo_cluster_link_punctuation.py @@ -0,0 +1,45 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import cluster_link_punctuation # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +class ClusterLinkPunctuationCheck(unittest.TestCase): + def test_trailing_sentence_punctuation_in_cluster_href_fails(self): + with tempfile.TemporaryDirectory() as public: + cluster = Path(public) / "clusters" / "cluster-1" + cluster.mkdir(parents=True) + (cluster / "index.html").write_text( + '
      ' + 'a ' + 'b ' + 'c' + '
      ', + encoding="utf-8", + ) + failures = cluster_link_punctuation.check(Site(public, [])) + self.assertEqual( + failures, + ["clusters/cluster-1/index.html (https://example.org/article., https://example.org/bracket], https://example.org/paren))"], + ) + + def test_clean_and_balanced_cluster_href_passes(self): + with tempfile.TemporaryDirectory() as public: + cluster = Path(public) / "clusters" / "cluster-1" + cluster.mkdir(parents=True) + (cluster / "index.html").write_text( + '
      ' + 'See https://example.org/article. ' + 'And wiki.' + '
      ', + encoding="utf-8", + ) + self.assertEqual(cluster_link_punctuation.check(Site(public, [])), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_cluster_title_markup.py b/scripts/tests/test_seo_cluster_title_markup.py new file mode 100644 index 00000000000..8591f133203 --- /dev/null +++ b/scripts/tests/test_seo_cluster_title_markup.py @@ -0,0 +1,38 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import tempfile # noqa: E402 + +from seo_checks import cluster_title_markup # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +def check(public): + return cluster_title_markup.check(Site(public, [])) + + +class ClusterTitleMarkupCheck(unittest.TestCase): + def failures(self, body): + with tempfile.TemporaryDirectory() as public: + page = Path(public) / "clusters" / "cluster-1" / "index.html" + page.parent.mkdir(parents=True) + page.write_text("
      %s
      " % body, encoding="utf-8") + return check(public) + + def test_rendered_markup_passes(self): + self.assertEqual(self.failures("In Africa at Cognition (p < .05)"), []) + + def test_literal_or_unrendered_markup_fails(self): + for body in ("at <i>Cognition</i>", "in Africa", "<em>AIMS</em>", + "at &lt;i&gt;Cognition&lt;/i&gt;"): + self.assertEqual(self.failures(body), ["clusters/cluster-1/index.html"], body) + + def test_missing_cluster_pages_fail(self): + with tempfile.TemporaryDirectory() as public: + self.assertEqual(check(public), ["clusters/ (no cluster pages found)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_clusters_map.py b/scripts/tests/test_seo_clusters_map.py new file mode 100644 index 00000000000..74192d6e946 --- /dev/null +++ b/scripts/tests/test_seo_clusters_map.py @@ -0,0 +1,45 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import clusters_map # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +def clusters_map_failures(page): + with tempfile.TemporaryDirectory() as public: + (Path(public) / "clusters").mkdir() + (Path(public) / "clusters" / "index.html").write_text(page, encoding="utf-8") + return clusters_map.check(Site(public, [])) + + +class ClustersMapCheck(unittest.TestCase): + MAP = ('
      ' + '
      1. One
      ' + '
      not in the map') + + def test_named_counted_names_hidden_drawing_closed_panels_and_targets_pass(self): + self.assertEqual(clusters_map_failures(self.MAP), []) + + def test_each_fault_fails_once(self): + for change in (('class="clusters-map__ring" aria-hidden="true">', 'class="clusters-map__ring">'), + ('aria-hidden="true">', 'aria-hidden="true">'), + ('id="c1-a"', 'id="c1-b"'), (" inert>", ">"), + ('clusters-map__tag" href="/clusters/cluster-1/"', 'clusters-map__tag" href=""'), + ('class="clusters-map__tag"', 'class="other"'), ('One', ''), + ('class="clusters-map__tag" href', 'class="clusters-map__tag" aria-hidden="true" href'), + ('
    • One
    • ', '
    • One
    • Two
    • ')): + with self.subTest(change): + self.assertEqual(len(clusters_map_failures(self.MAP.replace(*change))), 1) + + def test_page_without_the_drawing_fails(self): + self.assertTrue(clusters_map_failures("

      No map

      ")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_description_entities.py b/scripts/tests/test_seo_description_entities.py new file mode 100644 index 00000000000..3cab6cff17f --- /dev/null +++ b/scripts/tests/test_seo_description_entities.py @@ -0,0 +1,37 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import description_entities # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def failures_for(raw_description): + """The check on one page whose description has this raw attribute value.""" + page = page_from_html("" % raw_description) + return description_entities.check(Site("", [page])) + + +class DescriptionEntityCheck(unittest.TestCase): + def test_correctly_escaped_description_passes(self): + self.assertEqual(failures_for("R&D "quotes" “curly”"), []) + + def test_escaped_text_that_is_not_an_entity_passes(self): + for raw in ("the &name; syntax", "the &notanentity; syntax"): + with self.subTest(raw): + self.assertEqual(failures_for(raw), []) + + def test_double_escaped_entities_fail(self): + for raw, entity in (("&ldquo;quote&rdquo;", "“"), + ("R&amp;D", "&"), + ("it&#39;s", "'"), + ("it&#x27;s", "'")): + with self.subTest(raw): + failures = failures_for(raw) + self.assertEqual(len(failures), 1) + self.assertIn(entity, failures[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_empty_network_icon.py b/scripts/tests/test_seo_empty_network_icon.py new file mode 100644 index 00000000000..376349a16f7 --- /dev/null +++ b/scripts/tests/test_seo_empty_network_icon.py @@ -0,0 +1,26 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import empty_network_icon # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def icon_failures(html): + return empty_network_icon.check(Site("", [page_from_html("%s" % html)])) + + +class EmptyNetworkIconCheck(unittest.TestCase): + def test_empty_network_icon_is_flagged(self): + self.assertEqual(icon_failures('
        '), ["index.html"]) + + def test_populated_network_icon_passes(self): + self.assertEqual(icon_failures(''), []) + + def test_no_network_icon_passes(self): + self.assertEqual(icon_failures("

        Hello

        "), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_extension_move.py b/scripts/tests/test_seo_extension_move.py new file mode 100644 index 00000000000..564b8724d60 --- /dev/null +++ b/scripts/tests/test_seo_extension_move.py @@ -0,0 +1,50 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import extension_move # noqa: E402 +from seo_checks._site import load_site # noqa: E402 + + +MOVED = ("" + "" + "Continue") + + +def move_failures(page=MOVED, robots="User-agent: *\nAllow: /\n"): + """The check on a build with this old extension page and robots.txt (None: no file).""" + with tempfile.TemporaryDirectory() as public: + if page is not None: + path = Path(public) / "chromium-extension" / "index.html" + path.parent.mkdir() + path.write_text(page, encoding="utf-8") + if robots is not None: + (Path(public) / "robots.txt").write_text(robots, encoding="utf-8") + return extension_move.check(load_site(public)) + + +class ExtensionMoveCheck(unittest.TestCase): + def test_redirect_passes(self): + self.assertEqual(move_failures(), []) + + def test_missing_or_incomplete_redirect_fails(self): + self.assertIn("missing instant redirect", move_failures(page=None)[0]) + for part in MOVED.split("><"): + with self.subTest(part): + self.assertIn("missing instant redirect", move_failures(MOVED.replace(part, "br"))[0]) + + def test_staging_must_not_replace_the_extension_site(self): + robots = "User-agent: *\nDisallow: /\n" + self.assertIn("staging build", move_failures(robots=robots)[0]) + self.assertEqual(move_failures(page=None, robots=robots), []) + + def test_missing_robots_or_retired_sitemap_fails(self): + self.assertEqual(move_failures(robots=None), ["robots.txt (missing)"]) + self.assertEqual(move_failures(robots="Sitemap: https://forrt.org/chromium-extension/sitemap.xml\n"), + ["robots.txt (lists the retired extension sitemap)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_flora_citation.py b/scripts/tests/test_seo_flora_citation.py new file mode 100644 index 00000000000..92087194924 --- /dev/null +++ b/scripts/tests/test_seo_flora_citation.py @@ -0,0 +1,39 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import flora_citation # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +def flora_failures(html): + """The check on a FLoRA page with this HTML (None: no page).""" + with tempfile.TemporaryDirectory() as public: + if html is not None: + page = Path(public) / flora_citation.FLORA_PAGE + page.parent.mkdir(parents=True) + page.write_text(html, encoding="utf-8") + return flora_citation.check(Site(public, [])) + + +class FloraCitationCheck(unittest.TestCase): + TITLE = "Azevedo, F. (2026). FORRT Library of Reproduction and Replication Attempts (FLoRA) [Data set]. " + OSF = 'OSF. https://doi.org/10.17605/OSF.IO/9R62X' + ZENODO = 'Zenodo. https://doi.org/10.5281/zenodo.24461022' + + def test_citation_passes_whichever_doi_it_links(self): + for doi in (self.OSF, self.ZENODO): + with self.subTest(doi): + self.assertEqual(flora_failures("

        Wallrich, L.*, ... %s%s

        " % (self.TITLE, doi)), []) + + def test_missing_citation_or_page_fails(self): + self.assertIn("DOI", flora_failures("

        How to cite:

        ")[0]) + self.assertIn("DOI", flora_failures("

        %sOSF.

        other

        " % self.TITLE.replace("(FLoRA)", "(FLoRA)" + " x" * 200))[0]) + self.assertIn("DOI", flora_failures("

        See https://doi.org/10.5281/zenodo.24461022

        ")[0]) + self.assertIn("not found", flora_failures(None)[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_glossary_aka_filter.py b/scripts/tests/test_seo_glossary_aka_filter.py new file mode 100644 index 00000000000..d9b82505934 --- /dev/null +++ b/scripts/tests/test_seo_glossary_aka_filter.py @@ -0,0 +1,41 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import glossary_aka_filter # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +class GlossaryAkaFilterCheck(unittest.TestCase): + HUB = ('
      • \n Type I error
      • ' + '
      • p-hacking
      • ') + + def page(self, names): + return '

        T

        Also known as: %s

        ' % names + + def test_names_in_the_hub_filter_pass(self): + pages = {"/glossary/english/type_i_error/": self.page("False-positive, Alpha error"), + "/glossary/english/p_hacking/": self.page("Fishing, p-value fishing"), + "/glossary/english/other/": "

        No other names

        "} + self.assertEqual(glossary_aka_filter.glossary_aka_failures(self.HUB, pages), []) + + def test_preview_prefix_on_hub_links_is_ignored(self): + hub = self.HUB.replace('href="/glossary/', 'href="/rebrand-doors/glossary/') + pages = {"/glossary/english/type_i_error/": self.page("Alpha error")} + self.assertEqual(glossary_aka_filter.glossary_aka_failures(hub, pages), []) + + def test_missing_hub_fails(self): + with tempfile.TemporaryDirectory() as public: + self.assertEqual(glossary_aka_filter.check(Site(public, [])), ["%s (page not found)" % glossary_aka_filter.GLOSSARY_HUB]) + + def test_name_missing_from_the_hub_filter_fails(self): + pages = {"/glossary/english/type_i_error/": self.page("Alpha error, Type 1 error"), + "/glossary/english/missing/": self.page("Lost")} + self.assertEqual(glossary_aka_filter.glossary_aka_failures(self.HUB, pages), + ["/glossary/english/missing/ (Lost)", "/glossary/english/type_i_error/ (Type 1 error)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_glossary_hub_letters.py b/scripts/tests/test_seo_glossary_hub_letters.py new file mode 100644 index 00000000000..93d63875b40 --- /dev/null +++ b/scripts/tests/test_seo_glossary_hub_letters.py @@ -0,0 +1,29 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import glossary_hub_letters # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +class GlossaryHubLettersCheck(unittest.TestCase): + def test_repeated_cyrillic_letter_fails(self): + hub = '' + self.assertEqual(glossary_hub_letters.glossary_letter_failures("glossary/bulgarian/index.html", hub), + ["glossary/bulgarian/index.html (letter О listed more than once)"]) + + def test_unique_letters_and_non_hubs_pass(self): + hub = '' + self.assertEqual(glossary_hub_letters.glossary_letter_failures("glossary/english/index.html", hub), []) + self.assertEqual(glossary_hub_letters.glossary_letter_failures("glossary/english/x/index.html", "

        A A

        "), []) + + def test_build_without_hubs_fails(self): + with tempfile.TemporaryDirectory() as root: + self.assertEqual(glossary_hub_letters.check(Site(root, [])), + ["glossary/*/index.html (no glossary hub with letters found)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_glossary_links.py b/scripts/tests/test_seo_glossary_links.py new file mode 100644 index 00000000000..4311df153a0 --- /dev/null +++ b/scripts/tests/test_seo_glossary_links.py @@ -0,0 +1,38 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import tempfile # noqa: E402 + +from seo_checks import glossary_links # noqa: E402 +from seo_checks._site import load_site # noqa: E402 + + +class GlossaryLinkCheck(unittest.TestCase): + def check_links(self, hrefs, base="https://forrt.org/"): + with tempfile.TemporaryDirectory() as public: + root = Path(public) + term = root / "glossary/english/preregistration/index.html" + term.parent.mkdir(parents=True) + term.write_text('' % base) + links = "".join('term' % href for href in hrefs) + (root / "index.html").write_text('%s' % (base, links)) + return glossary_links.check(load_site(public)) + + def test_existing_term_and_preview_base_pass(self): + for base in ("https://forrt.org/", "https://forrt.org/rebrand-doors/"): + with self.subTest(base=base): + self.assertEqual(self.check_links([ + base + "glossary/english/preregistration/", + "glossary/english/preregistration/#definition", + ], base), []) + + def test_missing_non_english_external_and_empty_links_fail(self): + links = ["/glossary/english/missing/", "/glossary/german/preregistration/", + "https://example.org/glossary/english/preregistration/", ""] + self.assertEqual(len(self.check_links(links)), len(links)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_glossary_related_language.py b/scripts/tests/test_seo_glossary_related_language.py new file mode 100644 index 00000000000..31fe6259765 --- /dev/null +++ b/scripts/tests/test_seo_glossary_related_language.py @@ -0,0 +1,43 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import glossary_related_language # noqa: E402 +from seo_checks._site import load_site # noqa: E402 + + +def related_language_failures(target_alternates, prefix=""): + """A Turkish page links its related term to the English Paywall page.""" + with tempfile.TemporaryDirectory() as public: + english = Path(public) / "glossary/english/paywall" + turkish = Path(public) / "glossary/turkish/abstract" + english.mkdir(parents=True) + turkish.mkdir(parents=True) + links = "".join("" % h for h in target_alternates) + (english / "index.html").write_text("%s" % links, encoding="utf-8") + (turkish / "index.html").write_text( + "" + "

        elsewhere

        " % prefix, encoding="utf-8") + return glossary_related_language.check(load_site(public)) + + +class GlossaryRelatedLanguageCheck(unittest.TestCase): + def test_preview_prefix_is_ignored(self): + failures = related_language_failures(["https://forrt.org/rebrand-doors/glossary/turkish/odeme_duvar%C4%B1_paywall_/"], + prefix="/rebrand-doors") + self.assertEqual(len(failures), 1) + + def test_link_to_english_when_no_translation_exists_passes(self): + self.assertEqual(related_language_failures(["https://forrt.org/glossary/german/bezahlschranke/"]), []) + + def test_link_to_english_when_translation_exists_fails(self): + failures = related_language_failures(["https://forrt.org/glossary/turkish/odeme_duvar%C4%B1_paywall_/"]) + self.assertEqual(len(failures), 1) + self.assertIn("glossary/turkish/abstract", failures[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_glossary_title_markdown.py b/scripts/tests/test_seo_glossary_title_markdown.py new file mode 100644 index 00000000000..f3523796ba8 --- /dev/null +++ b/scripts/tests/test_seo_glossary_title_markdown.py @@ -0,0 +1,29 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import glossary_title_markdown # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +class GlossaryTitleMarkdownCheck(unittest.TestCase): + def check(self, title, h1, path="glossary/english/term/index.html"): + page = page_from_html("%s

        %s

        " % (title, h1), path) + return glossary_title_markdown.check(Site("", [page])) + + def test_rendered_emphasis_and_lone_asterisk_pass(self): + self.assertEqual(self.check("Research Contribution Metric (p) | FORRT", + "Research Contribution Metric (p)"), []) + self.assertEqual(self.check("G*Power | FORRT", "G*Power"), []) + self.assertEqual(self.check("G*Power and P*Hack | FORRT", "G*Power and P*Hack"), []) + + def test_literal_emphasis_fails_on_glossary_pages_only(self): + self.assertEqual(len(self.check("Research Contribution Metric (*p*) | FORRT", "x")), 1) + self.assertEqual(len(self.check("x", "Research Contribution Metric (*p*)")), 1) + self.assertEqual(len(self.check("x", "*p*-value")), 1) + self.assertEqual(self.check("x", "*p*", path="post/x/index.html"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_inline_scripts.py b/scripts/tests/test_seo_inline_scripts.py new file mode 100644 index 00000000000..1c709d99c76 --- /dev/null +++ b/scripts/tests/test_seo_inline_scripts.py @@ -0,0 +1,27 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import inline_scripts # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +class InlineScriptCheck(unittest.TestCase): + def failures(self, body): + return inline_scripts.check(Site("", [page_from_html("%s" % body)])) + + def test_small_inline_and_external_scripts_pass(self): + self.assertEqual(self.failures(""), []) + + def test_inline_data_over_the_limit_fails(self): + data = "x" * (inline_scripts.MAX_INLINE_SCRIPT + 1) + self.assertEqual(self.failures("" % data), ["index.html (200 KB)"]) + + def test_unclosed_inline_data_fails(self): + data = "x" * (inline_scripts.MAX_INLINE_SCRIPT + 1) + self.assertEqual(self.failures("' % src)])) + + def test_retired_script_fails(self): + self.assertEqual(self.check("/js/newsletter.js"), ["index.html"]) + + def test_other_scripts_pass(self): + self.assertEqual(self.check("/js/newsletter-form.js"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_related_card_pictures.py b/scripts/tests/test_seo_related_card_pictures.py new file mode 100644 index 00000000000..8607ec679a6 --- /dev/null +++ b/scripts/tests/test_seo_related_card_pictures.py @@ -0,0 +1,38 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import related_card_pictures # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def card(folder, whole): + return '
        ' % (" ec-thumb-whole" if whole else "", folder) + + +def picture_failures(listed_whole, related_whole, section="post"): + """The check on a section list and an article whose related card shows the same picture.""" + pages = [page_from_html(card("post/a", listed_whole), section + "/index.html"), + page_from_html(card("post/a", related_whole), section + "/b/index.html")] + return related_card_pictures.check(Site("", pages)) + + +class RelatedCardPicturesCheck(unittest.TestCase): + def test_same_treatment_passes(self): + for whole in (False, True): + with self.subTest(whole=whole): + self.assertEqual(picture_failures(whole, whole), []) + + def test_different_treatment_fails(self): + for section in ("post", "educators-corner"): + with self.subTest(section): + self.assertEqual(picture_failures(True, False, section), [section + "/b/index.html"]) + self.assertEqual(picture_failures(False, True, section), [section + "/b/index.html"]) + + def test_other_sections_are_ignored(self): + self.assertEqual(picture_failures(True, False, "pedagogies"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_resource_pagination.py b/scripts/tests/test_seo_resource_pagination.py new file mode 100644 index 00000000000..2b73e5d6d35 --- /dev/null +++ b/scripts/tests/test_seo_resource_pagination.py @@ -0,0 +1,76 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import json # noqa: E402 + +from seo_checks import resource_pagination # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def check(pages): + return resource_pagination.check(Site("", pages)) + + +class ResourcePaginationCheck(unittest.TestCase): + def pages(self, prefix=""): + pages = [] + for number in (1, 2, 3): + relative = "resources/" + ("page/%d/" % number if number > 1 else "") + url = "https://example.org" + prefix + "/" + relative + name = "Resources" + (" – Page %d" % number if number > 1 else "") + resource = prefix + "/curated_resources/item-%d/" % number + data = {"@type": "CollectionPage", "@id": url + "#collection", "url": url, "name": name, + "mainEntity": {"numberOfItems": 1, "itemListElement": [{"url": "https://example.org" + resource}]}} + text = ('%s | FORRT' + '' + '' + '' + '

        Resource

        ') % (name, url, url, name, number, json.dumps(data), resource) + pages.append(page_from_html(text, relative + "index.html")) + return pages + + def test_self_canonical_numbered_subsets_pass_with_preview_prefix(self): + for prefix in ("", "/rebrand-doors"): + with self.subTest(prefix=prefix): + self.assertEqual(check(self.pages(prefix)), []) + + def test_staging_noindex_applies_to_directory_and_subsets(self): + pages = self.pages("/rebrand-doors") + for page in pages: + page.noindex = True + self.assertEqual(check(pages), []) + + def test_repeated_first_page_metadata_fails(self): + pages = self.pages() + pages[1].canonical = pages[0].canonical + pages[1].title = pages[0].title + pages[1].descriptions = pages[0].descriptions + failures = check(pages) + self.assertEqual(len(failures), 1) + for text in ("not self-canonical", "repeated title", "repeated description", "omits page number"): + self.assertIn(text, failures[0]) + + def test_wrong_structured_subset_fails(self): + pages = self.pages() + pages[1].resource_links = pages[0].resource_links + self.assertIn("subset does not match HTML cards", check(pages)[0]) + + def test_malformed_collection_fails_without_crashing(self): + for entity in (None, [], "x", {"itemListElement": None}, {"itemListElement": ["x"]}, {"itemListElement": [{"url": 1}]}): + with self.subTest(entity=entity): + pages = self.pages() + data = json.loads(pages[1].jsonld[0]) + data["mainEntity"] = entity + pages[1].jsonld = [json.dumps(data)] + self.assertIn("subset does not match HTML cards", check(pages)[0]) + + def test_query_canonical_is_never_used_for_subsets(self): + pages = self.pages() + pages[1].canonical += "?type=reading" + self.assertIn("not self-canonical", check(pages)[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_share_image_metadata.py b/scripts/tests/test_seo_share_image_metadata.py new file mode 100644 index 00000000000..516549654be --- /dev/null +++ b/scripts/tests/test_seo_share_image_metadata.py @@ -0,0 +1,33 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import share_image_metadata # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +class ShareImageMetadataCheck(unittest.TestCase): + def failures(self, **overrides): + meta = {"og:image": "https://example.org/preview/social/test.png", + "twitter:image": "https://example.org/preview/social/test.png", + "og:image:type": "image/png", "og:image:width": "7", "og:image:height": "5"} + meta.update(overrides) + page = page_from_html("".join('' % (k, v) for k, v in meta.items())) + return share_image_metadata.check(Site("", [page])) + + def test_matching_png_metadata_passes(self): + self.assertEqual(self.failures(), []) + + def test_incorrect_type_dimensions_or_twitter_url_fail(self): + for change in ({"og:image:type": "image/webp"}, {"og:image:width": "0"}, + {"og:image:height": "unknown"}, {"twitter:image": "original.webp"}): + with self.subTest(change=change): + self.assertTrue(self.failures(**change)) + + def test_undecodable_original_remains_report_only(self): + self.assertEqual(self.failures(**{"og:image": "original.webp"}), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_sitemap_noindex.py b/scripts/tests/test_seo_sitemap_noindex.py new file mode 100644 index 00000000000..9c71865eddb --- /dev/null +++ b/scripts/tests/test_seo_sitemap_noindex.py @@ -0,0 +1,63 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import sitemap_noindex # noqa: E402 +from seo_checks._site import load_site # noqa: E402 + + +NOINDEX = "" +INDEXED = "" +URLSET = ("%s") + + +def sitemap_failures(sitemap_locs, index=False, write_sitemap=True): + """The check on a site with an indexed home page and a noindexed /authors/stub/. + With index=True, sitemap.xml is an index of en/sitemap.xml, which write_sitemap=False + leaves out; otherwise write_sitemap=False leaves out sitemap.xml itself.""" + with tempfile.TemporaryDirectory() as public: + root = Path(public) + (root / "authors" / "stub").mkdir(parents=True) + (root / "index.html").write_text(INDEXED, encoding="utf-8") + (root / "authors" / "stub" / "index.html").write_text(NOINDEX, encoding="utf-8") + urls = "".join("https://forrt.org%s" % loc for loc in sitemap_locs) + if index: + (root / "sitemap.xml").write_text( + "" + "https://forrt.org/en/sitemap.xml" + "", encoding="utf-8") + if write_sitemap: + (root / "en").mkdir() + (root / "en" / "sitemap.xml").write_text(URLSET % urls, encoding="utf-8") + elif write_sitemap: + (root / "sitemap.xml").write_text(URLSET % urls, encoding="utf-8") + return sitemap_noindex.check(load_site(public)) + + +class SitemapNoindexCheck(unittest.TestCase): + def test_indexed_pages_pass(self): + self.assertEqual(sitemap_failures(["/"]), []) + + def test_noindexed_page_fails(self): + self.assertEqual(sitemap_failures(["/", "/authors/stub/"]), ["/authors/stub/"]) + + def test_sitemap_index_is_followed(self): + self.assertEqual(sitemap_failures(["/authors/stub/"], index=True), ["/authors/stub/"]) + + def test_missing_sitemap_fails(self): + self.assertEqual(sitemap_failures([], write_sitemap=False), ["sitemap.xml (not found)"]) + + def test_empty_sitemap_fails(self): + for index in (False, True): + with self.subTest(index=index): + self.assertEqual(sitemap_failures([], index=index), ["sitemap.xml (lists no URLs)"]) + + def test_missing_child_sitemap_fails(self): + self.assertEqual(sitemap_failures([], index=True, write_sitemap=False), + ["en/sitemap.xml (not found)"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_summary_credit_marker.py b/scripts/tests/test_seo_summary_credit_marker.py new file mode 100644 index 00000000000..3faf95848be --- /dev/null +++ b/scripts/tests/test_seo_summary_credit_marker.py @@ -0,0 +1,62 @@ +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import summary_credit_marker # noqa: E402 +from seo_checks._site import Site # noqa: E402 + + +class SummaryCreditMarkerCheck(unittest.TestCase): + credit = '

        Summary by Dr Tamara Kalandadze

        ' + marked = {"summary_1": {"Title": "Paper ⬦"}, "summary_2": {"Title": "Other paper ⌺⬦"}} + + def check(self, html, *, dei_html="", summaries=None, missing=None): + with tempfile.TemporaryDirectory() as public: + for slug, body in (("", ""), ("open-reproducible", html), ("diversity-equity-inclusion", dei_html)): + if slug == missing: + continue + collection = Path(public) / "summaries" / slug / "index.html" + collection.parent.mkdir(parents=True, exist_ok=True) + collection.write_text(body, encoding="utf-8") + return summary_credit_marker.credit_failures(public, summaries or {}) + + def test_title_markers_fail_in_html_and_json_ld(self): + for html in ("

        Paper ⬦

        ", "

        Paper ⬦

        ", + r''): + with self.subTest(html=html): + self.assertEqual(self.check(html), ["summaries/open-reproducible/index.html: raw summary author marker"]) + + def test_missing_page_fails(self): + self.assertEqual(self.check("", missing="diversity-equity-inclusion"), + ["summaries/diversity-equity-inclusion/index.html: missing page"]) + + def test_no_credit_needed_for_data_without_author_markers(self): + self.assertEqual(self.check("

        Paper ◈ ⌺

        ", summaries={"summary_1": {"Title": "Paper ◈ ⌺"}}), []) + self.assertTrue(self.check(self.credit)) + + def test_requires_credits_matching_each_collections_data(self): + self.assertEqual(self.check(self.credit * 2, dei_html=self.credit, summaries=self.marked), []) + failures = self.check(self.credit, dei_html=self.credit.replace("Tamara", "Other"), summaries=self.marked) + self.assertEqual(failures, [ + "summaries/open-reproducible/index.html: expected 2 written credits, found 1 matching out of 1 credit lines", + "summaries/diversity-equity-inclusion/index.html: expected 1 written credits, found 0 matching out of 1 credit lines", + ]) + + def test_minified_credit_followed_by_heading(self): + html = self.credit.replace('class="summary-credit"', 'class=summary-credit').removesuffix("

        ") + self.assertEqual(self.check(html + "

        Main takeaways

        ", summaries={"summary_1": {"Title": "Paper ⬦"}}), []) + + def test_check_reads_the_builds_data_folder(self): + with tempfile.TemporaryDirectory() as data, mock.patch.dict(os.environ, {"HUGO_DATADIR": data}): + self.assertIn("could not read", summary_credit_marker.check(Site(data, []))[0]) + (Path(data) / "summaries.json").write_text(json.dumps(self.marked), encoding="utf-8") + self.assertEqual([f.rpartition(": ")[2] for f in summary_credit_marker.check(Site(data, []))], ["missing page"] * 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_summary_takeaway_links.py b/scripts/tests/test_seo_summary_takeaway_links.py new file mode 100644 index 00000000000..3b58e8a3019 --- /dev/null +++ b/scripts/tests/test_seo_summary_takeaway_links.py @@ -0,0 +1,38 @@ +import sys +import unittest +from html import escape +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import summary_takeaway_links # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +class SummaryTakeawayLinkCheck(unittest.TestCase): + path = "summaries/open-reproducible/index.html" + + def check(self, link, after=""): + html = '
        • ' + link + '
        ' + after + return summary_takeaway_links.check(Site("", [page_from_html(html, self.path)])) + + def test_google_redirect_fails(self): + href = "https://www.google.com/url?q=https://example.org/paper&sa=D" + self.assertEqual(self.check(f'Paper'), [f"{self.path}: {href!r}"]) + + def test_missing_or_placeholder_href_fails(self): + self.assertEqual(self.check("Paper"), [f"{self.path}: ''"]) + for href in ("", "#", "#ZgotmplZ"): + with self.subTest(href=href): + self.assertEqual(self.check(f'Paper'), [f"{self.path}: {href!r}"]) + + def test_direct_links_pass(self): + for href in ("https://example.org/paper", "#h.study", "/summaries/open-reproducible/#h.study"): + with self.subTest(href=href): + self.assertEqual(self.check(f'Paper'), []) + + def test_other_links_are_ignored(self): + self.assertEqual(self.check("Plain takeaway", ''), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_seo_visitors_page_titles.py b/scripts/tests/test_seo_visitors_page_titles.py new file mode 100644 index 00000000000..237a2cb3b18 --- /dev/null +++ b/scripts/tests/test_seo_visitors_page_titles.py @@ -0,0 +1,53 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from seo_checks import visitors_page_titles # noqa: E402 +from seo_checks._site import Site, page_from_html # noqa: E402 + + +def visitors_failures(links, existing=("tags",), base_prefix=""): + """The check on a Visitors page whose most-read list holds the given (href, text) links.""" + with tempfile.TemporaryDirectory() as public: + for name in existing: + (Path(public) / name).mkdir(parents=True) + (Path(public) / name / "index.html").write_text("", encoding="utf-8") + if links is not None: + page = Path(public) / "about" / "visitors" + page.mkdir(parents=True) + items = "".join('
      • %s9
      • ' % link for link in links) + (page / "index.html").write_text('
          %s
        ' % items, encoding="utf-8") + home = page_from_html("" % base_prefix) + return visitors_page_titles.check(Site(public, [home])) + + +class VisitorsPageTitlesCheck(unittest.TestCase): + def test_titles_pass(self): + self.assertEqual(visitors_failures([("/tags/", "Tags"), ("/", "Home page")]), []) + + def test_path_for_an_existing_page_fails(self): + self.assertEqual(len(visitors_failures([("/tags/", "forrt.org/tags/")])), 1) + self.assertEqual(len(visitors_failures([("/tags/", "/tags/")])), 1) + + def test_subfolder_preview_prefix_still_catches_raw_path(self): + self.assertEqual(len(visitors_failures([("/rebrand-doors/tags/", "/tags/")], base_prefix="/rebrand-doors")), 1) + self.assertEqual(visitors_failures([("/rebrand-doors/tags/", "Tags")], base_prefix="/rebrand-doors"), []) + + def test_path_for_a_missing_page_passes(self): + self.assertEqual(visitors_failures([("/gone/", "/gone/")]), []) + + def test_missing_list_fails_and_empty_fallback_passes(self): + with tempfile.TemporaryDirectory() as public: + page = Path(public) / "about" / "visitors" + page.mkdir(parents=True) + (page / "index.html").write_text("

        No list

        ", encoding="utf-8") + self.assertIn("no list", visitors_page_titles.check(Site(public, []))[0]) + (page / "index.html").write_text('

        No page views reported for this period yet.

        ', encoding="utf-8") + self.assertEqual(visitors_page_titles.check(Site(public, [])), []) + self.assertEqual(visitors_failures(None), []) + + +if __name__ == "__main__": + unittest.main()