Created
December 17, 2025 02:37
-
-
Save simonw/2281f0c03145e17ed7caf6c55deeea5f to your computer and use it in GitHub Desktop.
Run git clone https://github.com/cbor/test-vectors && cd test-vectors - then in that folder run: uv run test_cbor2.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = [ | |
| # "cbor2" | |
| # ] | |
| # /// | |
| import base64 | |
| import datetime as dt | |
| import json | |
| import math | |
| import re | |
| import cbor2 | |
| def parse_diag(diag: str): | |
| if diag == "Infinity": | |
| return float("inf") | |
| if diag == "-Infinity": | |
| return float("-inf") | |
| if diag == "NaN": | |
| return float("nan") | |
| if diag == "undefined": | |
| return cbor2.undefined | |
| m = re.fullmatch(r"simple\((\d+)\)", diag) | |
| if m: | |
| return ("simple", int(m.group(1))) | |
| m = re.fullmatch(r"h'([0-9a-fA-F]*)'", diag) | |
| if m: | |
| return bytes.fromhex(m.group(1)) | |
| m = re.fullmatch(r"\(_ (.*)\)", diag) | |
| if m: | |
| parts = [] | |
| for part in m.group(1).split(", "): | |
| mm = re.fullmatch(r"h'([0-9a-fA-F]*)'", part) | |
| if not mm: | |
| raise ValueError(f"unhandled diag part: {part!r}") | |
| parts.append(bytes.fromhex(mm.group(1))) | |
| return b"".join(parts) | |
| m = re.fullmatch(r"\{(\d+): (\d+), (\d+): (\d+)\}", diag) | |
| if m: | |
| a, b, c, d = map(int, m.groups()) | |
| return {a: b, c: d} | |
| m = re.fullmatch(r"(\d+)\((.*)\)", diag) | |
| if m: | |
| tag = int(m.group(1)) | |
| inner = m.group(2) | |
| if tag == 0: | |
| s = json.loads(inner) | |
| if s.endswith("Z"): | |
| s = s[:-1] + "+00:00" | |
| return dt.datetime.fromisoformat(s) | |
| if tag == 1: | |
| seconds = json.loads(inner) | |
| return dt.datetime.fromtimestamp(seconds, tz=dt.timezone.utc) | |
| if inner.startswith('"') and inner.endswith('"'): | |
| val = json.loads(inner) | |
| elif inner.startswith("h'") and inner.endswith("'"): | |
| val = bytes.fromhex(inner[2:-1]) | |
| else: | |
| val = json.loads(inner) | |
| return cbor2.CBORTag(tag, val) | |
| raise ValueError(f"unhandled diagnostic: {diag!r}") | |
| def eq(a, b) -> bool: | |
| if isinstance(b, tuple) and len(b) == 2 and b[0] == "simple" and isinstance(a, cbor2.CBORSimpleValue): | |
| return a.value == b[1] | |
| if isinstance(a, tuple) and len(a) == 2 and a[0] == "simple" and isinstance(b, cbor2.CBORSimpleValue): | |
| return b.value == a[1] | |
| if isinstance(a, float) and isinstance(b, float): | |
| if math.isnan(a) and math.isnan(b): | |
| return True | |
| return a == b | |
| if isinstance(a, cbor2.CBORTag) and isinstance(b, cbor2.CBORTag): | |
| return a.tag == b.tag and eq(a.value, b.value) | |
| if isinstance(a, dict) and isinstance(b, dict): | |
| if a.keys() != b.keys(): | |
| return False | |
| return all(eq(a[k], b[k]) for k in a.keys()) | |
| if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): | |
| if len(a) != len(b): | |
| return False | |
| return all(eq(x, y) for x, y in zip(a, b)) | |
| return a == b | |
| def run(path: str = "appendix_a.json") -> int: | |
| vectors = json.load(open(path)) | |
| for i, v in enumerate(vectors): | |
| raw = base64.b64decode(v["cbor"]) | |
| assert raw.hex() == v["hex"].lower(), (i, "hex-mismatch") | |
| actual = cbor2.loads(raw) | |
| expected = v["decoded"] if "decoded" in v else parse_diag(v["diagnostic"]) | |
| assert eq(actual, expected), (i, "value-mismatch", expected, actual) | |
| assert eq(cbor2.loads(cbor2.dumps(actual)), actual), (i, "roundtrip-mismatch") | |
| print(f"PASS: {len(vectors)}/{len(vectors)} vectors") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(run()) |
Author
Author
Relevant conversation: https://news.ycombinator.com/item?id=46295771#46296725
Author
Transcript that created this in Codex CLI: https://gistpreview.github.io/?3753c9f64507e458b0d340a894edcbbd
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/cbor/test-vectors is a conformance suite, this is a script to exercise it using the
cbor2Python library.