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# usage: runpy.sh calcval.py <port> <cases.tsv> <out.json> 22# python3 -I calcval.py --compare old.json new.json 23# 24# Evaluates the formulas of a cases TSV (see calcval-cases.tsv for the columns 25# and the data area) in a new Calc document and records, per case, the compile 26# and evaluation result of the current build, and whether it equals the value 27# that ODF 1.3 Part 4 requires. --compare lists the cases whose result changed. 28 29import json, math, re, sys 30 31 32def parse_mode(mode): 33 m = re.fullmatch(r"cell(?:@(\d+))?", mode) 34 if m: 35 return "cell", 1, 1, int(m.group(1) or 1) 36 m = re.fullmatch(r"array(?::(\d+)x(\d+))?", mode) 37 if m: 38 return "array", int(m.group(1) or 1), int(m.group(2) or 1), 1 39 raise ValueError("bad mode %r" % mode) 40 41 42def read_cases(path): 43 cases = [] 44 for ln, line in enumerate(open(path, encoding="utf-8"), 1): 45 line = line.rstrip("\n") 46 if not line or line.startswith("#"): 47 continue 48 f = line.split("\t") 49 if len(f) != 5: 50 raise SystemExit("%s:%d: expected 5 tab separated columns, got %d" % (path, ln, len(f))) 51 cases.append(dict(zip(("id", "formula", "mode", "expected", "note"), f))) 52 ids = [c["id"] for c in cases] 53 if len(set(ids)) != len(ids): 54 raise SystemExit("duplicate case ids in " + path) 55 return cases 56 57 58# Analysis add-in functions are not known by their English names to setFormula; 59# the case formulas keep the ODF names and are rewritten to the programmatic names. 60ADDIN = {"RECEIVED": "getReceived", "BESSELK": "getBesselk", "BESSELY": "getBessely", "CONVERT": "getConvert", 61 "ODDFPRICE": "getOddfprice", "ODDFYIELD": "getOddfyield"} 62 63 64def api_formula(f): 65 for name, prog in ADDIN.items(): 66 f = re.sub(r"(?<![A-Za-z0-9_.])%s\(" % name, "com.sun.star.sheet.addin.Analysis.%s(" % prog, f) 67 return f 68 69 70NOT_AVAILABLE = 32767 71 72 73def elem_match(exp, cell): 74 # cell: dict with rt (CellContentType name of the formula result; errors report VALUE), err, str, val 75 if exp == "#N/A": 76 return cell["err"] == NOT_AVAILABLE 77 if exp == "#ERR": 78 return cell["err"] != 0 79 if cell["err"] != 0: 80 return False 81 if exp.startswith("s:"): 82 return cell["rt"] == "TEXT" and cell["str"] == exp[2:] 83 tol = 1e-9 84 if exp.startswith("~"): 85 exp, tol = exp[1:], 1e-6 86 e = float(exp) 87 return cell["rt"] == "VALUE" and isinstance(cell["val"], float) and abs(cell["val"] - e) <= tol * max(1.0, abs(e)) 88 89 90def judge(expected, cells): 91 if expected == "-": 92 return "record" 93 exps = expected.split("|") 94 if len(exps) != len(cells): 95 return "mismatch" 96 return "match" if all(elem_match(e, c) for e, c in zip(exps, cells)) else "mismatch" 97 98 99def num(v): 100 return v if math.isfinite(v) else repr(v) 101 102 103def cell_result(cell): 104 try: 105 rt = cell.getPropertyValue("FormulaResultType").value 106 except Exception: 107 rt = None 108 return {"rt": rt, "err": cell.getError(), "str": cell.getString(), "val": num(float(cell.getValue()))} 109 110 111def setup_data(doc): 112 sheets = doc.getSheets() 113 sheets.insertNewByName("Other", 1) 114 sh = sheets.getByIndex(0) 115 116 def put(addr, vals): 117 # vals: list of rows; None leaves the cell empty; str is text 118 a0 = sh.getCellRangeByName(addr).getRangeAddress() 119 for r, row in enumerate(vals): 120 for c, v in enumerate(row): 121 if v is None: 122 continue 123 cell = sh.getCellByPosition(a0.StartColumn + c, a0.StartRow + r) 124 if isinstance(v, str): 125 cell.setString(v) 126 else: 127 cell.setValue(v) 128 129 put("A1", [[v] for v in "yxxyxyxxy"]) 130 put("B1", [[v] for v in "yxyyyyxyx"]) 131 put("D1", [[10 * i, 11 * i, 101 * i] for i in range(1, 6)]) 132 put("H1", [[10 * i for i in range(1, 6)], [11 * i for i in range(1, 6)], [101 * i for i in range(1, 6)]]) 133 put("N1", [[v] for v in (3, 5, 8, 9, 13, 14)]) 134 put("O1", [[v] for v in (1, 2, 3, 4, 5, 6)]) 135 put("P1", [[v] for v in (2, 4, 7, 15, 30, 58)]) 136 put("R1", [["Name", "Age", "Score"], ["A", 20, 5], ["B", 30, "n/a"], ["C", 40, 15], ["D", 50, None], ["E", 60, 25]]) 137 put("V1", [["Age"], [">=30"]]) 138 put("W1", [["Age"], [None]]) 139 put("Y1", [["Name"], ["A"]]) 140 put("AH1", [[v] for v in (6, 6, 6, 6, 3, 2, 1, 2, 6, 4, 2)]) 141 put("AI1", [[v] for v in (1, 3, 5)]) 142 put("AJ1", [[v] for v in (2, 4, 7, 9)]) 143 put("AK1", [[v] for v in (2, 4, 7, 9)]) 144 for addr, f in (("AM1", "=NA()"), ("AM2", "=1/0"), ("AM3", '=""'), ("AN1", "5"), ("AN2", "=NA()"), ("AN4", "=NA()"), ("AN5", "7"), ("AN6", "=1/0")): 145 sh.getCellRangeByName(addr).setFormula(f) 146 sh.getCellRangeByName("AN3").setString("x") 147 put("AP1", [["Score"], ["<>5"]]) 148 put("AQ1", [["Score"], ["="]]) 149 put("AR1", [["Score", "Age"], ["=", ">=30"]]) 150 put("AT1", [["Age", "Score"], [">=30", "="]]) 151 put("AV1", [["Score", "Age"], ["25", None], [None, "50"]]) 152 put("AX11", [["K", "V"], ["a", 1], ["b", 2], ["c", 3]]) 153 put("AZ11", [["K"], [None]]) 154 put("BB1", [["K", "V"], ["a", 1], [None, 2], [None, None], ["c", 3]]) 155 put("BD1", [["K"], ["="]]) 156 return sh 157 158 159def office_version(ctx): 160 try: 161 from unohelp import pv 162 cp = ctx.ServiceManager.createInstanceWithContext("com.sun.star.configuration.ConfigurationProvider", ctx) 163 ca = cp.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", 164 (pv("nodepath", "/org.openoffice.Setup/Product"),)) 165 return "%s %s" % (ca.getByName("ooName"), ca.getByName("ooSetupVersion")) 166 except Exception as e: 167 return "unknown (%s)" % e 168 169 170def run(port, cases_path, out_path): 171 from unohelp import connect, desktop, pv 172 cases = read_cases(cases_path) 173 ctx = connect(port) 174 desk = desktop(ctx) 175 doc = desk.loadComponentFromURL("private:factory/scalc", "_blank", 0, (pv("Hidden", True),)) 176 if doc is None: 177 raise SystemExit("could not create a Calc document") 178 results = [] 179 aborted = None 180 try: 181 sh = setup_data(doc) 182 scratch = sh.getCellRangeByName("AA1:AF12") 183 for case in cases: 184 kind, cols, rows, row = parse_mode(case["mode"]) 185 rec = dict(case) 186 try: 187 formula = api_formula(case["formula"]) 188 if kind == "cell": 189 cell = sh.getCellByPosition(26, row - 1) 190 cell.setFormula(formula) 191 cells = [cell] 192 else: 193 rng = sh.getCellRangeByPosition(26, 0, 26 + cols - 1, rows - 1) 194 rng.setArrayFormula(formula) 195 cells = [sh.getCellByPosition(26 + c, r) for r in range(rows) for c in range(cols)] 196 doc.calculateAll() 197 rec["formula_used"] = formula 198 res = [cell_result(c) for c in cells] 199 rec["readback"] = cells[0].getFormula() 200 rec["result"] = res 201 rec["status"] = judge(case["expected"], res) 202 except Exception as e: 203 rec["exception"] = "%s: %s" % (type(e).__name__, e) 204 rec["status"] = "exception" 205 if "Disposed" in type(e).__name__ or "connect" in str(e).lower(): 206 aborted = case["id"] 207 results.append(rec) 208 try: 209 scratch.clearContents(1 | 2 | 4 | 8 | 16 | 32) 210 except Exception as e: 211 aborted = aborted or case["id"] 212 rec["exception"] = rec.get("exception", "") + " clear: %s" % e 213 if aborted: 214 break 215 finally: 216 try: 217 doc.close(True) 218 except Exception: 219 pass 220 out = {"office": office_version(ctx) if not aborted else "unknown", "cases_file": cases_path, 221 "aborted_at": aborted, "cases": results} 222 with open(out_path, "w", encoding="utf-8") as f: 223 json.dump(out, f, indent=1, ensure_ascii=False) 224 f.write("\n") 225 n = len(results) 226 st = {} 227 for r in results: 228 st[r["status"]] = st.get(r["status"], 0) + 1 229 nerr = sum(1 for r in results if r["status"] != "exception" and any(c["err"] for c in r["result"])) 230 print("cases run %d of %d: %s; cases with an error value in the result: %d%s" % ( 231 n, len(cases), ", ".join("%s=%d" % kv for kv in sorted(st.items())), nerr, 232 "; ABORTED at " + aborted if aborted else "")) 233 for r in results: 234 if r["status"] == "mismatch": 235 print("MISMATCH %-28s %-12s expected %s got %s" % (r["id"], r["mode"], r["expected"], summary(r))) 236 return 1 if aborted else 0 237 238 239def summary(rec): 240 if "result" not in rec: 241 return rec.get("exception", "?") 242 return " | ".join("err=%d" % c["err"] if c["err"] else 243 ("%r" % c["val"] if c["rt"] == "VALUE" else "%r" % c["str"]) for c in rec["result"]) 244 245 246def same(a, b): 247 if "result" not in a or "result" not in b: 248 return a.get("exception") == b.get("exception") and ("result" in a) == ("result" in b) 249 if a["readback"] != b["readback"] or len(a["result"]) != len(b["result"]): 250 return False 251 for x, y in zip(a["result"], b["result"]): 252 if (x["rt"], x["err"], x["str"]) != (y["rt"], y["err"], y["str"]): 253 return False 254 vx, vy = x["val"], y["val"] 255 if isinstance(vx, float) and isinstance(vy, float): 256 if abs(vx - vy) > 1e-12 * max(1.0, abs(vx)): 257 return False 258 elif vx != vy: 259 return False 260 return True 261 262 263def compare(old_path, new_path): 264 old = {r["id"]: r for r in json.load(open(old_path, encoding="utf-8"))["cases"]} 265 new = {r["id"]: r for r in json.load(open(new_path, encoding="utf-8"))["cases"]} 266 changed = 0 267 for i in old: 268 if i not in new: 269 print("REMOVED %s" % i); changed += 1 270 elif not same(old[i], new[i]): 271 changed += 1 272 print("CHANGED %-28s %-12s %s\n old: %s [%s]\n new: %s [%s]" % ( 273 i, new[i]["mode"], new[i]["formula"], summary(old[i]), old[i]["status"], 274 summary(new[i]), new[i]["status"])) 275 for i in new: 276 if i not in old: 277 print("ADDED %s" % i); changed += 1 278 print("%d cases compared, %d changed" % (len(set(old) & set(new)), changed)) 279 return 1 if changed else 0 280 281 282def main(argv): 283 if len(argv) == 4 and argv[1] == "--compare": 284 return compare(argv[2], argv[3]) 285 if len(argv) == 4: 286 return run(int(argv[1]), argv[2], argv[3]) 287 print("usage: runpy.sh calcval.py <port> <cases.tsv> <out.json>\n" 288 " python3 -I calcval.py --compare old.json new.json", file=sys.stderr) 289 return 2 290 291 292sys.exit(main(sys.argv)) 293