xref: /trunk/test/aoo-test/src/aootest/checkers/validate.py (revision 6e223505681eb073927a3bbffc2acd512d92ba3f)
1#**************************************************************
2#
3#  Licensed to the Apache Software Foundation (ASF) under one
4#  or more contributor license agreements.  See the NOTICE file
5#  distributed with this work for additional information
6#  regarding copyright ownership.  The ASF licenses this file
7#  to you under the Apache License, Version 2.0 (the
8#  "License"); you may not use this file except in compliance
9#  with the License.  You may obtain a copy of the License at
10#
11#    http://www.apache.org/licenses/LICENSE-2.0
12#
13#  Unless required by applicable law or agreed to in writing,
14#  software distributed under the License is distributed on an
15#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16#  KIND, either express or implied.  See the License for the
17#  specific language governing permissions and limitations
18#  under the License.
19#
20#**************************************************************
21
22# usage: python -m aootest.checkers.validate <outdir> <val.json>   (needs AOO_JING and AOO_SCHEMA_DIR; tests call check())
23# Validates every package in <outdir> against ODF 1.2 as written, against ODF 1.3 and 1.4 with an office:version or
24# manifest:version of 1.2 or 1.3 rewritten to the target ("13", "14"; any other version stays and is reported), and against
25# ODF 1.2, 1.3 and 1.4 after removing foreign elements and attributes ("12x", "13x", "14x"; Part 1 2.2.2 B.1; manifest left
26# as written apart from the version).
27import sys, os, re, zipfile, subprocess, json
28
29from aootest.checkers import foreign
30
31SCHEMA_FILES = {"12": ("OpenDocument-v1.2-os-schema.rng", "OpenDocument-v1.2-os-manifest-schema.rng"),
32                "13": ("OpenDocument-v1.3-schema.rng", "OpenDocument-v1.3-manifest-schema.rng"),
33                "14": ("OpenDocument-v1.4-schema.rng", "OpenDocument-v1.4-manifest-schema.rng")}
34VERSIONS = ("12", "14", "12x", "13", "13x", "14x")
35STREAMS = {"content.xml", "styles.xml", "meta.xml", "settings.xml"}
36# ODF 1.2 Part 1 2.2.1 B.4: a content.xml rooted at MathML is validated against MathML, not ODF
37ERR = re.compile(r"^(.*?):(\d+):(\d+): (error|fatal|warning): (.*)$")
38
39
40def root_is_mathml(text):
41    body = re.sub(r'<\?xml[^>]*\?>|<!DOCTYPE[^>]*>|<!--.*?-->', '', text[:4000], flags=re.S).lstrip()
42    return bool(re.match(r'<(?:[\w.-]+:)?math[\s>/]', body))
43
44
45def schemas(schema_dir):
46    sch = {v: tuple(os.path.join(schema_dir, f) for f in fs) for v, fs in SCHEMA_FILES.items()}
47    sch["12x"], sch["13x"], sch["14x"] = sch["12"], sch["13"], sch["14"]
48    return sch
49
50
51def check(outdir, workdir, jing, schema_dir):
52    """Returns the result that main() writes as <val.json>. `jing` is the command prefix (java, -jar, jar, -i);
53    `workdir` must be empty or absent: the checker writes its working copies there and never deletes anything."""
54    work = os.path.abspath(workdir)
55    if os.path.isdir(work) and os.listdir(work):
56        raise ValueError("validate: workdir is not empty: " + work)
57    SCH = schemas(schema_dir)
58    files = {v: ([], []) for v in VERSIONS}
59    mixed = {v: foreign.mixed_elements(SCH[v][0]) for v in ("12x", "13x", "14x")}
60    skipped, bad_zip = [], []
61    pkgs = sorted(p for p in os.listdir(outdir) if not p.startswith("."))
62    for pkg in pkgs:
63        try:
64            z = zipfile.ZipFile(os.path.join(outdir, pkg))
65        except Exception:
66            bad_zip.append(pkg); continue
67        for name in z.namelist():
68            is_mani = name == "META-INF/manifest.xml"
69            if name.rsplit("/", 1)[-1] not in STREAMS and not is_mani:
70                continue
71            text = z.read(name).decode("utf-8")
72            if not is_mani and name.endswith("content.xml") and root_is_mathml(text):
73                skipped.append(pkg + "/" + name); continue
74            for v in VERSIONS:
75                t = text
76                if v in mixed and not is_mani:
77                    t = foreign.strip_foreign(t, mixed[v])
78                if v in ("13", "13x", "14", "14x"):
79                    attr = "manifest:version" if is_mani else "office:version"
80                    t = re.sub(attr + '="1\\.[23]"', attr + '="1.%s"' % v[1], t, count=1)
81                p = os.path.join(work, v, pkg, name)
82                os.makedirs(os.path.dirname(p), exist_ok=True)
83                open(p, "w", encoding="utf-8").write(t)
84                files[v][1 if is_mani else 0].append(p)
85    errors = {}
86    for v in VERSIONS:
87        errs = []
88        for schema, fl in ((SCH[v][0], files[v][0]), (SCH[v][1], files[v][1])):
89            while fl:
90                batch = fl[:400]
91                r = subprocess.run(jing + [schema] + batch, capture_output=True, text=True)
92                fl = fl[400:]
93                for line in (r.stdout + r.stderr).splitlines():
94                    m = ERR.match(line)
95                    if m:
96                        errs.append([os.path.relpath(m.group(1), os.path.join(work, v)), int(m.group(2)), int(m.group(3)), m.group(5)])
97                        # a fatal error stops jing: resume with the files after the one that caused it
98                        if m.group(4) == "fatal" and m.group(1) in batch:
99                            fl = batch[batch.index(m.group(1)) + 1:] + fl
100                    elif line.strip():
101                        errs.append(["?", 0, 0, line.strip()])
102        errors[v] = errs
103    return {"packages": pkgs, "bad_zip": bad_zip, "mathml_skipped": skipped,
104            "nfiles": len(files["12"][0]) + len(files["12"][1]), "errors": errors}
105
106
107def main(argv=None):
108    outdir, valjson = sys.argv[1:3] if argv is None else argv
109    res = check(outdir, valjson[:-5] + ".xml", ["java", "-jar", os.environ["AOO_JING"], "-i"], os.environ["AOO_SCHEMA_DIR"])
110    json.dump(res, open(valjson, "w"))
111    errors, pkgs, skipped, bad_zip = res["errors"], res["packages"], res["mathml_skipped"], res["bad_zip"]
112    for v in VERSIONS:
113        print(f"ODF {v[0]}.{v[1]}{' extended, foreign content removed' if v.endswith('x') else ''}: {len(errors[v])} errors in {len({e[0].split('/')[0] for e in errors[v]})} of {len(pkgs)} packages")
114    print(f"files validated: {res['nfiles']}, MathML skipped: {len(skipped)}, bad zips: {bad_zip}")
115    unparsed = [e for v in errors for e in errors[v] if e[0] == "?"]
116    if unparsed:
117        print("UNPARSED jing output:", *[e[3] for e in unparsed[:5]], sep="\n  ")
118
119
120if __name__ == "__main__":
121    main()
122