#!/usr/bin/env python3 """tests/tz_diff.py - differential test of plugin_time against real tzdata. `tests/run.sh` pins epochs it was written from. That catches regressions, but it cannot catch a *belief*: if the plugin and the suite author both think 2040-07-01 in New York is EST, the suite passes and the answer is still wrong. This harness asks a second, independent implementation instead - Python's `zoneinfo` over the host's own tz database - and compares field by field. It is what found the two bugs the offline suite could not: * the post-2037 transition list was returned as-is instead of handing over to the zone's POSIX rule, so every northern zone answered "standard time" for every date after 2038 (401 mismatches); * a southern-hemisphere DST rule was tested as a window rather than as sorted events, so 60 zones reported DST through their winter (60 more). Skips cleanly (exit 0) when `zoneinfo` is unavailable or has no tz database, so a node without Python's tzdata is never blocked by it. python3 tests/tz_diff.py # default sweep, ~40 s python3 tests/tz_diff.py --quick # one instant, ~5 s python3 tests/tz_diff.py --strict # exit 2 when zoneinfo is missing """ import argparse import datetime import json import os import subprocess import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_time") # Instants chosen to land on both sides of the transitions that matter: the # spring and autumn changes in each hemisphere, a leap year, and two dates well # past the point where the compiled tz table stops generating transitions # (2037), where only each zone's own POSIX rule can answer. DATES = [ datetime.datetime(2026, 1, 15, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 3, 29, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 7, 15, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 10, 25, tzinfo=datetime.timezone.utc), datetime.datetime(2028, 2, 29, tzinfo=datetime.timezone.utc), datetime.datetime(2038, 3, 28, tzinfo=datetime.timezone.utc), datetime.datetime(2038, 7, 1, tzinfo=datetime.timezone.utc), datetime.datetime(2040, 6, 1, tzinfo=datetime.timezone.utc), ] QUICK_DATES = [datetime.datetime(2026, 11, 14, tzinfo=datetime.timezone.utc)] # Hours around each date, so a transition that lands mid-day is crossed too. HOUR_OFFSETS = list(range(-36, 60, 7)) QUICK_HOURS = [0] # convert_time: wall times that only exist once, once-twice (fall back) and # never (spring forward) depending on the zone. WALL_TIMES = [(0, 0), (1, 30), (2, 30), (3, 30), (9, 0), (12, 30), (23, 59)] CONVERT_TARGETS = ["UTC", "Asia/Kathmandu", "Australia/Lord_Howe"] FAILS = [] def ok(desc): print(" ok %s" % desc) def bad(desc, detail=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" " + str(detail)[:300]) if detail else "")) def mcp(requests, now=None): """Run one --mcp session and return the parsed responses, in order.""" env = dict(os.environ) if now: env["SX_TIME_NOW"] = now payload = "\n".join(json.dumps(r) for r in requests) + "\n" out = subprocess.run([BIN, "--mcp"], input=payload.encode(), capture_output=True, env=env, timeout=300).stdout return [json.loads(l) for l in out.decode("utf-8", "replace").splitlines() if l.strip()] def struct_of(resp): result = resp.get("result", {}) if result.get("isError"): return {"error": result.get("content", [{}])[0].get("text", "")} return result.get("structuredContent", {}) def iso(obj, key): return obj.get(key, "") if isinstance(obj, dict) else "" def diff_current(zones, dates, hours): total = 0 for date in dates: for h in hours: now = date + datetime.timedelta(hours=h) stamp = now.strftime("%Y-%m-%dT%H:%M:%SZ") reqs = [{"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", "params": {"name": "get_current_time", "arguments": {"timezone": z}}} for i, z in enumerate(zones)] out = mcp(reqs, now=stamp) if len(out) != len(zones): bad("get_current_time @ %s returned %d of %d responses" % (stamp, len(out), len(zones))) continue epoch = int(now.timestamp()) for z, resp in zip(zones, out): got = struct_of(resp) ref = datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)\ .astimezone(__import__("zoneinfo").ZoneInfo(z)) expect = { "timezone": z, "datetime": ref.isoformat(timespec="seconds"), "day_of_week": ref.strftime("%A"), "is_dst": bool(ref.dst()), } total += 1 for key, want in expect.items(): if got.get(key) != want: bad("get_current_time %s @ %s: %s = %r, zoneinfo says %r" % (z, stamp, key, got.get(key), want)) break return total def diff_convert(zones, dates): from zoneinfo import ZoneInfo total = 0 for date in dates: stamp = date.strftime("%Y-%m-%dT%H:%M:%SZ") reqs, meta = [], [] for z in zones: for target in CONVERT_TARGETS: for hh, mm in WALL_TIMES: reqs.append({"jsonrpc": "2.0", "id": len(reqs) + 1, "method": "tools/call", "params": {"name": "convert_time", "arguments": { "source_timezone": z, "time": "%02d:%02d" % (hh, mm), "target_timezone": target}}}) meta.append((z, target, hh, mm)) out = mcp(reqs, now=stamp) if len(out) != len(meta): bad("convert_time @ %s returned %d of %d responses" % (stamp, len(out), len(meta))) continue for (src, dst, hh, mm), resp in zip(meta, out): total += 1 zs, zt = ZoneInfo(src), ZoneInfo(dst) # "Today" in the source zone, at the requested wall time. now_src = date.astimezone(zs) wall = datetime.datetime(now_src.year, now_src.month, now_src.day, hh, mm, tzinfo=zs) # A wall time skipped by a clock change does not survive a round # trip through UTC; the reference server errors on it. round_trip = datetime.datetime.fromtimestamp(wall.timestamp(), zs) skipped = round_trip.replace(tzinfo=None) != wall.replace(tzinfo=None) # A wall time repeated by a clock change has a second reading at a # different offset (Python's fold=1). fold1 = wall.replace(fold=1) ambiguous = fold1.utcoffset() != wall.utcoffset() got = struct_of(resp) if skipped: if not got.get("error"): bad("convert_time %s %02d:%02d @ %s should be an error " "(the wall time does not exist)" % (src, hh, mm, stamp)) elif "does not exist" not in got["error"]: bad("convert_time %s %02d:%02d: skipped-hour error text is %r" % (src, hh, mm, got["error"])) continue if got.get("error"): bad("convert_time %s %02d:%02d @ %s errored: %r" % (src, hh, mm, stamp, got["error"])) continue target = wall.astimezone(zt) if iso(got.get("source"), "datetime") != wall.isoformat(timespec="seconds"): bad("convert_time %s %02d:%02d @ %s: source %r, zoneinfo %r" % (src, hh, mm, stamp, iso(got.get("source"), "datetime"), wall.isoformat(timespec="seconds"))) continue if iso(got.get("target"), "datetime") != target.isoformat(timespec="seconds"): bad("convert_time %s %02d:%02d -> %s @ %s: target %r, zoneinfo %r" % (src, hh, mm, dst, stamp, iso(got.get("target"), "datetime"), target.isoformat(timespec="seconds"))) continue hours = (target.utcoffset() - wall.utcoffset()).total_seconds() / 3600 want = ("%+.1fh" % hours) if float(hours).is_integer() \ else ("%+.2f" % hours).rstrip("0").rstrip(".") + "h" if got.get("time_difference") != want: bad("convert_time %s -> %s @ %s: difference %r, expected %r" % (src, dst, stamp, got.get("time_difference"), want)) continue later = got.get("later_occurrence") if ambiguous: if not later: bad("convert_time %s %02d:%02d @ %s: the hour repeats but no " "later_occurrence was reported" % (src, hh, mm, stamp)) continue later_target = fold1.astimezone(zt) if iso(later.get("source"), "datetime") != fold1.isoformat(timespec="seconds"): bad("convert_time %s %02d:%02d @ %s: later source %r, zoneinfo %r" % (src, hh, mm, stamp, iso(later.get("source"), "datetime"), fold1.isoformat(timespec="seconds"))) elif iso(later.get("target"), "datetime") != later_target.isoformat(timespec="seconds"): bad("convert_time %s %02d:%02d -> %s @ %s: later target %r, " "zoneinfo %r" % (src, hh, mm, dst, stamp, iso(later.get("target"), "datetime"), later_target.isoformat(timespec="seconds"))) elif later: bad("convert_time %s %02d:%02d @ %s: reported a later_occurrence " "for an unambiguous time" % (src, hh, mm, stamp)) return total def main(): ap = argparse.ArgumentParser() ap.add_argument("--quick", action="store_true", help="one instant instead of the full sweep (~5 s)") ap.add_argument("--strict", action="store_true", help="exit 2 when zoneinfo is unavailable instead of skipping") args = ap.parse_args() try: from zoneinfo import ZoneInfo, available_timezones except ImportError: print("zoneinfo is not available (Python < 3.9) - skipping the differential run") return 2 if args.strict else 0 if not os.access(BIN, os.X_OK): bad("plugin_time is missing - run make first") return 1 # `localtime` is a symlink on some hosts and not an IANA key; the plugin # refuses it on purpose, so it is not a comparison candidate. zones = sorted(z for z in available_timezones() if z != "localtime" and "/" in z or z in ("UTC", "GMT")) if not zones: print("no tz database on this host - skipping the differential run") return 2 if args.strict else 0 dates = QUICK_DATES if args.quick else DATES hours = QUICK_HOURS if args.quick else HOUR_OFFSETS print("differential run: %d zones x %d instants" % (len(zones), len(dates) * len(hours))) before = len(FAILS) n_current = diff_current(zones, dates, hours) print(" get_current_time: %d comparisons, %d failures so far" % (n_current, len(FAILS) - before)) if args.quick: print(" convert_time: skipped in --quick mode") else: before = len(FAILS) n_convert = diff_convert(zones, dates) print(" convert_time: %d comparisons, %d failures so far" % (n_convert, len(FAILS) - before)) print("") if FAILS: print("FAILED %d comparison(s) against zoneinfo" % len(FAILS)) return 1 print("every comparison matches zoneinfo") return 0 if __name__ == "__main__": sys.exit(main())