| 1 | #!/usr/bin/env python3 |
| 2 | """tests/tz_diff.py - differential test of plugin_time against real tzdata. |
| 3 | |
| 4 | `tests/run.sh` pins epochs it was written from. That catches regressions, but it |
| 5 | cannot catch a *belief*: if the plugin and the suite author both think 2040-07-01 |
| 6 | in New York is EST, the suite passes and the answer is still wrong. This harness |
| 7 | asks a second, independent implementation instead - Python's `zoneinfo` over the |
| 8 | host's own tz database - and compares field by field. |
| 9 | |
| 10 | It is what found the two bugs the offline suite could not: |
| 11 | * the post-2037 transition list was returned as-is instead of handing over to |
| 12 | the zone's POSIX rule, so every northern zone answered "standard time" for |
| 13 | every date after 2038 (401 mismatches); |
| 14 | * a southern-hemisphere DST rule was tested as a window rather than as sorted |
| 15 | events, so 60 zones reported DST through their winter (60 more). |
| 16 | |
| 17 | Skips cleanly (exit 0) when `zoneinfo` is unavailable or has no tz database, so |
| 18 | a node without Python's tzdata is never blocked by it. |
| 19 | |
| 20 | python3 tests/tz_diff.py # default sweep, ~40 s |
| 21 | python3 tests/tz_diff.py --quick # one instant, ~5 s |
| 22 | python3 tests/tz_diff.py --strict # exit 2 when zoneinfo is missing |
| 23 | """ |
| 24 | |
| 25 | import argparse |
| 26 | import datetime |
| 27 | import json |
| 28 | import os |
| 29 | import subprocess |
| 30 | import sys |
| 31 | |
| 32 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 33 | BIN = os.path.join(ROOT, "plugin_time") |
| 34 | |
| 35 | # Instants chosen to land on both sides of the transitions that matter: the |
| 36 | # spring and autumn changes in each hemisphere, a leap year, and two dates well |
| 37 | # past the point where the compiled tz table stops generating transitions |
| 38 | # (2037), where only each zone's own POSIX rule can answer. |
| 39 | DATES = [ |
| 40 | datetime.datetime(2026, 1, 15, tzinfo=datetime.timezone.utc), |
| 41 | datetime.datetime(2026, 3, 29, tzinfo=datetime.timezone.utc), |
| 42 | datetime.datetime(2026, 7, 15, tzinfo=datetime.timezone.utc), |
| 43 | datetime.datetime(2026, 10, 25, tzinfo=datetime.timezone.utc), |
| 44 | datetime.datetime(2028, 2, 29, tzinfo=datetime.timezone.utc), |
| 45 | datetime.datetime(2038, 3, 28, tzinfo=datetime.timezone.utc), |
| 46 | datetime.datetime(2038, 7, 1, tzinfo=datetime.timezone.utc), |
| 47 | datetime.datetime(2040, 6, 1, tzinfo=datetime.timezone.utc), |
| 48 | ] |
| 49 | QUICK_DATES = [datetime.datetime(2026, 11, 14, tzinfo=datetime.timezone.utc)] |
| 50 | |
| 51 | # Hours around each date, so a transition that lands mid-day is crossed too. |
| 52 | HOUR_OFFSETS = list(range(-36, 60, 7)) |
| 53 | QUICK_HOURS = [0] |
| 54 | |
| 55 | # convert_time: wall times that only exist once, once-twice (fall back) and |
| 56 | # never (spring forward) depending on the zone. |
| 57 | WALL_TIMES = [(0, 0), (1, 30), (2, 30), (3, 30), (9, 0), (12, 30), (23, 59)] |
| 58 | CONVERT_TARGETS = ["UTC", "Asia/Kathmandu", "Australia/Lord_Howe"] |
| 59 | |
| 60 | FAILS = [] |
| 61 | |
| 62 | |
| 63 | def ok(desc): |
| 64 | print(" ok %s" % desc) |
| 65 | |
| 66 | |
| 67 | def bad(desc, detail=""): |
| 68 | FAILS.append(desc) |
| 69 | print(" FAIL %s%s" % (desc, (" " + str(detail)[:300]) if detail else "")) |
| 70 | |
| 71 | |
| 72 | def mcp(requests, now=None): |
| 73 | """Run one --mcp session and return the parsed responses, in order.""" |
| 74 | env = dict(os.environ) |
| 75 | if now: |
| 76 | env["SX_TIME_NOW"] = now |
| 77 | payload = "\n".join(json.dumps(r) for r in requests) + "\n" |
| 78 | out = subprocess.run([BIN, "--mcp"], input=payload.encode(), |
| 79 | capture_output=True, env=env, timeout=300).stdout |
| 80 | return [json.loads(l) for l in out.decode("utf-8", "replace").splitlines() if l.strip()] |
| 81 | |
| 82 | |
| 83 | def struct_of(resp): |
| 84 | result = resp.get("result", {}) |
| 85 | if result.get("isError"): |
| 86 | return {"error": result.get("content", [{}])[0].get("text", "")} |
| 87 | return result.get("structuredContent", {}) |
| 88 | |
| 89 | |
| 90 | def iso(obj, key): |
| 91 | return obj.get(key, "") if isinstance(obj, dict) else "" |
| 92 | |
| 93 | |
| 94 | def diff_current(zones, dates, hours): |
| 95 | total = 0 |
| 96 | for date in dates: |
| 97 | for h in hours: |
| 98 | now = date + datetime.timedelta(hours=h) |
| 99 | stamp = now.strftime("%Y-%m-%dT%H:%M:%SZ") |
| 100 | reqs = [{"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", |
| 101 | "params": {"name": "get_current_time", |
| 102 | "arguments": {"timezone": z}}} |
| 103 | for i, z in enumerate(zones)] |
| 104 | out = mcp(reqs, now=stamp) |
| 105 | if len(out) != len(zones): |
| 106 | bad("get_current_time @ %s returned %d of %d responses" |
| 107 | % (stamp, len(out), len(zones))) |
| 108 | continue |
| 109 | epoch = int(now.timestamp()) |
| 110 | for z, resp in zip(zones, out): |
| 111 | got = struct_of(resp) |
| 112 | ref = datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)\ |
| 113 | .astimezone(__import__("zoneinfo").ZoneInfo(z)) |
| 114 | expect = { |
| 115 | "timezone": z, |
| 116 | "datetime": ref.isoformat(timespec="seconds"), |
| 117 | "day_of_week": ref.strftime("%A"), |
| 118 | "is_dst": bool(ref.dst()), |
| 119 | } |
| 120 | total += 1 |
| 121 | for key, want in expect.items(): |
| 122 | if got.get(key) != want: |
| 123 | bad("get_current_time %s @ %s: %s = %r, zoneinfo says %r" |
| 124 | % (z, stamp, key, got.get(key), want)) |
| 125 | break |
| 126 | return total |
| 127 | |
| 128 | |
| 129 | def diff_convert(zones, dates): |
| 130 | from zoneinfo import ZoneInfo |
| 131 | |
| 132 | total = 0 |
| 133 | for date in dates: |
| 134 | stamp = date.strftime("%Y-%m-%dT%H:%M:%SZ") |
| 135 | reqs, meta = [], [] |
| 136 | for z in zones: |
| 137 | for target in CONVERT_TARGETS: |
| 138 | for hh, mm in WALL_TIMES: |
| 139 | reqs.append({"jsonrpc": "2.0", "id": len(reqs) + 1, |
| 140 | "method": "tools/call", |
| 141 | "params": {"name": "convert_time", |
| 142 | "arguments": { |
| 143 | "source_timezone": z, |
| 144 | "time": "%02d:%02d" % (hh, mm), |
| 145 | "target_timezone": target}}}) |
| 146 | meta.append((z, target, hh, mm)) |
| 147 | out = mcp(reqs, now=stamp) |
| 148 | if len(out) != len(meta): |
| 149 | bad("convert_time @ %s returned %d of %d responses" |
| 150 | % (stamp, len(out), len(meta))) |
| 151 | continue |
| 152 | for (src, dst, hh, mm), resp in zip(meta, out): |
| 153 | total += 1 |
| 154 | zs, zt = ZoneInfo(src), ZoneInfo(dst) |
| 155 | # "Today" in the source zone, at the requested wall time. |
| 156 | now_src = date.astimezone(zs) |
| 157 | wall = datetime.datetime(now_src.year, now_src.month, now_src.day, |
| 158 | hh, mm, tzinfo=zs) |
| 159 | # A wall time skipped by a clock change does not survive a round |
| 160 | # trip through UTC; the reference server errors on it. |
| 161 | round_trip = datetime.datetime.fromtimestamp(wall.timestamp(), zs) |
| 162 | skipped = round_trip.replace(tzinfo=None) != wall.replace(tzinfo=None) |
| 163 | # A wall time repeated by a clock change has a second reading at a |
| 164 | # different offset (Python's fold=1). |
| 165 | fold1 = wall.replace(fold=1) |
| 166 | ambiguous = fold1.utcoffset() != wall.utcoffset() |
| 167 | |
| 168 | got = struct_of(resp) |
| 169 | if skipped: |
| 170 | if not got.get("error"): |
| 171 | bad("convert_time %s %02d:%02d @ %s should be an error " |
| 172 | "(the wall time does not exist)" % (src, hh, mm, stamp)) |
| 173 | elif "does not exist" not in got["error"]: |
| 174 | bad("convert_time %s %02d:%02d: skipped-hour error text is %r" |
| 175 | % (src, hh, mm, got["error"])) |
| 176 | continue |
| 177 | if got.get("error"): |
| 178 | bad("convert_time %s %02d:%02d @ %s errored: %r" |
| 179 | % (src, hh, mm, stamp, got["error"])) |
| 180 | continue |
| 181 | |
| 182 | target = wall.astimezone(zt) |
| 183 | if iso(got.get("source"), "datetime") != wall.isoformat(timespec="seconds"): |
| 184 | bad("convert_time %s %02d:%02d @ %s: source %r, zoneinfo %r" |
| 185 | % (src, hh, mm, stamp, iso(got.get("source"), "datetime"), |
| 186 | wall.isoformat(timespec="seconds"))) |
| 187 | continue |
| 188 | if iso(got.get("target"), "datetime") != target.isoformat(timespec="seconds"): |
| 189 | bad("convert_time %s %02d:%02d -> %s @ %s: target %r, zoneinfo %r" |
| 190 | % (src, hh, mm, dst, stamp, iso(got.get("target"), "datetime"), |
| 191 | target.isoformat(timespec="seconds"))) |
| 192 | continue |
| 193 | hours = (target.utcoffset() - wall.utcoffset()).total_seconds() / 3600 |
| 194 | want = ("%+.1fh" % hours) if float(hours).is_integer() \ |
| 195 | else ("%+.2f" % hours).rstrip("0").rstrip(".") + "h" |
| 196 | if got.get("time_difference") != want: |
| 197 | bad("convert_time %s -> %s @ %s: difference %r, expected %r" |
| 198 | % (src, dst, stamp, got.get("time_difference"), want)) |
| 199 | continue |
| 200 | |
| 201 | later = got.get("later_occurrence") |
| 202 | if ambiguous: |
| 203 | if not later: |
| 204 | bad("convert_time %s %02d:%02d @ %s: the hour repeats but no " |
| 205 | "later_occurrence was reported" % (src, hh, mm, stamp)) |
| 206 | continue |
| 207 | later_target = fold1.astimezone(zt) |
| 208 | if iso(later.get("source"), "datetime") != fold1.isoformat(timespec="seconds"): |
| 209 | bad("convert_time %s %02d:%02d @ %s: later source %r, zoneinfo %r" |
| 210 | % (src, hh, mm, stamp, iso(later.get("source"), "datetime"), |
| 211 | fold1.isoformat(timespec="seconds"))) |
| 212 | elif iso(later.get("target"), "datetime") != later_target.isoformat(timespec="seconds"): |
| 213 | bad("convert_time %s %02d:%02d -> %s @ %s: later target %r, " |
| 214 | "zoneinfo %r" % (src, hh, mm, dst, stamp, |
| 215 | iso(later.get("target"), "datetime"), |
| 216 | later_target.isoformat(timespec="seconds"))) |
| 217 | elif later: |
| 218 | bad("convert_time %s %02d:%02d @ %s: reported a later_occurrence " |
| 219 | "for an unambiguous time" % (src, hh, mm, stamp)) |
| 220 | return total |
| 221 | |
| 222 | |
| 223 | def main(): |
| 224 | ap = argparse.ArgumentParser() |
| 225 | ap.add_argument("--quick", action="store_true", |
| 226 | help="one instant instead of the full sweep (~5 s)") |
| 227 | ap.add_argument("--strict", action="store_true", |
| 228 | help="exit 2 when zoneinfo is unavailable instead of skipping") |
| 229 | args = ap.parse_args() |
| 230 | |
| 231 | try: |
| 232 | from zoneinfo import ZoneInfo, available_timezones |
| 233 | except ImportError: |
| 234 | print("zoneinfo is not available (Python < 3.9) - skipping the differential run") |
| 235 | return 2 if args.strict else 0 |
| 236 | |
| 237 | if not os.access(BIN, os.X_OK): |
| 238 | bad("plugin_time is missing - run make first") |
| 239 | return 1 |
| 240 | |
| 241 | # `localtime` is a symlink on some hosts and not an IANA key; the plugin |
| 242 | # refuses it on purpose, so it is not a comparison candidate. |
| 243 | zones = sorted(z for z in available_timezones() |
| 244 | if z != "localtime" and "/" in z or z in ("UTC", "GMT")) |
| 245 | if not zones: |
| 246 | print("no tz database on this host - skipping the differential run") |
| 247 | return 2 if args.strict else 0 |
| 248 | |
| 249 | dates = QUICK_DATES if args.quick else DATES |
| 250 | hours = QUICK_HOURS if args.quick else HOUR_OFFSETS |
| 251 | |
| 252 | print("differential run: %d zones x %d instants" % (len(zones), len(dates) * len(hours))) |
| 253 | before = len(FAILS) |
| 254 | n_current = diff_current(zones, dates, hours) |
| 255 | print(" get_current_time: %d comparisons, %d failures so far" |
| 256 | % (n_current, len(FAILS) - before)) |
| 257 | |
| 258 | if args.quick: |
| 259 | print(" convert_time: skipped in --quick mode") |
| 260 | else: |
| 261 | before = len(FAILS) |
| 262 | n_convert = diff_convert(zones, dates) |
| 263 | print(" convert_time: %d comparisons, %d failures so far" |
| 264 | % (n_convert, len(FAILS) - before)) |
| 265 | |
| 266 | print("") |
| 267 | if FAILS: |
| 268 | print("FAILED %d comparison(s) against zoneinfo" % len(FAILS)) |
| 269 | return 1 |
| 270 | print("every comparison matches zoneinfo") |
| 271 | return 0 |
| 272 | |
| 273 | |
| 274 | if __name__ == "__main__": |
| 275 | sys.exit(main()) |