HookTest 2.0.0rc0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hooktest/__init__.py ADDED
File without changes
hooktest/cli.py ADDED
@@ -0,0 +1,200 @@
1
+ import os.path
2
+ import sys
3
+ from typing import List
4
+ import click
5
+ import tabulate
6
+ import textwrap
7
+ from .tester import Tester, Log
8
+ from tqdm import tqdm
9
+
10
+ def to_small_caps(text):
11
+ small_caps_map = str.maketrans(
12
+ "abcdefghijklmnopqrstuvwxyz",
13
+ "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ"
14
+ )
15
+ return text.translate(small_caps_map)
16
+
17
+
18
+ class CustomLogger:
19
+ def __init__(self, level: str = "minimal"):
20
+ """
21
+
22
+ minimal
23
+ verbose
24
+
25
+ """
26
+ self._eq = {
27
+ "minimal": 10, # Only bugs and necessary info is shown
28
+ "details": 5, # Some information is kept
29
+ "verbose": 0 # Everything is shown
30
+ }
31
+ self.level = self._eq[level]
32
+ self.width = 88
33
+ self._table_indent = "\n "
34
+
35
+ def _print(self, string, level: str = "minimal", indent: int = 0, color : str = None, **kwargs):
36
+ if self._eq[level] >= self.level:
37
+ click.echo(click.style(indent*"\t"+string, fg=color, **kwargs))
38
+
39
+ def header(self, string, level: str = "minimal"):
40
+ self._print(f"\n==== {to_small_caps(string.title())} ====", level=level, bold=True)
41
+
42
+ def info(self, string, level: str = "minimal", indent: int = 0):
43
+ self._print(f"INFO: {string}", level=level, indent=indent, color="cyan")
44
+
45
+ def filter_logs(self, content: List[Log]):
46
+ return [
47
+ (
48
+ f"{log.name}: " + self.green_red(log.details or "✔", log.status) if log.status else (
49
+ f"{log.name}: " + self.green_red(
50
+ self._table_indent.join(textwrap.wrap(log.details, width=self.width)),
51
+ log.status
52
+ )
53
+ )
54
+ )
55
+ for log in content
56
+ if log.status == False or self.level <= 0
57
+ ]
58
+
59
+ def filter_append(self, haystack: List, hay, level: str = "minimal"):
60
+ if self._eq[level] >= self.level:
61
+ haystack.append(hay)
62
+
63
+ def green_red(self, string: str, status: bool):
64
+ if not status:
65
+ if self._table_indent in string:
66
+ return (click.style(" ", fg="reset")+self._table_indent).join(
67
+ click.style(substring, fg="red")
68
+ for substring in string.split(self._table_indent)
69
+ )
70
+ return click.style(string, fg="red")
71
+ elif status and self.level <= 5: # Only show green in details / verbose
72
+ return click.style(string, fg="green")
73
+ return string
74
+
75
+ def checkmark(self, status):
76
+ if status:
77
+ return self.green_red("✔", status)
78
+ return self.green_red("✗", status)
79
+
80
+ @click.command
81
+ @click.argument("files", nargs=-1, type=click.Path(file_okay=True, dir_okay=False, exists=True))
82
+ @click.option("-m", "--include-metadata-report", is_flag=True, default=False)
83
+ @click.option("-v", "--verbosity", default="minimal", type=click.Choice(["minimal", "details", "verbose"]))
84
+ @click.option("-f", "--failures-only", default=False, is_flag=True, help="Show failures only")
85
+ @click.option("-p", "--progress", default=False, is_flag=True, help="Enable progress bar")
86
+ @click.option("--catalog/--no-catalog", default=True, is_flag=True,
87
+ help="Use --no-catalog when you only one to test single files")
88
+ @click.option("-o", "--manifest", default=None, type=click.Path(dir_okay=False),
89
+ help="Write a manifest of files that passed all tests to this path")
90
+ @click.option("-s", "--schema", default=None, type=click.Path(exists=True, dir_okay=False),
91
+ help="Validate each TEI resource file against this RelaxNG (.rng) schema")
92
+ def cli(files, include_metadata_report: bool, verbosity: str, catalog: bool, progress: bool, failures_only: bool, manifest: str, schema: str):
93
+ tester = Tester(resource_schema=schema)
94
+ printer = CustomLogger(verbosity)
95
+ if catalog:
96
+ count_collections, count_resources = tester.ingest(files)
97
+ else:
98
+ count_resources = tester.ingest_tei_only(files)
99
+ count_collections = 0
100
+
101
+ catalog_results = dict(tester.results) if catalog else {}
102
+ if catalog:
103
+ printer.info(f"Found {count_collections} collection(s)")
104
+ printer.info(f"Found {count_resources} resource(s)")
105
+
106
+ #
107
+ # Collection files
108
+ #
109
+ if catalog:
110
+ printer.header("Report: Catalog files")
111
+ table = [["File", "Status", "Tests"]]
112
+ for file, result in tester.results.items():
113
+ if failures_only and result.status:
114
+ continue
115
+ printer.filter_append(
116
+ haystack=table,
117
+ hay=[
118
+ file,
119
+ printer.checkmark(result.status),
120
+ "\n".join(printer.filter_logs(result.statuses))
121
+ ],
122
+ level="minimal"
123
+ )
124
+ if failures_only and len(table) == 1:
125
+ click.echo("No error to report")
126
+ else:
127
+ click.echo(tabulate.tabulate(table, tablefmt="grid"))
128
+
129
+ #
130
+ # Metadata
131
+ #
132
+ if catalog and include_metadata_report:
133
+ printer.header("Report: Metadata")
134
+ table = [["Identifier", "Key", "Language", "Metadata"]]
135
+ for identifier, collection in tester.catalog.objects.items():
136
+ table.append([identifier, "title", "", collection.title])
137
+ if collection.description:
138
+ table.append([identifier, "description", "", collection.description])
139
+ for dc in collection.dublin_core:
140
+ table.append([identifier, f"dc:{dc.term}", dc.language or "", dc.value])
141
+ for ex in collection.extensions:
142
+ table.append([identifier, f"{ex.term}", ex.language or "", ex.value])
143
+ click.echo(tabulate.tabulate(table))
144
+
145
+ #
146
+ # Texts
147
+ #
148
+ printer.header("Report: TEI files")
149
+ table = [["File", "Status", "Tests"]]
150
+ global_status = []
151
+ for test, status in tester.tests(pbar=tqdm() if progress else None) .items():
152
+ global_status.append(status)
153
+ if (failures_only and status is False) or failures_only is False:
154
+ result = tester.results[test]
155
+ printer.filter_append(
156
+ haystack=table,
157
+ hay=[
158
+ os.path.relpath(test),
159
+ printer.checkmark(result.status),
160
+ "\n".join(printer.filter_logs(result.statuses))
161
+ ],
162
+ level="minimal"
163
+ )
164
+ if failures_only and len(table) == 1:
165
+ click.echo("No error to report")
166
+ else:
167
+ click.echo(tabulate.tabulate(table, tablefmt="grid"))
168
+
169
+ if manifest:
170
+ passing_files = [
171
+ os.path.relpath(file)
172
+ for file, result in tester.results.items()
173
+ if result.status
174
+ ]
175
+ with open(manifest, "w") as f:
176
+ f.write("\n".join(passing_files))
177
+ printer.info(f"Wrote {len(passing_files)} passing file(s) to manifest {manifest}")
178
+
179
+ printer.header("Summary")
180
+ rows = []
181
+ if catalog:
182
+ rows.append(["Collections found", count_collections])
183
+ rows.append(["Catalog files tested", len(catalog_results)])
184
+ rows.append(["Catalog files failed", sum(1 for r in catalog_results.values() if not r.status)])
185
+ rows.append(["Resources found", count_resources])
186
+ rows.append(["TEI files tested", len(global_status)])
187
+ rows.append(["TEI files passed", global_status.count(True)])
188
+ rows.append(["TEI files failed", global_status.count(False)])
189
+ click.echo(tabulate.tabulate(rows, tablefmt="simple"))
190
+
191
+ if False not in global_status:
192
+ click.echo("All tests passed")
193
+ else:
194
+ click.echo(f"{global_status.count(False)/len(global_status)*100:.2f}% of the files "
195
+ f"failed (Abs: {global_status.count(False)}/{len(global_status)})")
196
+ sys.exit(1)
197
+ return tester
198
+
199
+ if __name__ == "__main__":
200
+ cli()
@@ -0,0 +1,195 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <grammar
3
+ xmlns="http://relaxng.org/ns/structure/1.0"
4
+ xmlns:a="http://relaxng.org/ns/compatibility/annotations/1.0"
5
+ datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
6
+ <start>
7
+ <choice>
8
+ <ref name="resource"/>
9
+ <ref name="collection"/>
10
+ </choice>
11
+ </start>
12
+
13
+ <define name="identifier-and-path">
14
+ <choice>
15
+ <group>
16
+ <attribute name="identifier">
17
+ <a:documentation>Identifier of the Collection or Resource</a:documentation>
18
+ <data type="anyURI"/>
19
+ </attribute>
20
+ <optional>
21
+ <attribute name="filepath">
22
+ <a:documentation>Path to the relevant Collection or Resource</a:documentation>
23
+ <data type="anyURI"/>
24
+ </attribute>
25
+ </optional>
26
+ </group>
27
+ <!-- Link stub: the identifier lives in the linked catalog file -->
28
+ <attribute name="filepath">
29
+ <a:documentation>Path to the relevant Collection or Resource</a:documentation>
30
+ <data type="anyURI"/>
31
+ </attribute>
32
+ </choice>
33
+ </define>
34
+ <define name="parent">
35
+ <optional>
36
+ <element name="parent">
37
+ <a:documentation xml:lang="eng">Identifier of the parent if required by a parent
38
+ collection</a:documentation>
39
+ <data type="anyURI"/>
40
+ </element>
41
+ </optional>
42
+ </define>
43
+ <define name="baseDetails">
44
+ <element name="title">
45
+ <a:documentation>Title / name of a Collection or Resource</a:documentation>
46
+ <data type="string"/>
47
+ </element>
48
+ <optional>
49
+ <element name="description">
50
+ <a:documentation>Description of a Collection or Resource</a:documentation>
51
+ <data type="string"/>
52
+ </element>
53
+ </optional>
54
+ </define>
55
+ <define name="dublinCore">
56
+ <element name="dublinCore">
57
+ <interleave>
58
+ <zeroOrMore>
59
+ <element ns="http://purl.org/dc/terms/">
60
+ <a:documentation>Something</a:documentation>
61
+ <choice>
62
+ <name>abstract</name>
63
+ <name>accessRights</name>
64
+ <name>accrualMethod</name>
65
+ <name>accrualPeriodicity</name>
66
+ <name>accrualPolicy</name>
67
+ <name>alternative</name>
68
+ <name>audience</name>
69
+ <name>available</name>
70
+ <name>bibliographicCitation</name>
71
+ <name>conformsTo</name>
72
+ <name>contributor</name>
73
+ <name>coverage</name>
74
+ <name>created</name>
75
+ <name>creator</name>
76
+ <name>date</name>
77
+ <name>dateAccepted</name>
78
+ <name>dateCopyrighted</name>
79
+ <name>dateSubmitted</name>
80
+ <name>description</name>
81
+ <name>educationLevel</name>
82
+ <name>extent</name>
83
+ <name>format</name>
84
+ <name>hasFormat</name>
85
+ <name>hasPart</name>
86
+ <name>hasVersion</name>
87
+ <name>identifier</name>
88
+ <name>instructionalMethod</name>
89
+ <name>isFormatOf</name>
90
+ <name>isPartOf</name>
91
+ <name>isReferencedBy</name>
92
+ <name>isReplacedBy</name>
93
+ <name>isRequiredBy</name>
94
+ <name>issued</name>
95
+ <name>isVersionOf</name>
96
+ <name>language</name>
97
+ <name>license</name>
98
+ <name>mediator</name>
99
+ <name>medium</name>
100
+ <name>modified</name>
101
+ <name>provenance</name>
102
+ <name>publisher</name>
103
+ <name>references</name>
104
+ <name>relation</name>
105
+ <name>replaces</name>
106
+ <name>requires</name>
107
+ <name>rights</name>
108
+ <name>rightsHolder</name>
109
+ <name>source</name>
110
+ <name>spatial</name>
111
+ <name>subject</name>
112
+ <name>tableOfContents</name>
113
+ <name>temporal</name>
114
+ <name>title</name>
115
+ <name>type</name>
116
+ <name>valid</name>
117
+ </choice>
118
+ <optional>
119
+ <attribute name="xml:lang">
120
+ <data type="language"/>
121
+ </attribute>
122
+ </optional>
123
+ <data type="string"/>
124
+ </element>
125
+ </zeroOrMore>
126
+ </interleave>
127
+ </element>
128
+
129
+ </define>
130
+ <define name="extension">
131
+ <element>
132
+ <a:documentation>Structured metadata contains any other optional metadata that are not part of
133
+ DublinCore Terms namespace</a:documentation>
134
+ <name>extensions</name>
135
+ <zeroOrMore>
136
+ <element>
137
+ <anyName>
138
+ <except>
139
+ <nsName ns="http://purl.org/dc/terms/"/>
140
+ </except>
141
+ </anyName>
142
+ <optional>
143
+ <attribute name="xml:lang">
144
+ <data type="language"/>
145
+ </attribute>
146
+ </optional>
147
+ <text/>
148
+ </element>
149
+ </zeroOrMore>
150
+ </element>
151
+ </define>
152
+ <define name="members">
153
+ <a:documentation>Children member of a collection or ressource</a:documentation>
154
+ <element>
155
+ <name>members</name>
156
+ <interleave>
157
+ <oneOrMore>
158
+ <choice>
159
+ <ref name="collection"/>
160
+ <ref name="resource"/>
161
+ </choice>
162
+ </oneOrMore>
163
+ </interleave>
164
+ </element>
165
+ </define>
166
+ <define name="collection-pattern">
167
+ <ref name="identifier-and-path"/>
168
+ <ref name="parent"/>
169
+ <optional>
170
+ <ref name="baseDetails"/>
171
+ </optional>
172
+ <optional>
173
+ <ref name="dublinCore"/>
174
+ </optional>
175
+ <optional>
176
+ <ref name="extension"/>
177
+ </optional>
178
+ <optional>
179
+ <ref name="members"/>
180
+ </optional>
181
+ <optional>
182
+ <ref name="parent"/>
183
+ </optional>
184
+ </define>
185
+ <define name="resource">
186
+ <element name="resource">
187
+ <ref name="collection-pattern"/>
188
+ </element>
189
+ </define>
190
+ <define name="collection">
191
+ <element name="collection">
192
+ <ref name="collection-pattern"/>
193
+ </element>
194
+ </define>
195
+ </grammar>
hooktest/tester.py ADDED
@@ -0,0 +1,626 @@
1
+ import dataclasses
2
+ import difflib
3
+ import os.path
4
+ import re
5
+ from collections import Counter
6
+ from typing import Dict, List, Optional, Tuple, Union
7
+
8
+ import tqdm
9
+ from dapytains.errors import UnresolvableReference
10
+ from dapytains.processor import get_xpath_proc
11
+ from dapytains.metadata.classes import Collection
12
+ from dapytains.tei.citeStructure import CitableUnit, CitableStructure, CiteStructureParser
13
+ from dapytains.tei.document import Document, xpath_eval
14
+ from dapytains.metadata.xml_parser import parse, Catalog
15
+ from lxml import etree as ET
16
+
17
+
18
+ # Monkey patch for test
19
+ def _dispatch(self, child_xpath: str, structure: CitableStructure, xpath_processor, unit: CitableUnit, level: int):
20
+ # A self-closing unit (<pb/>, <milestone/>) owns the following siblings up to the next one:
21
+ # dapytains needs its match to bound them, otherwise it looks for children inside the empty element.
22
+ milestone_match = structure.match if structure.milestone else None
23
+ if len(structure.children) == 1:
24
+ for element in xpath_eval(xpath_processor, child_xpath):
25
+ self.find_refs(
26
+ root=element,
27
+ structure=structure.children[0],
28
+ unit=unit,
29
+ level=level,
30
+ milestone_match=milestone_match
31
+ )
32
+ else:
33
+ for element in xpath_eval(xpath_processor, child_xpath):
34
+ self.find_refs_from_branches(
35
+ root=element,
36
+ structure=structure.children,
37
+ unit=unit,
38
+ level=level,
39
+ milestone_match=milestone_match
40
+ )
41
+ CiteStructureParser._dispatch = _dispatch
42
+
43
+ @dataclasses.dataclass
44
+ class Log:
45
+ name: str
46
+ status: bool
47
+ exception: Optional[Union[Exception, str]] = None
48
+ details: Optional[str] = None
49
+
50
+ def __repr__(self):
51
+ return f"<Log class='{self.name}' status={self.status}>{self.details}</Log>"
52
+
53
+ @dataclasses.dataclass
54
+ class Result:
55
+ target: str
56
+ statuses: List[Log] = dataclasses.field(default_factory=list)
57
+
58
+ @property
59
+ def status(self):
60
+ for s in self.statuses:
61
+ if not s.status:
62
+ return False
63
+ return True
64
+
65
+ def __repr__(self):
66
+ NL = "\n"
67
+ TB = "\t"
68
+ return f"<Result target='{self.target}'>\n\t{NL.join([TB+repr(log) for log in self.statuses])}\n</Result>"
69
+
70
+
71
+ def _count_tree(units: List[CitableUnit], types = None) -> str:
72
+ types = types if types is not None else {}
73
+ for element in units:
74
+ if element.citeType not in types:
75
+ types[element.citeType] = {
76
+ "count": 0,
77
+ "children": {}
78
+ }
79
+ types[element.citeType]["count"] += 1
80
+ _count_tree(element.children, types[element.citeType]["children"])
81
+ return types
82
+
83
+
84
+ def _stringify_tree_count(tree) -> str:
85
+ return ", ".join([
86
+ f"{level}({details['count']})" + (
87
+ f"->[{_stringify_tree_count(details['children'])}]" if details["children"]
88
+ else ""
89
+ )
90
+ for level, details in tree.items()
91
+ ])
92
+
93
+ def check_naming_type(struct: CitableStructure) -> Tuple[bool, List[str]]:
94
+ citeType = re.match(r"^\w+$", struct.citeType)
95
+ children = [
96
+ check_naming_type(child)
97
+ for child in struct.children
98
+ ]
99
+ if not citeType:
100
+ return False, [f"`{struct.citeType}`"]
101
+ else:
102
+ return False not in [a for a,b in children], [t for a, b in children for t in b]
103
+
104
+ def _parse_for_check(filepath: str, check_name: str):
105
+ """ Parse `filepath` for one of the pre-dapytains, lxml-only structural checks.
106
+
107
+ :returns: (tree, None) on success, (None, failing Log) when the file cannot be parsed.
108
+ """
109
+ try:
110
+ return ET.parse(filepath), None
111
+ except Exception as E:
112
+ return None, Log(
113
+ check_name, False,
114
+ details=f"Unable to parse XML to check {check_name} ({type(E).__name__}: {E})"
115
+ )
116
+
117
+
118
+ def _direct_cite_structures(parent) -> List:
119
+ """ Direct citeStructure children of `parent`, skipping comments and processing
120
+ instructions (which have no QName and would crash ET.QName). """
121
+ return [
122
+ child for child in parent
123
+ if isinstance(child.tag, str) and ET.QName(child).localname == "citeStructure"
124
+ ]
125
+
126
+
127
+ def check_citestructure_delims(filepath: str) -> Log:
128
+ """ dapytains requires every citeStructure nested within another citeStructure
129
+ to carry a @delim attribute (the top-level citeStructure(s) of a refsDecl do not,
130
+ since there is no parent reference to prepend a delimiter to). A missing @delim
131
+ on a non-top citeStructure crashes dapytains' regex building with a cryptic
132
+ TypeError, so we check for it upfront with a clear message.
133
+ """
134
+ tree, error = _parse_for_check(filepath, "citeStructure/@delim")
135
+ if tree is None:
136
+ return error
137
+
138
+ missing = []
139
+ # iter() on a tag pattern skips comments and processing instructions, which have no
140
+ # QName and used to crash this check.
141
+ for el in tree.iter("{*}citeStructure"):
142
+ parent = el.getparent()
143
+ if parent is not None and ET.QName(parent).localname == "citeStructure" and not el.get("delim"):
144
+ missing.append(el.get("unit") or "?")
145
+
146
+ status = len(missing) == 0
147
+ return Log(
148
+ "citeStructure/@delim",
149
+ status,
150
+ details=(
151
+ "Non-top citeStructure(s) are missing the required @delim attribute "
152
+ f"(unit(s): {', '.join(missing)})"
153
+ ) if not status else None
154
+ )
155
+
156
+ def check_ignored_citestructure(filepath: str) -> Log:
157
+ """ dapytains only ever reads the *first* citeStructure of a refsDecl
158
+ (`./citeStructure[1]`, in CiteStructureParser.__init__) and then recurses through that
159
+ element's own `./citeStructure` children. Any further citeStructure sitting directly
160
+ under the refsDecl is silently dropped: no XPath is ever built or evaluated for it, so
161
+ nothing raises. The citation tree is simply one level shallower than the file looks.
162
+
163
+ The usual cause is a self-closed parent -- `<citeStructure ... />` followed by an
164
+ indented sibling that was meant to be nested inside it. The failure is quiet and easy to
165
+ miss: top-level references keep resolving, while deeper ones return nothing, because the
166
+ one surviving unit's regex (`.+`) then swallows the delimiters as part of its own value.
167
+ """
168
+ tree, error = _parse_for_check(filepath, "citeStructure/ignored")
169
+ if tree is None:
170
+ return error
171
+
172
+ ignored = [
173
+ (extra.get("unit") or "?", extra.get("match") or "?", extra.sourceline)
174
+ for refs_decl in tree.iter("{*}refsDecl")
175
+ for extra in _direct_cite_structures(refs_decl)[1:]
176
+ ]
177
+
178
+ status = len(ignored) == 0
179
+ return Log(
180
+ "citeStructure/ignored",
181
+ status,
182
+ details=(
183
+ "citeStructure(s) never read by dapytains, which only uses the first "
184
+ "citeStructure of each refsDecl: "
185
+ + "; ".join([
186
+ f"unit `{unit}` (match `{match}`, line {line})"
187
+ for unit, match, line in ignored
188
+ ])
189
+ + ". Nest it inside the preceding citeStructure (which is probably self-closed) "
190
+ "or move it to its own refsDecl."
191
+ ) if not status else None
192
+ )
193
+
194
+
195
+ def _get_delim(s: CitableStructure) -> List[str]:
196
+ return ([s.delim] if s.delim else []) + [d for c in s.children for d in _get_delim(c)]
197
+
198
+ def _check_refs(
199
+ document: Document,
200
+ structure: CitableStructure,
201
+ previous_delim: Optional[List[str]] = None,
202
+ base_xpath: str = ""
203
+ ) -> List[Tuple[str, str, str]]:
204
+ if not previous_delim:
205
+ previous_delim = _get_delim(structure)
206
+
207
+ xproc = get_xpath_proc(document.xml, processor=document.xml_processor)
208
+ returns: List[Tuple[str, str, str]] = []
209
+
210
+ # There is a limit here to this approach
211
+ # ToDo: Have something to deal with structure.xpath where we ensure that parents have the @n ???
212
+ xpath = "/".join([base_xpath, structure.xpath]) if base_xpath else structure.xpath
213
+ xpath_match = "/".join([base_xpath, structure.xpath_match]) if base_xpath else structure.xpath_match
214
+
215
+ for reff in xpath_eval(xproc, xpath):
216
+ reff = reff.get_string_value()
217
+ for delim in previous_delim:
218
+ if delim in reff:
219
+ returns.append((xpath, reff, delim))
220
+
221
+ for child in structure.children:
222
+ returns.extend(_check_refs(document, child, previous_delim, xpath_match))
223
+
224
+ return returns
225
+
226
+
227
+ def _join_xpath(base: str, xpath: str) -> str:
228
+ """ Join a parent match with a child match. A child match can be written ".//x" or "//x",
229
+ both of which must end up as a single descendant step. """
230
+ if not base:
231
+ return xpath
232
+ return f"{base}/{xpath}".replace("///", "//")
233
+
234
+
235
+ def _absolute_path(document: Document, node) -> str:
236
+ """ Positional XPath of a concrete node (e.g. /TEI[1]/text[1]/body[1]/div[8]), so a report
237
+ points at one element rather than at the whole match. """
238
+ return str(get_xpath_proc(node, processor=document.xml_processor).evaluate_single(
239
+ "string-join(for $n in (ancestor-or-self::*) "
240
+ "return concat('/', name($n), '[', 1 + count($n/preceding-sibling::*[name() = name($n)]), ']'), '')"
241
+ ))
242
+
243
+
244
+ def _bare_match(structure: CitableStructure) -> str:
245
+ """ The element match of a citeStructure, without the `[@n]`-style predicate dapytains
246
+ appends to it: that predicate hides the very elements we want to report, the ones missing
247
+ their @use attribute altogether. """
248
+ match = getattr(structure, "match", "")
249
+ if match:
250
+ return match
251
+ suffix = f"[{structure.use}]"
252
+ if structure.xpath_match.endswith(suffix):
253
+ return structure.xpath_match[:-len(suffix)]
254
+ return structure.xpath_match
255
+
256
+
257
+ def _check_empty_values(
258
+ document: Document,
259
+ structure: CitableStructure,
260
+ base_xpath: str = ""
261
+ ) -> List[Tuple[str, str, str]]:
262
+ """ Find matched nodes carrying an empty citeStructure/@use value (typically a
263
+ `<div n="">` left behind by a conversion). Such a node yields an empty reference, which
264
+ dapytains cannot cite, cannot resolve, and which takes down every unit nested under it.
265
+
266
+ A node missing the attribute entirely is not reported: dapytains matches on `[@use]`, so
267
+ it is simply not part of the citation tree (a bare `<lb/>` inside a heading, say), which
268
+ is legitimate encoding rather than broken data.
269
+
270
+ :returns: List of (citeType, positional xpath of the node, human readable reason)
271
+ """
272
+ xproc = get_xpath_proc(document.xml, processor=document.xml_processor)
273
+ returns: List[Tuple[str, str, str]] = []
274
+
275
+ match = _join_xpath(base_xpath, _bare_match(structure))
276
+
277
+ if structure.use != "position()":
278
+ for node in xpath_eval(xproc, match):
279
+ local = get_xpath_proc(node, processor=document.xml_processor)
280
+ if str(local.evaluate_single(f"string({structure.use})")):
281
+ continue
282
+ # Matched on the bare match, so that nodes nested under an uncited one are still
283
+ # inspected; only an attribute that is present and empty is a defect.
284
+ if local.effective_boolean_value(f"boolean({structure.use})"):
285
+ returns.append((
286
+ structure.citeType,
287
+ _absolute_path(document, node),
288
+ f"`{structure.use}` is empty"
289
+ ))
290
+
291
+ for child in structure.children:
292
+ # Children of a milestone (e.g. <lb/> under <cb/>) are siblings of it, not descendants:
293
+ # scoping them under their parent's match would match nothing. `milestone` only exists
294
+ # in newer dapytains releases, hence the getattr.
295
+ milestone = getattr(structure, "milestone", False)
296
+ returns.extend(_check_empty_values(document, child, "" if milestone else match))
297
+
298
+ return returns
299
+
300
+
301
+ def _duplicate_xpath(citation_tree, reference: str) -> Optional[str]:
302
+ """ XPath of a duplicated `reference`, or None when dapytains cannot resolve it: under a
303
+ milestone parent, resolution follows the first occurrence of each parent, so a child that only
304
+ exists under a later occurrence (e.g. a PG column the text comes back to) has no node. """
305
+ try:
306
+ return citation_tree.generate_xpath(reference)
307
+ except UnresolvableReference:
308
+ return None
309
+
310
+
311
+ def _check_dbl_refs(
312
+ document: Document,
313
+ tree: str
314
+ ) -> List[Tuple[str, str, int]]:
315
+ """ Duplicates are counted within each list of siblings (the children of one unit), not over the
316
+ flattened tree: a duplicated parent carries the same children list once per match, which would
317
+ over-report them. The children of a self-closing unit (<lb/> under <pb/>) have no XPath of their
318
+ own that matches them all (dapytains returns the position of the first one), so the sibling count
319
+ is kept when the XPath finds fewer nodes. """
320
+ returns: Dict[str, Tuple[str, str, int]] = {}
321
+
322
+ def walk(units: List[CitableUnit]):
323
+ for reference, sibling_count in Counter(u.ref for u in units).items():
324
+ if sibling_count > 1 and reference not in returns:
325
+ xpath = _duplicate_xpath(document.citeStructure[tree], reference)
326
+ if xpath is None:
327
+ returns[reference] = ("unresolvable under a repeated milestone", f"`{reference}`", sibling_count)
328
+ continue
329
+ count = max(sibling_count, len(list(xpath_eval(document.xpath_processor, xpath))))
330
+ returns[reference] = (xpath, f"`{reference}`", count)
331
+ for u in units:
332
+ walk(u.children)
333
+
334
+ walk(document.get_reffs(tree))
335
+ return list(returns.values())
336
+
337
+
338
+ class Tester:
339
+ """ Tester class, allows for retrieving results outside of the CLI
340
+ """
341
+ def __init__(self, resource_schema: Optional[str] = None):
342
+ self.catalog = Catalog()
343
+ self.results: Dict[str, Result] = {}
344
+
345
+ # Load the Relax NG schema
346
+ self.catalog_schema = ET.RelaxNG(
347
+ ET.parse(
348
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "collection-schema.rng")
349
+ )
350
+ )
351
+
352
+ # Optional user-supplied schema to validate TEI resource files against
353
+ self.resource_schema: Optional[ET.RelaxNG] = (
354
+ ET.RelaxNG(ET.parse(resource_schema)) if resource_schema else None
355
+ )
356
+
357
+ def _validate_against_schema(self, schema: ET.RelaxNG, filepath: str) -> Log:
358
+ try:
359
+ status = schema.validate(ET.parse(filepath))
360
+ details = []
361
+ if not status:
362
+ for el in schema.error_log:
363
+ details.append(":".join(str(el).split("\n")[0].split(":")[6:]).strip())
364
+ return Log("schema", status, details="; ".join(details))
365
+ except Exception as E:
366
+ return Log(
367
+ "schema", False,
368
+ details=f"Unable to validate against schema ({type(E).__name__}: {E}); check the file is well-formed XML"
369
+ )
370
+
371
+ @staticmethod
372
+ def _catalog_hints(filepath: str) -> List[str]:
373
+ """ RelaxNG reports an unexpected child of a collection/resource as "extra content" on the
374
+ *following* sibling (e.g. `<extension>` is flagged as an error on `<title>`). Name the real culprit.
375
+ """
376
+ allowed = ["parent", "title", "description", "dublinCore", "extensions", "members"]
377
+ hints = []
378
+ try:
379
+ root = ET.parse(filepath).getroot()
380
+ except Exception:
381
+ return hints
382
+ for node in root.iter("collection", "resource"):
383
+ where = node.get("identifier") or node.get("filepath") or node.tag
384
+ for child in node:
385
+ if not isinstance(child.tag, str):
386
+ continue
387
+ if child.tag not in allowed:
388
+ close = difflib.get_close_matches(child.tag, allowed, n=1)
389
+ hint = f" (did you mean <{close[0]}>?)" if close else ""
390
+ hints.append(
391
+ f"line {child.sourceline}: unexpected <{child.tag}> in {node.tag} {where}{hint}; "
392
+ f"allowed: {', '.join(allowed)}"
393
+ )
394
+ for child in node.findall("dublinCore/*"):
395
+ if isinstance(child.tag, str) and not child.tag.startswith("{http://purl.org/dc/terms/}"):
396
+ hints.append(
397
+ f"line {child.sourceline}: <{ET.QName(child).localname}> in <dublinCore> must be in the "
398
+ f"http://purl.org/dc/terms/ namespace"
399
+ )
400
+ return hints
401
+
402
+ def run_catalog_schema(self, filepath) -> Log:
403
+ log = self._validate_against_schema(self.catalog_schema, filepath)
404
+ if not log.status:
405
+ hints = self._catalog_hints(filepath)
406
+ if hints:
407
+ log.details = "; ".join(hints) + (f" [RelaxNG: {log.details}]" if log.details else "")
408
+ return log
409
+
410
+ def ingest_tei_only(self, files: List[str]) -> int:
411
+ """ Ingest TEI Files as resources (does not require catalogs)
412
+
413
+ :param files: TEI files following the Dapitains structure
414
+ :returns: Number of resources found
415
+ """
416
+ self.catalog.objects = {
417
+ os.path.relpath(file): Collection(
418
+ title=os.path.relpath(file),
419
+ identifier=os.path.relpath(file),
420
+ filepath=os.path.relpath(file),
421
+ resource=True
422
+ )
423
+ for file in files
424
+ }
425
+ return len(self.catalog.objects)
426
+
427
+ def ingest(self, files: List[str]) -> Tuple[int, int]:
428
+ """ Ingest catalog(s) files to test resources
429
+
430
+ :param files: Catalog files following the Dapitains structure
431
+ :returns: Number of collections found, number of resources found
432
+ """
433
+
434
+ for file in files:
435
+ file = os.path.relpath(file)
436
+ try:
437
+ before = len(self.catalog.relationships)
438
+ _, collection = parse(file, self.catalog)
439
+ except Exception as E:
440
+ self.results[file] = Result(
441
+ file, [Log(
442
+ "parse", False,
443
+ details=f"Unable to parse catalog file ({type(E).__name__}: {E}); "
444
+ f"check it is well-formed XML following the Dapytains catalog structure"
445
+ )]
446
+ )
447
+ continue
448
+ self.results[file] = Result(
449
+ file, [
450
+ Log("parse", True),
451
+ Log(
452
+ "relationships", True,
453
+ details="+ {0} element(s)".format(len(self.catalog.relationships) - before)
454
+ ),
455
+ Log(
456
+ "children", True,
457
+ details="{0} child(ren)".format(len([
458
+ pair
459
+ for pair in self.catalog.relationships
460
+ if collection.identifier in pair
461
+ ]))
462
+ ),
463
+ self.run_catalog_schema(file)
464
+ ]
465
+ )
466
+ for collection in self.catalog.objects.values():
467
+ if collection._metadata_filepath:
468
+ file = os.path.relpath(collection._metadata_filepath)
469
+ if file in self.results:
470
+ continue
471
+ self.results[file] = Result(
472
+ file, [self.run_catalog_schema(file)]
473
+ )
474
+ return len(self.catalog.objects), len([o for o in self.catalog.objects.values() if o.resource])
475
+
476
+ def tests(self, pbar: Optional[tqdm.tqdm] = None) -> Dict[str, bool]:
477
+ resources = [o for o in self.catalog.objects.values() if o.resource]
478
+ passing: Dict[str, bool] = {}
479
+ for r in resources:
480
+ passing[r.filepath] = True
481
+ delim_log = check_citestructure_delims(r.filepath)
482
+ ignored_log = check_ignored_citestructure(r.filepath)
483
+ self.results[r.filepath] = Result(r.filepath, [delim_log, ignored_log])
484
+ if not delim_log.status or not ignored_log.status:
485
+ passing[r.filepath] = False
486
+
487
+ if self.resource_schema is not None:
488
+ schema_log = self._validate_against_schema(self.resource_schema, r.filepath)
489
+ self.results[r.filepath].statuses.append(schema_log)
490
+ if not schema_log.status:
491
+ passing[r.filepath] = False
492
+
493
+ try:
494
+ doc = Document(r.filepath)
495
+ except Exception as E:
496
+ self.results[r.filepath].statuses.append(
497
+ Log(
498
+ "parse", False,
499
+ details=f"Unable to build a document/citeStructure model from this file "
500
+ f"({type(E).__name__}: {E}); check the TEI is well-formed XML with a "
501
+ f"valid refsDecl/citeStructure"
502
+ )
503
+ )
504
+ passing[r.filepath] = False
505
+ continue
506
+
507
+ self.results[r.filepath].statuses.extend([
508
+ Log("parse", True),
509
+ Log("parse(refsDecl/@n)", True, details=f"Tree(s) found: {len(doc.citeStructure)}")
510
+ ])
511
+ try:
512
+ working_tree = {}
513
+ for tree in doc.citeStructure:
514
+ s, details = check_naming_type(doc.citeStructure[tree].structure)
515
+ self.results[r.filepath].statuses.append(
516
+ Log("citeStructure/@unit", s, details=f"citeType must be matching the regex ^\\w+$. Problematic names: {', '.join(details)}" if not s else None)
517
+ )
518
+ working_tree[tree] = s
519
+ passing[r.filepath] = passing[r.filepath] and s
520
+
521
+ # Checked before get_reffs(): an empty value raises there, with no way to tell
522
+ # which element is at fault.
523
+ empty_trees = set()
524
+ for tree in doc.citeStructure:
525
+ empty_values = _check_empty_values(doc, doc.citeStructure[tree].structure)
526
+ self.results[r.filepath].statuses.append(Log(
527
+ f"emptyRefs[Tree={tree}]",
528
+ len(empty_values) == 0,
529
+ details="" if len(empty_values) == 0 else (
530
+ "Matched node(s) cannot be cited, their @use value is unusable: "
531
+ + "; ".join([
532
+ f"{citeType} at `{path}` ({reason})"
533
+ for citeType, path, reason in empty_values
534
+ ])
535
+ )
536
+ ))
537
+ if not self.results[r.filepath].statuses[-1].status:
538
+ passing[r.filepath] = False
539
+ working_tree[tree] = False
540
+ empty_trees.add(tree)
541
+
542
+ reffs = {}
543
+ try:
544
+ # Now check the reference / structure
545
+ # A tree with an empty value cannot be walked (get_reffs raises on it):
546
+ # it is already reported above, no need for a second, vaguer failure.
547
+ reffs = {
548
+ tree: doc.get_reffs(tree)
549
+ for tree in doc.citeStructure
550
+ if tree not in empty_trees
551
+ }
552
+ self.results[r.filepath].statuses.append(
553
+ Log(
554
+ "parse(citeStructures)",
555
+ True,
556
+ details="\n".join([
557
+ f"Tree:{tree}->{_stringify_tree_count(_count_tree(reffs[tree]))}"
558
+ for tree in reffs
559
+ ])
560
+ )
561
+ )
562
+ except Exception:
563
+ self.results[r.filepath].statuses.append(
564
+ Log(
565
+ "citeStructures",
566
+ False,
567
+ details="Unable to get reffs from citeStructure"
568
+ )
569
+ )
570
+ passing[r.filepath] = False
571
+ if reffs:
572
+ bad_refs = {}
573
+ double_refs = {}
574
+ for tree in reffs:
575
+ if not working_tree[tree]:
576
+ continue
577
+ bad_refs[tree] = {}
578
+ double_refs[tree] = {}
579
+ for xpath, *values in _check_refs(doc, doc.citeStructure[tree].structure):
580
+ if xpath not in bad_refs:
581
+ bad_refs[tree][xpath] = []
582
+ bad_refs[tree][xpath].append(values)
583
+
584
+ for xpath, value, count in _check_dbl_refs(doc, tree):
585
+ double_refs[tree][xpath] = (value, count)
586
+
587
+ self.results[r.filepath].statuses.append(Log(
588
+ f"forbiddenRefs[Tree={tree}]",
589
+ len(bad_refs[tree]) == 0,
590
+ details="" if len(bad_refs[tree]) == 0 else (
591
+ "Reference(s) contain[s] a delimiter, which will break parsing: " + "; ".join([
592
+ f"At xpath `{xpath}`: " + ", ".join([
593
+ f"`{ref}` (Delim: `{delim}`)"
594
+ for ref, delim in bad_refs[tree][xpath]
595
+ ]) for xpath in bad_refs[tree]
596
+ ])
597
+ )
598
+ ))
599
+ if not self.results[r.filepath].statuses[-1].status:
600
+ passing[r.filepath] = False
601
+
602
+ self.results[r.filepath].statuses.append(Log(
603
+ f"duplicateRefs[Tree={tree}]",
604
+ len(double_refs[tree]) == 0,
605
+ details="" if len(double_refs[tree]) == 0 else (
606
+ "Reference(s) at following XPath(s) are found more than once: " + "; ".join([
607
+ f"Reference {ref} (×{count}, xPath: `{xpath}`): " for xpath, (ref, count) in double_refs[tree].items()
608
+ ])
609
+ )
610
+ ))
611
+ if not self.results[r.filepath].statuses[-1].status:
612
+ passing[r.filepath] = False
613
+ except Exception as E:
614
+ self.results[r.filepath].statuses.append(
615
+ Log(
616
+ "error", False,
617
+ details=f"Unexpected error while checking citeStructure references "
618
+ f"({type(E).__name__}: {E})"
619
+ )
620
+ )
621
+ passing[r.filepath] = False
622
+ if pbar is not None:
623
+ pbar.update(1)
624
+ return passing
625
+
626
+
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: hooktest
3
+ Version: 2.0.0rc0
4
+ Summary: Library for testing CiteStructure data, using Dapitains library
5
+ Author-email: Thibault Clérice <leponteineptique@gmail.com>
6
+ License-Expression: MPL-2.0
7
+ Project-URL: Homepage, http://github.com/cllg/hooktest
8
+ Classifier: Topic :: Software Development :: Quality Assurance
9
+ Classifier: Topic :: Software Development :: Testing
10
+ Classifier: Topic :: Software Development :: Version Control
11
+ Classifier: Topic :: Text Processing :: Markup :: XML
12
+ Classifier: Topic :: Text Processing :: General
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Python: >=3.12
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: dapytains>=1.0.0rc5
20
+ Requires-Dist: click<9.0.0,>=8.1.8
21
+ Requires-Dist: colorama~=0.4.6
22
+ Requires-Dist: tabulate~=0.9.0
23
+ Requires-Dist: tqdm
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == "test"
26
+ Requires-Dist: pytest-cov; extra == "test"
27
+ Requires-Dist: requests-mock; extra == "test"
28
+
29
+ ![Header for HookTest](images/header.png)
30
+
31
+ [![License: MPL 2.0](https://img.shields.io/badge/License-MPL%202.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0)
32
+ [![Software Test](https://github.com/cllg-project/hooktest/actions/workflows/test.yml/badge.svg)](https://github.com/cllg-project/hooktest/actions/workflows/test.yml)
33
+
34
+ Dapytains provides a server-side or client-side library to deal with
35
+ [Distributed Text Services APIs](https://distributed-text-services.github.io/) as well as
36
+ TEI XML files using the [CiteStructure](https://tei-c.org/release/doc/tei-p5-doc/en/html/ref-citeStructure.html)
37
+ encoding of their machine actionable architecture, allowing to split and retrieve reference in a file
38
+ "without human intervention".
39
+
40
+ HookTestv2, which replaces the original [HookTest](https://hal.science/hal-01709868/), allows for testing those file,
41
+ including tests for catalog registry.
42
+
43
+ **This software is still quite in alpha mode, feel free to report bugs**
44
+
45
+ ## How to install
46
+
47
+ ```sh
48
+ pip install --pre hooktest
49
+ ```
50
+
51
+ Or from source:
52
+
53
+ ```sh
54
+ git clone https://github.com/cllg-project/hooktest.git
55
+ cd hooktest
56
+ pip install .
57
+ ```
58
+
59
+ ## How to run
60
+
61
+ If you want to test a system where you have a root catalog file, you can run `hooktest path/to/your/catalog.xml`
62
+ where catalog are using [`hooktest/resources/collection-schema.rng`](hooktest/resources/collection-schema.rng).
63
+
64
+ Otherwise, run `hooktest --no-catalog /path/to/your/tei/files.xml`.
65
+
66
+
67
+ ## Support
68
+
69
+ Funded via the CLLG Project.
70
+
71
+ Ce travail a bénéficié d’une aide de l’État gérée par l’Agence Nationale de la
72
+ Recherche au titre de France 2030 portant la référence « ANR-24-RRII- 0002 » et opéré par
73
+ le Programme Inria Quadrant.
@@ -0,0 +1,9 @@
1
+ hooktest/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ hooktest/cli.py,sha256=LqQrT1CJ0pVXDL3g9-fAlSU6VLLnGvlfRVSI_fqRQdQ,7882
3
+ hooktest/tester.py,sha256=LW0Cb8yEvDlr5tfPfVZE73MZiTQJI0-Qne46fd2GKRc,27192
4
+ hooktest/resources/collection-schema.rng,sha256=j0_ulbHnH5Hg99i9o0qQFsfBYbYieO6y_2GgG8i4s4Q,7525
5
+ hooktest-2.0.0rc0.dist-info/METADATA,sha256=nOGwmOu5WEbrY-RjmYcf2GLRoxX7T1-gmabz1jcy7SE,2828
6
+ hooktest-2.0.0rc0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ hooktest-2.0.0rc0.dist-info/entry_points.txt,sha256=ipPWFI95t9rHU1YGShJ5qgjNiIjXVgbUDUt1YlBnnjk,46
8
+ hooktest-2.0.0rc0.dist-info/top_level.txt,sha256=FziSTdFjWlXB41Gu1DavXpkmrImDZY1TViIp7MtffXY,9
9
+ hooktest-2.0.0rc0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hooktest = hooktest.cli:cli
@@ -0,0 +1 @@
1
+ hooktest