#!/usr/bin/env python3
from __future__ import annotations
import contextlib
import io
import json
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from docbook_qa import (
SQL_BLOCK_STARTER_KEYWORDS,
SQL_BLOCK_STARTER_EXTRAS,
SQL_HIGHLIGHT_KEYWORDS,
SQL_STARTERS,
SQL_STATEMENT_START_KEYWORDS,
add_source_findings,
build_index,
check_html_file,
load_xml,
main,
)
from xml_tree import parse as parse_xml
DOCBOOK_OPEN = ''
DOCBOOK_CLOSE = ' '
def write_tmp(suffix: str, text: str) -> Path:
path = Path(tempfile.mkdtemp()) / f"fixture{suffix}"
path.write_text(text, encoding="utf-8")
return path
class DocBookSourceLintTest(unittest.TestCase):
def source_findings(self, body: str):
path = write_tmp(".xml", DOCBOOK_OPEN + body + DOCBOOK_CLOSE)
return add_source_findings(load_xml(path).getroot(), path)
def assertCategories(self, body: str, categories: set[str]):
self.assertEqual(categories, {finding.category for finding in self.source_findings(body)})
def assertInfoCategory(self, body: str, category: str):
findings = self.source_findings(body)
self.assertEqual([(category, "info")], [(finding.category, finding.severity) for finding in findings])
def test_mixed_programlisting_output_violation_and_clean_case(self):
self.assertCategories(
'SELECT 1;\n ?column?\n----------\n 1\n(1 row) ',
{"mixed-programlisting-output"},
)
self.assertCategories('SELECT 1; ', set())
def test_xml_tree_rejects_doctype(self):
path = write_tmp(
".xml",
']>'
+ DOCBOOK_OPEN
+ '&expand; '
+ DOCBOOK_CLOSE,
)
with self.assertRaises(Exception):
parse_xml(path)
def test_xml_tree_allows_doctype_without_entity_references(self):
# postgis-out.xml itself carries a DOCTYPE: xmllint emits the DocBook DTD's
# public identifier plus dozens of unreferenced SYSTEM/literal entity
# declarations left over from assembling doc/*.xml at build time. None of
# that is an attack when nothing in the document body asks the parser to
# expand any of it, so a harmless DOCTYPE like this one must still parse.
path = write_tmp(
".xml",
''
''
']>'
+ DOCBOOK_OPEN
+ 'no custom entity is referenced here '
+ DOCBOOK_CLOSE,
)
tree = parse_xml(path)
self.assertEqual("book", tree.tree.getroot().tag.rsplit("}", 1)[-1])
def test_xml_tree_rejects_non_ascii_entity_reference(self):
# A regex that only matches ASCII entity names, [A-Za-z_][\\w.-]*,
# never sees "&é;": the guard must not depend on predicting
# every spelling a reference can take, so this must still be rejected.
path = write_tmp(
".xml",
']>'
+ DOCBOOK_OPEN
+ '&é; '
+ DOCBOOK_CLOSE,
)
with self.assertRaises(Exception):
parse_xml(path)
def test_xml_tree_rejects_parameter_entity_injected_general_entity(self):
# The general entity "expand" is never declared directly; a parameter
# entity's replacement text declares it instead. A pre-pass that
# collects only directly-declared general entity names never sees it,
# so the guard must not rely on predicting every declaration path.
path = write_tmp(
".xml",
"\">\n"
"%pe;\n"
"]>\n"
+ DOCBOOK_OPEN
+ '&expand; '
+ DOCBOOK_CLOSE,
)
with self.assertRaises(Exception):
parse_xml(path)
def test_xml_tree_rejects_entity_reference_in_attribute_value(self):
# Attribute-value normalization substitutes entity references before
# any element/attribute handler ever sees them, so a reference cannot
# be caught by inspecting element content alone.
path = write_tmp(
".xml",
']>'
+ DOCBOOK_OPEN
+ 'text '
+ DOCBOOK_CLOSE,
)
with self.assertRaises(Exception):
parse_xml(path)
def test_mixed_programlisting_dash_run_markers_and_sql_comments(self):
for output in ("left | right\n----|----\n1 | 2", "----RESULT output ---\n1"):
with self.subTest(output=output):
self.assertCategories(
f'SELECT 1;\n{output} ',
{"mixed-programlisting-output"},
)
self.assertCategories(
'-- first comment\n-- second caption line\nSELECT 1;\n-- internal comment ',
{"leading-sql-comment"},
)
self.assertCategories(
'---- decorative preface\nSELECT 1; ',
{"mixed-programlisting-output"},
)
self.assertCategories(
'SELECT 1;\n-- explain the next step\nSELECT 2; ',
set(),
)
self.assertCategories(
'-- Manifest.txt --\nAssembly-Version: 1.0 ',
set(),
)
self.assertCategories(
'-- export this file\n\\lo_export 42 /tmp/result.png ',
{"leading-sql-comment"},
)
def test_screen_contains_sql_violation_and_clean_case(self):
self.assertCategories('SELECT 1; ', {"screen-contains-sql"})
self.assertCategories('POINT(1 2) ', set())
def test_screen_contains_psql_command_violation_and_clean_cases(self):
for command in (r"\d roads", r" \pset tuples_only on", r"\?", r"\! echo ready"):
with self.subTest(command=command):
self.assertCategories(
f'output\n{command}\nmore output ',
{"screen-contains-psql-command"},
)
self.assertCategories(
r'\d roads Table "roads" ',
set(),
)
self.assertCategories(
r'C:\temp\roads.sql ',
set(),
)
self.assertCategories(
r'\x0103000020e6100000 ',
set(),
)
def test_substantive_raster_image_violation_and_branding_allowlist(self):
self.assertCategories(
' '
' ',
{"legacy-raster-image"},
)
self.assertCategories(
' '
' ',
set(),
)
self.assertCategories(
' '
' ',
set(),
)
self.assertCategories(
' '
' ',
set(),
)
self.assertCategories(
' '
' ',
set(),
)
def test_redundant_output_caption_violation_and_real_prose_clean_case(self):
self.assertCategories(
' The output: 1 ',
{"redundant-output-caption"},
)
self.assertCategories(
'The output preserves the input SRID. 1 ',
set(),
)
def test_duplicate_refsection_title_violation_and_clean_case(self):
self.assertCategories(
'Description '
'Description ',
{"duplicate-refsection-title"},
)
self.assertCategories(
'Description '
'Examples ',
set(),
)
def test_repeated_example_section_variants_violation_and_single_section_clean_case(self):
self.assertCategories(
'Example: Geometry '
'Examples - Geography ',
{"repeated-example-sections"},
)
self.assertCategories(
'Examples '
'Geometry. SELECT 1; 1 '
'Geography. SELECT 2; 2 '
' ',
set(),
)
def test_metadata_role_in_admonition_violation_and_clean_case(self):
self.assertCategories(
'Availability: 3.7 ',
{"metadata-role-in-admonition"},
)
self.assertCategories(
'Description '
'Availability: 3.7 ',
set(),
)
def test_support_only_description_violation_and_semantic_prose_clean_case(self):
badge = (
' '
'This function supports 3d. '
)
self.assertCategories(
'Description '
'Availability: 3.7 ' + badge + ' ',
{"support-only-description"},
)
self.assertCategories(
'Description '
'Converts curves to linear geometry. ' + badge + ' ',
set(),
)
def test_documented_reference_requires_description_section(self):
entry = (
'ST_Foo '
'Returns a value. '
'integer '
'ST_Foo '
)
self.assertCategories(entry + ' ', {"missing-description"})
self.assertCategories(
entry + 'Description Returns one. ',
set(),
)
def test_tab_in_verbatim_violation_and_clean_case(self):
self.assertInfoCategory('SELECT\t1; ', "tab-in-verbatim")
self.assertCategories('1 2 ', set())
def test_admonition_must_not_contain_code_or_output_blocks(self):
self.assertCategories(
'Run this command: make check ',
{"admonition-contains-verbatim"},
)
self.assertCategories(
'Run this command: make check ',
set(),
)
def test_wide_verbatim_line_violation_and_recommendation(self):
long_sql = (
"SELECT col_a, col_b, col_c, col_d, col_e, col_f, col_g, col_h, col_i, col_j, col_k, "
"col_l, col_m, col_n FROM huge_schema.huge_table_with_very_wide_columns WHERE id > 0;"
)
findings = self.source_findings(f'{long_sql} ')
self.assertEqual({"wide-verbatim-line"}, {finding.category for finding in findings})
self.assertTrue(any("wrap" in finding.message for finding in findings))
def test_wide_verbatim_table_row_in_screen_recommends_psql_expanded_output(self):
table_row = (
" id | name | description | created_at | updated_at | extra_comment | status_comment | geometry_wkt | source_id | user_name | note | flag | tag\n"
"----+------+-------------+------------+------------+---------------+---------------+------------+----------+----------+------|----+------+"
)
findings = self.source_findings(f'{table_row} ')
self.assertEqual({"wide-output-table"}, {finding.category for finding in findings})
self.assertEqual({"info"}, {finding.severity for finding in findings})
self.assertIn("2 wide line(s)", findings[0].message)
self.assertTrue(any("psql expanded output" in finding.message for finding in findings))
def test_ragged_scalar_output_indent_violation_and_clean_cases(self):
self.assertCategories(
' 10156\n10157\n10158 ',
{"ragged-scalar-output-indent"},
)
self.assertCategories(
'10156\n10157\n10158 ',
set(),
)
self.assertCategories(
' t\n(1 row) ',
set(),
)
self.assertCategories(
' name | value\n------+------\n a | b ',
set(),
)
self.assertCategories(
' geography\n'
'----------------------------------------------------\n'
' 0101000020AD1000000000000000C05EC00000000000004140 ',
set(),
)
self.assertCategories(
' LINESTRING(0 0,\n1 1) ',
set(),
)
def test_psql_table_at_manual_width_is_not_forced_to_expanded_output(self):
table_row = (
" digits | encode | st_astext \n"
"--------+--------------------------------------------+----------------------------------------------\n"
" 13 | 01010000005e9a72083cdd5e405e9a72083cdd5e40 | POINT(123.45678912345599 123.45678912345599)"
)
self.assertCategories(f'{table_row} ', set())
def test_misaligned_psql_table_violation_and_unicode_clean_case(self):
findings = self.source_findings(
' left | right\n'
'-----+------\n'
'1 | 2 ',
)
self.assertEqual({"misaligned-psql-table"}, {finding.category for finding in findings})
self.assertEqual({"info"}, {finding.severity for finding in findings})
self.assertCategories(
'left │ right\n'
'─────┼──────\n'
'1 │ 2 ',
set(),
)
def test_wide_verbatim_line_negative_payload_and_opt_out(self):
payload = "\\x" + "0123456789abcdef" * 10
self.assertCategories(
f'{payload} ',
set(),
)
self.assertCategories(
f'{payload * 2} ',
set(),
)
def test_sql_staircase_indent_violation_and_opt_out(self):
self.assertCategories(
'SELECT x\n'
'FROM (SELECT y\n'
' FROM\n'
' table_name) AS q; ',
{"sql-staircase-indent"},
)
self.assertCategories(
'SELECT gps.track_id, ST_MakeLine(gps.geom) AS geom\n'
' FROM ( SELECT track_id, gps_time, geom\n'
' FROM gps_points ORDER BY track_id, gps_time ) AS gps\n'
' GROUP BY track_id; ',
{"sql-staircase-indent"},
)
self.assertCategories(
'SELECT p.gid,\n'
' CASE WHEN EXISTS( SELECT w.geom\n'
' FROM waterlines w\n'
' WHERE ST_Within(w.geom, p.geom))\n'
' THEN ARRAY( SELECT w.geom\n'
' FROM waterlines w)\n'
' END AS geom\n'
'FROM provinces p; ',
{"sql-staircase-indent"},
)
self.assertCategories(
'SELECT COUNT(*), squares.geom\n'
'FROM\n'
'pointtable AS pts\n'
'INNER JOIN\n'
'ST_SquareGrid(1000, pts.geom) AS squares\n'
'ON ST_Intersects(pts.geom, squares.geom) ',
{"sql-staircase-indent"},
)
self.assertCategories(
'SELECT x\n'
'FROM (\n'
' SELECT y\n'
' FROM table_name\n'
') AS q; ',
set(),
)
self.assertCategories(
'SELECT x\n'
' FROM\n'
' table_name; ',
set(),
)
def test_stacked_admonitions_violation_and_clean_case(self):
self.assertInfoCategory(
'First Second ',
"stacked-admonitions",
)
self.assertCategories(
'First Bridge Second ',
set(),
)
def test_ancient_version_note_violation_and_clean_case(self):
self.assertInfoCategory(
'Changed in PostGIS 1.5.3. ',
"ancient-version-note",
)
self.assertCategories(
'Changed in PostGIS 2.0. ',
set(),
)
def test_example_missing_output_violation_and_clean_case(self):
self.assertInfoCategory(
'Standard Examples '
'SELECT 1; No output ',
"example-missing-output",
)
self.assertCategories(
'Examples '
'SELECT 1; 1 ',
set(),
)
def test_current_function_in_examples_for_functions_and_operators(self):
self.assertCategories(
'ST_Foo '
'integer '
'ST_Foo '
'Examples SELECT ST_Foo(1); '
'1 ',
set(),
)
self.assertInfoCategory(
'ST_Foo '
'integer '
'ST_Foo '
'Examples SELECT ST_Bar(1); '
'1 ',
"current-function-in-examples",
)
self.assertCategories(
''
'&&(geometry,box2df) '
'boolean '
'&& '
'Examples SELECT a && b; '
't ',
set(),
)
self.assertInfoCategory(
''
'&&(geometry,box2df) '
'boolean '
'&& '
'Examples SELECT a @ b; '
't ',
"current-function-in-examples",
)
def test_deprecated_alias_requires_canonical_links_and_no_examples(self):
canonical = (
'CG_Foo '
'Canonical '
)
alias = (
'ST_Foo '
'Deprecated alias Description '
'Use . '
)
self.assertCategories(canonical + alias, set())
self.assertCategories(
canonical + alias + 'See . ',
{"deprecated-alias-link"},
)
self.assertCategories(
canonical + alias.replace(
'',
'Examples SELECT ST_Foo(); '
'1 ',
),
{"deprecated-alias-examples"},
)
self.assertCategories(
canonical + alias + 'Examples '
'SELECT ST_Foo(); ',
{"deprecated-alias-reference", "example-missing-output"},
)
def test_info_findings_do_not_fail_warning_gate_or_count_as_warnings(self):
path = write_tmp(".xml", DOCBOOK_OPEN + '1\t2 ' + DOCBOOK_CLOSE)
output = io.StringIO()
with contextlib.redirect_stdout(output):
self.assertEqual(0, main(["lint-source", "--fail-on", "warning", "--max-warnings", "0", str(path)]))
self.assertIn("info=1", output.getvalue())
self.assertNotIn("warning=", output.getvalue())
def test_table_polish_findings_do_not_fail_warning_gate(self):
table = (
"left | right | a_very_long_column_name_that_should_be_expanded_in_polished_docs\n"
"-----+-------+--------------------------------------------------------------------------\n"
"1 | 2 | " + "x" * 90
)
path = write_tmp(".xml", DOCBOOK_OPEN + f'{table} ' + DOCBOOK_CLOSE)
output = io.StringIO()
with contextlib.redirect_stdout(output):
self.assertEqual(0, main(["lint-source", "--fail-on", "warning", "--max-warnings", "0", str(path)]))
self.assertIn("info=", output.getvalue())
self.assertNotIn("warning=", output.getvalue())
def test_sql_token_data_drives_all_source_detectors(self):
self.assertTrue(set(SQL_STATEMENT_START_KEYWORDS).issubset(SQL_HIGHLIGHT_KEYWORDS))
self.assertTrue(set(SQL_BLOCK_STARTER_EXTRAS).issubset(SQL_HIGHLIGHT_KEYWORDS))
for keyword in SQL_STATEMENT_START_KEYWORDS:
self.assertCategories(
f'{keyword} 1;\n(1 row) ',
{"mixed-programlisting-output"},
)
self.assertCategories(
f'{keyword} 1; ',
{"screen-contains-sql"},
)
for starter in SQL_STARTERS:
body = starter if starter.endswith(";") else starter + "1;"
findings = self.html_findings_for_sql_probe(body)
self.assertTrue(any("lacks data-postgis-language='sql'" in finding.location for finding in findings), body)
def test_xsl_sql_detection_covers_all_block_starters(self):
xsl = (
Path(__file__).resolve().parents[3]
/ "doc"
/ "xsl"
/ "postgis-html-block-labels.xsl"
).read_text(encoding="utf-8")
for keyword in SQL_BLOCK_STARTER_KEYWORDS:
suffix = ";" if keyword in {"BEGIN", "COMMIT"} else " "
self.assertIn(
f"starts-with($code.text.upper, '{keyword}{suffix}')",
xsl,
f"XSL SQL detection is missing {keyword}",
)
def html_findings_for_sql_probe(self, text: str):
path = write_tmp(
"-en.html",
'
'
''
'',
)
return check_html_file(path, set())
class DocBookHtmlLintTest(unittest.TestCase):
def html_findings(self, body: str, required_kinds: set[str] | None = None):
path = write_tmp("-en.html", f"{body}")
return check_html_file(path, required_kinds or set())
def test_programlisting_wrapper_violation_and_clean_case(self):
findings = self.html_findings('SELECT 1; ')
self.assertIn("html-block-label", {finding.category for finding in findings})
self.assertEqual(
[],
self.html_findings(
''
'
Code '
'
'
'
SELECT 1; '
'
'
),
)
def test_sql_code_language_violation_and_clean_case(self):
findings = self.html_findings(
''
)
self.assertTrue(any("lacks data-postgis-language='sql'" in finding.location for finding in findings))
self.assertEqual(
[],
self.html_findings(
''
),
)
def test_screen_code_class_and_copy_button_violation_and_clean_case(self):
findings = self.html_findings(
''
)
messages = "\n".join(finding.location for finding in findings)
self.assertIn("code/highlight class tokens", messages)
self.assertIn("unexpectedly has a copy button", messages)
self.assertEqual(
[],
self.html_findings(
''
),
)
def test_expect_from_requires_source_programlisting_on_refentry_page(self):
xml = write_tmp(
".xml",
DOCBOOK_OPEN
+ 'Examples SELECT 1; '
+ DOCBOOK_CLOSE,
)
html = Path(xml.parent) / "ST_Foo.html"
html.write_text("No generated code block here.
", encoding="utf-8")
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(1, main(["lint-html", "--expect-from", str(xml), str(html)]))
def test_expect_from_does_not_require_screen_when_source_has_no_screen(self):
xml = write_tmp(
".xml",
DOCBOOK_OPEN
+ 'Examples SELECT 1; '
+ DOCBOOK_CLOSE,
)
html = Path(xml.parent) / "ST_Foo.html"
html.write_text(
''
'
Code '
'
'
'
SELECT 1; '
'
',
encoding="utf-8",
)
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(0, main(["lint-html", "--expect-from", str(xml), str(html)]))
def test_required_kinds_violation_and_clean_case(self):
self.assertTrue(self.html_findings("", {"programlisting"}))
self.assertEqual(
[],
self.html_findings(
'',
{"screen"},
),
)
def test_geometry_figure_requires_adjacent_shared_visual_stack(self):
broken = self.html_findings(
'
'
'
'
'
'
)
self.assertTrue(any("do not share visual id" in finding.location for finding in broken))
self.assertEqual([], self.html_findings(
'
'
'
'
'
'
))
class DocBookRefIndexTest(unittest.TestCase):
def test_ref_index_command_function_operator_and_clean_empty_case(self):
path = write_tmp(
".xml",
DOCBOOK_OPEN
+ 'Administration '
'Hard upgrade postgis_restore '
' '
+ 'ST_Point Makes a point '
+ '&& Overlaps '
+ DOCBOOK_CLOSE,
)
index = build_index(path)
self.assertEqual(
{
"id": "hard-upgrade",
"label": "postgis_restore",
"href": "admin.html#hard-upgrade",
"title": "Hard upgrade",
},
index["commands"]["postgis_restore"],
)
self.assertEqual("ST_Point", index["functions"]["ST_POINT"]["label"])
self.assertEqual("geometry_overlaps", index["operators"]["&&"][0]["id"])
self.assertEqual(list(SQL_HIGHLIGHT_KEYWORDS), index["keywords"])
self.assertIn("SELECT", index["keywords"])
empty_path = write_tmp(".xml", DOCBOOK_OPEN + DOCBOOK_CLOSE)
self.assertEqual(
{"commands": {}, "functions": {}, "operators": {}, "keywords": list(SQL_HIGHLIGHT_KEYWORDS)},
build_index(empty_path),
)
def test_ref_index_command_writes_json_and_script_with_same_data(self):
path = write_tmp(
".xml",
DOCBOOK_OPEN
+ 'ST_Point Makes a point '
+ DOCBOOK_CLOSE,
)
json_output = path.parent / "postgis-ref-index.json"
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(0, main(["ref-index", str(path), str(json_output)]))
expected = build_index(path)
self.assertEqual(expected, json.loads(json_output.read_text(encoding="utf-8")))
script = (path.parent / "postgis-ref-index.js").read_text(encoding="utf-8")
self.assertTrue(script.startswith("window.POSTGIS_REF_INDEX = "))
self.assertTrue(script.endswith(";\n"))
self.assertEqual(expected, json.loads(script.removeprefix("window.POSTGIS_REF_INDEX = ").removesuffix(";\n")))
def test_deprecated_alias_search_opens_canonical_page(self):
path = write_tmp(
".xml",
DOCBOOK_OPEN
+ 'CG_Foo '
'Canonical function '
+ 'ST_Foo '
'Deprecated alias for CG_Foo '
'Use . '
+ DOCBOOK_CLOSE,
)
index = build_index(path)
self.assertEqual("CG_Foo", index["functions"]["ST_FOO"]["id"])
self.assertEqual("CG_Foo.html", index["functions"]["ST_FOO"]["href"])
if __name__ == "__main__":
unittest.main()