This is an automated email from the ASF dual-hosted git repository.

jimjag pushed a commit to branch odf-devel
in repository https://gitbox.apache.org/repos/asf/openoffice.git

commit 5b8dded923053ba1991dc727b1c512090ac5ab81
Author: Jim Jagielski <[email protected]>
AuthorDate: Mon Oct 26 11:41:35 2026 -0400

    test/odf-validate: check xml:id and namespaces, resume after a jing fatal 
error
    
    A fatal jing error ended its whole 400-file batch, so the files after it
    were never validated.
---
 test/odf-validate/README.md        |  5 +++
 test/odf-validate/idcheck.py       | 83 ++++++++++++++++++++++++++++++++++++++
 test/odf-validate/make-controls.py |  6 +++
 test/odf-validate/selftest.py      | 11 +++++
 test/odf-validate/validate.py      |  9 ++++-
 5 files changed, 112 insertions(+), 2 deletions(-)

diff --git a/test/odf-validate/README.md b/test/odf-validate/README.md
index fbcb6c3731..6411dc92cd 100644
--- a/test/odf-validate/README.md
+++ b/test/odf-validate/README.md
@@ -46,6 +46,9 @@ The steps:
   Embedded objects whose `content.xml` is MathML are skipped (ODF 1.2 Part 1
   §2.2.1 B.4).
 - `report.py` groups the errors by normalized message.
+- `idcheck.py <outdir> <ids.json>` parses every stream namespace-aware and
+  checks `xml:id` syntax and uniqueness per stream (ODF 1.2 Part 1 §2.2.1
+  D.1, D.2). `jing -i` does not check ID uniqueness.
 
 ## Checking a change
 
@@ -67,5 +70,7 @@ expressions with expected values; `--capture <out.json>` 
records them instead.
 - jing must run with `-i`, otherwise it rejects the ODF schemas themselves.
 - A jing fatal error can hide later errors. Such lines are reported as
   `UNPARSED` kinds, and `compare.py` fails on any new `UNPARSED` kind.
+- jing stops at a fatal error (a stream that is not well-formed);
+  `validate.py` records it and carries on with the remaining files.
 - `setup-app.sh` renames an existing `app/OpenOffice.app` to
   `OpenOffice.app.old.<timestamp>` instead of deleting it.
diff --git a/test/odf-validate/idcheck.py b/test/odf-validate/idcheck.py
new file mode 100644
index 0000000000..63e798c809
--- /dev/null
+++ b/test/odf-validate/idcheck.py
@@ -0,0 +1,83 @@
+#**************************************************************
+#
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing,
+#  software distributed under the License is distributed on an
+#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#  KIND, either express or implied.  See the License for the
+#  specific language governing permissions and limitations
+#  under the License.
+#
+#**************************************************************
+
+# usage: idcheck.py <outdir> <ids.json>
+# ODF 1.2 Part 1 2.2.1 D.1 and D.2, which `jing -i` does not check: each XML 
stream is
+# parsed namespace-aware, and its xml:id values must be NCNames, unique within 
the stream.
+import sys, os, re, zipfile, json
+from xml.parsers import expat
+
+D = os.path.dirname(os.path.abspath(__file__))
+STREAMS = {"content.xml", "styles.xml", "meta.xml", "settings.xml", 
"manifest.xml"}
+XMLID = "http://www.w3.org/XML/1998/namespace id"
+# XML 1.0 5th ed. NameStartChar/NameChar without ':'
+_S = "A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\U00010000-\U000EFFFF"
+NCNAME = re.compile("[" + _S + "][" + _S + r"\-.0-9·̀-ͯ‿-⁀]*\Z")
+
+
+def check_stream(data):
+    """Returns [(line, col, message)]."""
+    errs, seen = [], {}
+    p = expat.ParserCreate(namespace_separator=" ")
+
+    def start(name, attrs):
+        if XMLID not in attrs:
+            return
+        # xml:id 1.0 sec. 4: normalize like an ID-typed attribute
+        v = " ".join(attrs[XMLID].split())
+        pos = (p.CurrentLineNumber, p.CurrentColumnNumber)
+        if not NCNAME.match(v):
+            errs.append(pos + ('xml:id "%s" is not an NCName' % v,))
+        elif v in seen:
+            errs.append(pos + ('xml:id "%s" duplicates line %d' % (v, 
seen[v]),))
+        else:
+            seen[v] = pos[0]
+    p.StartElementHandler = start
+    try:
+        p.Parse(data, True)
+    except expat.ExpatError as e:
+        errs.append((e.lineno, e.offset, "not namespace-well-formed: " + 
expat.ErrorString(e.code)))
+    return errs
+
+
+def main():
+    outdir, idsjson = sys.argv[1], sys.argv[2]
+    if not os.path.abspath(idsjson).startswith(os.path.join(D, "runs") + 
os.sep):
+        sys.exit("idcheck.py: <ids.json> must live under " + os.path.join(D, 
"runs"))
+    errors, bad_zip, nstreams = [], [], 0
+    pkgs = sorted(p for p in os.listdir(outdir) if not p.startswith("."))
+    for pkg in pkgs:
+        try:
+            z = zipfile.ZipFile(os.path.join(outdir, pkg))
+        except Exception:
+            bad_zip.append(pkg); continue
+        for name in z.namelist():
+            if name.rsplit("/", 1)[-1] not in STREAMS:
+                continue
+            nstreams += 1
+            for line, col, msg in check_stream(z.read(name)):
+                errors.append([pkg + "/" + name, line, col, msg])
+    json.dump({"packages": pkgs, "bad_zip": bad_zip, "nstreams": nstreams, 
"errors": errors}, open(idsjson, "w"))
+    print(f"xml:id / namespace check: {len(errors)} errors in 
{len({e[0].split('/')[0] for e in errors})} of {len(pkgs)} packages, "
+          f"streams checked: {nstreams}, bad zips: {bad_zip}")
+
+
+main()
diff --git a/test/odf-validate/make-controls.py 
b/test/odf-validate/make-controls.py
index b985e55ab8..d1ec181447 100644
--- a/test/odf-validate/make-controls.py
+++ b/test/odf-validate/make-controls.py
@@ -47,3 +47,9 @@ mk("bad", "1.2", "<text:bogus/>")
 mk("wrongver", "1.1", "<text:p>hi</text:p>")
 # ODF 1.2 Part 1 2.2.1 B.4: an embedded object whose content.xml is MathML
 mk("mathobj", "1.2", "<text:p>hi</text:p>", {"Object 1/content.xml": MATH})
+# ODF 1.2 Part 1 2.2.1 D.1/D.2: checked by idcheck.py, not by the schema
+mk("goodid", "1.2", '<text:p xml:id="a1">x</text:p><text:p xml:id=" b-2.c 
">y</text:p>')
+mk("dupid", "1.2", '<text:p xml:id="a1">x</text:p><text:p xml:id=" a1 
">y</text:p>')
+mk("badid", "1.2", '<text:p xml:id="1abc">x</text:p>')
+mk("badid2", "1.2", '<text:p xml:id="a b">x</text:p>')
+mk("badns", "1.2", "<text:p><zz:span/></text:p>")
diff --git a/test/odf-validate/selftest.py b/test/odf-validate/selftest.py
index 2d7e860fdc..0058afe95a 100644
--- a/test/odf-validate/selftest.py
+++ b/test/odf-validate/selftest.py
@@ -35,6 +35,17 @@ checks = {
     "mathobj.odt MathML object skipped": d["mathml_skipped"] == 
["mathobj.odt/Object 1/content.xml"] and not errs("12", "mathobj.odt"),
     "no unparsed jing output": not any(e[0] == "?" for v in d["errors"] for e 
in d["errors"][v]),
 }
+ids = os.path.join(D, "runs", "control", "ids.json")
+subprocess.run([sys.executable, "-I", os.path.join(D, "idcheck.py"), 
os.path.join(D, "fixtures", "control"), ids], check=True, capture_output=True)
+i = json.load(open(ids))
+def ierrs(pkg): return [e[3] for e in i["errors"] if e[0].startswith(pkg + 
"/")]
+checks.update({
+    "idcheck: good.odt, goodid.odt (normalized ids) clean": not 
ierrs("good.odt") and not ierrs("goodid.odt"),
+    "idcheck: dupid.odt flags the duplicate after normalization": 
any("duplicates" in m for m in ierrs("dupid.odt")),
+    "idcheck: badid.odt, badid2.odt flag non-NCName ids": all(any("not an 
NCName" in m for m in ierrs(p)) for p in ("badid.odt", "badid2.odt")),
+    "idcheck: badns.odt flags the unbound prefix": any("unbound prefix" in m 
for m in ierrs("badns.odt")),
+    "idcheck: no errors in other packages": {e[0].split("/")[0] for e in 
i["errors"]} == {"dupid.odt", "badid.odt", "badid2.odt", "badns.odt"},
+})
 for k, ok in checks.items():
     print(("PASS " if ok else "FAIL ") + k)
 sys.exit(0 if all(checks.values()) else 1)
diff --git a/test/odf-validate/validate.py b/test/odf-validate/validate.py
index f5e2ac8474..f905957793 100644
--- a/test/odf-validate/validate.py
+++ b/test/odf-validate/validate.py
@@ -71,12 +71,17 @@ def main():
     for v in ("12", "14"):
         errs = []
         for schema, fl in ((SCH[v][0], files[v][0]), (SCH[v][1], files[v][1])):
-            for i in range(0, len(fl), 400):
-                r = subprocess.run(JING + [schema] + fl[i:i + 400], 
capture_output=True, text=True)
+            while fl:
+                batch = fl[:400]
+                r = subprocess.run(JING + [schema] + batch, 
capture_output=True, text=True)
+                fl = fl[400:]
                 for line in (r.stdout + r.stderr).splitlines():
                     m = ERR.match(line)
                     if m:
                         errs.append([os.path.relpath(m.group(1), 
os.path.join(work, v)), int(m.group(2)), int(m.group(3)), m.group(5)])
+                        # a fatal error stops jing: resume with the files 
after the one that caused it
+                        if m.group(4) == "fatal" and m.group(1) in batch:
+                            fl = batch[batch.index(m.group(1)) + 1:] + fl
                     elif line.strip():
                         errs.append(["?", 0, 0, line.strip()])
         errors[v] = errs

Reply via email to