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 cd3a0a395628aee6ae9d58285051c12840a59bfd Author: Jim Jagielski <[email protected]> AuthorDate: Mon Oct 26 11:58:28 2026 -0400 test/odf-validate: check document type consistency --- test/odf-validate/.gitignore | 1 + test/odf-validate/README.md | 9 ++ test/odf-validate/doctypecheck.py | 189 +++++++++++++++++++++++++++++ test/odf-validate/make-doctype-controls.py | 91 ++++++++++++++ test/odf-validate/selftest.py | 9 ++ 5 files changed, 299 insertions(+) diff --git a/test/odf-validate/.gitignore b/test/odf-validate/.gitignore index 241fe5c692..67bc86e570 100644 --- a/test/odf-validate/.gitignore +++ b/test/odf-validate/.gitignore @@ -5,3 +5,4 @@ baseline/ __pycache__/ fixtures/control/ fixtures/control-pkg/ +fixtures/control-doctype/ diff --git a/test/odf-validate/README.md b/test/odf-validate/README.md index 93562e111b..8187aa9ee0 100644 --- a/test/odf-validate/README.md +++ b/test/odf-validate/README.md @@ -52,6 +52,15 @@ The steps: contents, `manifest:size` and STORED on encrypted entries, and signature files (well-formed, root, `OpenDocument-v1.2-os-dsig-schema.rng`). Findings are `shall:` or `should:`; only `shall` findings are non-conformances. +- `doctypecheck.py <outdir> <dt.json>` checks Part 1 §2.2.1 A.2/E and + §2.2.3-2.2.10: the `mimetype` file (or `office:mimetype` of a flat file), the + root element and the `office:body` child must agree on one document type. + Embedded sub documents are compared with their manifest media type + (`should:` findings). Two deviations from the literal text of §2.2.5: it + spells the drawing values `application.vnd.oasis.opendocument.graphics` and + `...graphic-template`; the registered `...graphics` and `...graphics-template` + of Part 1 appendix C are accepted. `...text-web` and `...formula-template` + are registered but no §2.2.x allows them, so they are reported. - `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. diff --git a/test/odf-validate/doctypecheck.py b/test/odf-validate/doctypecheck.py new file mode 100644 index 0000000000..fdba21e6e8 --- /dev/null +++ b/test/odf-validate/doctypecheck.py @@ -0,0 +1,189 @@ +#************************************************************** +# +# 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: doctypecheck.py <outdir> <dt.json> +# ODF 1.2 Part 1 2.2.1 A.2/E and 2.2.3-2.2.10 on every package (or flat XML file) in <outdir>: +# the mimetype file (or office:mimetype), the root element and the office:body child must agree +# on one document type. Findings are "shall: [rule] ..." or "should: [rule] ...". +import sys, os, io, json, zipfile, collections +from xml.etree import ElementTree as ET + +D = os.path.dirname(os.path.abspath(__file__)) +OFFICE = "urn:oasis:names:tc:opendocument:xmlns:office:1.0" +MATH = "http://www.w3.org/1998/Math/MathML" +P = "application/vnd.oasis.opendocument." +# type -> (mimetype values, office:body child). 2.2.5 spells the drawing values "application.vnd...graphics" +# and "...graphic-template"; the registered values in Part 1 appendix C are used instead. +TYPES = { + "text": ([P + "text", P + "text-template", P + "text-master"], "text"), + "spreadsheet": ([P + "spreadsheet", P + "spreadsheet-template"], "spreadsheet"), + "drawing": ([P + "graphics", P + "graphics-template"], "drawing"), + "presentation": ([P + "presentation", P + "presentation-template"], "presentation"), + "chart": ([P + "chart", P + "chart-template"], "chart"), + "image": ([P + "image", P + "image-template"], "image"), + "formula": ([P + "formula"], None), + "database": ([P + "base"], "database"), +} +BY_MIME = {m: t for t, (ms, _) in TYPES.items() for m in ms} +# registered in Part 1 appendix C, but not a value any of 2.2.3-2.2.10 allows +UNLISTED = {P + "text-web", P + "formula-template"} + + +def local(tag): + if not tag.startswith("{"): + return tag + ns, name = tag[1:].split("}", 1) + return {OFFICE: "office:", MATH: "math:"}.get(ns, "?:") + name + + +def scan(data): + """Returns (root tag, [office:body child tags]); stops reading after office:body.""" + root, body, depth, in_body = None, [], 0, False + for ev, el in ET.iterparse(io.BytesIO(data), events=("start", "end")): + if ev == "start": + depth += 1 + if depth == 1: + root = el.tag + elif depth == 2 and el.tag == "{%s}body" % OFFICE: + in_body = True + elif depth == 3 and in_body: + body.append(el.tag) + else: + depth -= 1 + if depth == 1 and in_body: + break + return root, body + + +def check_content(add, entry, data, T, flat_mime=None): + """Checks one content.xml (or a flat file) against document type T.""" + try: + root, body = scan(data) + except ET.ParseError as e: + add(entry, "shall", "doctype-malformed", "not well-formed: %s" % e) + return + if T == "formula": + if root != "{%s}math" % MATH: + add(entry, "shall", "doctype-root", "formula document whose root is %s, not math:math (2.2.9 B)" % local(root)) + return + want = "{%s}document%s" % (OFFICE, "" if flat_mime is not None else "-content") + if root != want: + add(entry, "shall", "doctype-root", "root is %s, not %s (2.2.1 B.2.1, C.2)" % (local(root), local(want))) + return + child = TYPES[T][1] + if "{%s}%s" % (OFFICE, child) not in body: + add(entry, "shall", "doctype-body", "%s document without office:%s in office:body; has %s (2.2.x C)" % + (T, child, ", ".join(local(b) for b in body) or "no body child")) + + +def check_package(path): + out = [] + + def add(entry, level, rule, msg): + out.append((entry, level, rule, msg)) + with open(path, "rb") as f: + magic = f.read(4) + if magic[:2] != b"PK": + return check_flat(path, out, add) + z = zipfile.ZipFile(path) + files = set(z.namelist()) + if "content.xml" not in files and "styles.xml" not in files: + add("", "shall", "doctype-no-content", "neither content.xml nor styles.xml (2.2.1 A.2)") + mime = z.read("mimetype").decode("utf-8", "replace") if "mimetype" in files else None + T = None + if mime is None: + add("mimetype", "shall", "doctype-no-mimetype", "no mimetype file (2.2.3-2.2.10 B)") + elif mime in UNLISTED: + add("mimetype", "shall", "doctype-unlisted-mimetype", '"%s" is registered but no document type in 2.2.3-2.2.10 allows it' % mime) + elif mime not in BY_MIME: + add("mimetype", "shall", "doctype-unknown-mimetype", 'mimetype "%s" is not a value of any document type (2.2.1 E)' % mime) + else: + T = BY_MIME[mime] + if T and "content.xml" not in files: + add("content.xml", "shall", "doctype-no-body", "no content.xml, so no office:body child (2.2.x C)") + elif T: + check_content(add, "content.xml", z.read("content.xml"), T) + # sub documents: the manifest media type of a directory against that directory's content.xml + if "META-INF/manifest.xml" in files: + try: + root = ET.fromstring(z.read("META-INF/manifest.xml")) + except ET.ParseError: + root = [] + mns = "{urn:oasis:names:tc:opendocument:xmlns:manifest:1.0}" + for e in root: + p, mt = e.get(mns + "full-path"), e.get(mns + "media-type") + if p and p.endswith("/") and p != "/" and p + "content.xml" in files and mt in BY_MIME: + sub = [] + check_content(lambda en, lv, ru, ms: sub.append((en, ru, ms)), p + "content.xml", z.read(p + "content.xml"), BY_MIME[mt]) + for en, ru, ms in sub: + add(en, "should", "sub-" + ru, "sub document typed %s: %s" % (mt, ms)) + return out, mime or "(none)" + + +def check_flat(path, out, add): + data = open(path, "rb").read() + + try: + root = ET.fromstring(data) + except ET.ParseError as e: + raise zipfile.BadZipFile(str(e)) + mime = root.get("{%s}mimetype" % OFFICE) + if root.tag == "{%s}math" % MATH: + return out, "(flat math)" + if mime is None: + add("", "shall", "doctype-no-mimetype", "no office:mimetype attribute (2.2.3-2.2.10 A)") + return out, "(none)" + T = BY_MIME.get(mime) + if mime in UNLISTED: + add("", "shall", "doctype-unlisted-mimetype", '"%s" is registered but no document type in 2.2.3-2.2.10 allows it' % mime) + elif T is None or T == "formula": + add("", "shall", "doctype-unknown-mimetype", 'office:mimetype "%s" is not a value of any flat document type (2.2.1 E)' % mime) + else: + check_content(add, "", data, T, flat_mime=mime) + return out, mime + + +def main(): + outdir, dtjson = sys.argv[1], sys.argv[2] + if not os.path.abspath(dtjson).startswith(os.path.join(D, "runs") + os.sep): + sys.exit("doctypecheck.py: <dt.json> must live under " + os.path.join(D, "runs")) + errors, bad, types = [], [], collections.Counter() + pkgs = sorted(p for p in os.listdir(outdir) if not p.startswith(".")) + for pkg in pkgs: + try: + found, mime = check_package(os.path.join(outdir, pkg)) + except zipfile.BadZipFile: + bad.append(pkg); continue + types[mime] += 1 + for entry, level, rule, msg in found: + errors.append([pkg + "/" + entry, 0, 0, "%s: [%s] %s" % (level, rule, msg)]) + json.dump({"packages": pkgs, "bad": bad, "types": types, "errors": errors}, open(dtjson, "w")) + shall = [e for e in errors if e[3].startswith("shall:")] + print(f"document type check: {len(shall)} shall and {len(errors) - len(shall)} should findings in " + f"{len({e[0].split('/')[0] for e in errors})} of {len(pkgs)} documents, unreadable: {bad}") + for k, v in sorted(types.items()): + print(f" {v:6d} {k}") + rules = collections.Counter(e[3].split("]")[0] + "]" for e in errors) + for k, v in sorted(rules.items()): + print(f" {v:6d} {k}") + + +main() diff --git a/test/odf-validate/make-doctype-controls.py b/test/odf-validate/make-doctype-controls.py new file mode 100644 index 0000000000..5765539b44 --- /dev/null +++ b/test/odf-validate/make-doctype-controls.py @@ -0,0 +1,91 @@ +#************************************************************** +# +# 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: make-doctype-controls.py -- (re)generate doctypecheck.py's negative-control documents in fixtures/control-doctype/ +# .expected.json maps each document to the (level, rule) pairs doctypecheck.py must report, exactly. +import json, os, shutil, zipfile + +C = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "control-doctype") +P = "application/vnd.oasis.opendocument." +NS = ('xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML"') +S, Z = zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED +EXPECTED = {} + + +def content(child="text", root="office:document-content", extra=""): + body = "<office:body>%s</office:body>" % ("<office:%s/>" % child if child else "") + return '<?xml version="1.0" encoding="UTF-8"?>\n<%s %s office:version="1.2"%s>%s</%s>\n' % (root, NS, extra, body, root) + + +MATHDOC = '<?xml version="1.0" encoding="UTF-8"?>\n<math:math %s><math:mi>x</math:mi></math:math>\n' % NS + + +def pkg(name, mime, body, expect=(), files=None, manifest=""): + """files: replaces the default content.xml; manifest: extra file-entry elements.""" + with zipfile.ZipFile(os.path.join(C, name + ".odt"), "w") as z: + if mime is not None: + z.writestr(zipfile.ZipInfo("mimetype"), mime, compress_type=S) + for n, d in (files if files is not None else {"content.xml": body}).items(): + z.writestr(n, d, compress_type=Z) + z.writestr("META-INF/manifest.xml", '<?xml version="1.0" encoding="UTF-8"?>\n<manifest:manifest xmlns:manifest=' + '"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">%s</manifest:manifest>\n' % manifest, compress_type=Z) + EXPECTED[name + ".odt"] = sorted(expect) + + +def flat(name, mime, child="text", expect=()): + attr = "" if mime is None else ' office:mimetype="%s"' % mime + open(os.path.join(C, name + ".fodt"), "w").write(content(child, "office:document", attr)) + EXPECTED[name + ".fodt"] = sorted(expect) + + +shutil.rmtree(C, ignore_errors=True) +os.makedirs(C) +for t, ms, child in (("text", ["text", "text-template", "text-master"], "text"), ("spreadsheet", ["spreadsheet", "spreadsheet-template"], "spreadsheet"), + ("drawing", ["graphics", "graphics-template"], "drawing"), ("presentation", ["presentation", "presentation-template"], "presentation"), + ("chart", ["chart", "chart-template"], "chart"), ("image", ["image", "image-template"], "image"), ("database", ["base"], "database")): + for m in ms: + pkg("good-" + m, P + m, content(child)) +pkg("good-formula", P + "formula", MATHDOC) +sub = lambda mt, c: {"content.xml": content(), "Object 1/content.xml": c} +ent = lambda mt: '<manifest:file-entry manifest:full-path="Object 1/" manifest:media-type="%s"/>' % mt +pkg("good-embedded", P + "text", None, files=sub(P + "chart", content("chart")), manifest=ent(P + "chart")) +pkg("good-embedded-math", P + "text", None, files=sub("", MATHDOC), manifest=ent(P + "formula")) +flat("good-flat", P + "text") +for m, ru in (("application/x-bogus", "doctype-unknown-mimetype"), (P + "text\n", "doctype-unknown-mimetype"), + ("application.vnd.oasis.opendocument.graphics", "doctype-unknown-mimetype"), + (P + "text-web", "doctype-unlisted-mimetype"), (P + "formula-template", "doctype-unlisted-mimetype")): + pkg("bad-mime-" + str(len(EXPECTED)), m, content(), [("shall", ru)]) +pkg("no-mimetype", None, content(), [("shall", "doctype-no-mimetype")]) +pkg("body-mismatch", P + "text", content("spreadsheet"), [("shall", "doctype-body")]) +pkg("body-empty", P + "text", content(None), [("shall", "doctype-body")]) +pkg("root-styles", P + "text", content(root="office:document-styles"), [("shall", "doctype-root")]) +pkg("formula-wrong-root", P + "formula", content(), [("shall", "doctype-root")]) +pkg("math-in-text", P + "text", MATHDOC, [("shall", "doctype-root")]) +pkg("only-styles", P + "text", None, [("shall", "doctype-no-body")], files={"styles.xml": content(None, "office:document-styles")}) +pkg("only-meta", P + "text", None, [("shall", "doctype-no-content"), ("shall", "doctype-no-body")], files={"meta.xml": "<a/>"}) +pkg("malformed", P + "text", "<office:document-content", [("shall", "doctype-malformed")]) +pkg("sub-body", P + "text", None, [("should", "sub-doctype-body")], files=sub(P + "chart", content("spreadsheet")), manifest=ent(P + "chart")) +pkg("sub-root", P + "text", None, [("should", "sub-doctype-root")], files=sub(P + "formula", content()), manifest=ent(P + "formula")) +flat("flat-no-mimetype", None, expect=[("shall", "doctype-no-mimetype")]) +flat("flat-unknown", "application/x-bogus", expect=[("shall", "doctype-unknown-mimetype")]) +flat("flat-formula-mime", P + "formula", expect=[("shall", "doctype-unknown-mimetype")]) +flat("flat-body", P + "text", "presentation", [("shall", "doctype-body")]) +json.dump(EXPECTED, open(os.path.join(C, ".expected.json"), "w"), indent=1) diff --git a/test/odf-validate/selftest.py b/test/odf-validate/selftest.py index 61e6091695..f5e1c1183a 100644 --- a/test/odf-validate/selftest.py +++ b/test/odf-validate/selftest.py @@ -56,6 +56,15 @@ expected = json.load(open(os.path.join(pdir, ".expected.json"))) def found(pkg): return sorted({tuple(m.split("]")[0].split(": [")) for m in (e[3] for e in pe if e[0].startswith(pkg + "/"))}) for pkg in sorted(expected): checks["pkgcheck: " + pkg + " reports exactly " + (", ".join(r for _, r in map(tuple, expected[pkg])) or "nothing")] = found(pkg) == [tuple(x) for x in expected[pkg]] +subprocess.run([sys.executable, "-I", os.path.join(D, "make-doctype-controls.py")], check=True) +dt = os.path.join(D, "runs", "control", "dt.json") +ddir = os.path.join(D, "fixtures", "control-doctype") +subprocess.run([sys.executable, "-I", os.path.join(D, "doctypecheck.py"), ddir, dt], check=True, capture_output=True) +de = json.load(open(dt))["errors"] +dexpected = json.load(open(os.path.join(ddir, ".expected.json"))) +def dfound(doc): return sorted({tuple(m.split("]")[0].split(": [")) for m in (e[3] for e in de if e[0].startswith(doc + "/"))}) +for doc in sorted(dexpected): + checks["doctypecheck: " + doc + " reports exactly " + (", ".join(r for _, r in dexpected[doc]) or "nothing")] = dfound(doc) == [tuple(x) for x in dexpected[doc]] for k, ok in checks.items(): print(("PASS " if ok else "FAIL ") + k) sys.exit(0 if all(checks.values()) else 1)
