#!/usr/bin/env python3 """test_json.py — verify `sfile --json`. For every synthetic fixture (tests/make_fixtures.py) this checks: 1. the --json output parses as JSON (one object per line); 2. it carries the same facts as the human-readable output on the same file (format, identification method, magic, every header field, document decode, hex dump) — the text table is the reference, JSON must not disagree with it; 3. exit codes match between modes (0 identified, 2 unreadable, 3 unknown); 4. geotags appear when geotag_scan() finds a location (the tests/geotag/ fixtures: a JPEG with EXIF GPS, an MP4 with two QuickTime locations, a JPEG with a mechanism but no location). Header latitude/longitude FIELDS (e.g. the SPS fixture) are not geotags — task 678 has no geotagging mechanism, so no key. Usage: python3 tests/test_json.py [sfile_binary] """ import json import math import os import re import subprocess import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from make_fixtures import build_fixtures SFILE = sys.argv[1] if len(sys.argv) > 1 else "./sfile" FAILURES = [] def check(name, cond, detail=""): print(f" {'PASS' if cond else 'FAIL'} {name}" + (f" — {detail}" if detail and not cond else "")) if not cond: FAILURES.append(name) def run(args): return subprocess.run(args, capture_output=True, text=True) def parse_text_fields(out): """(offset, size, name, value) rows of the header table. Only lines after the "Header (...-endian):" heading count: the hex dump of an unknown file (" 01 02 03 ...") would otherwise match the same shape. """ fields = [] in_table = False for line in out.splitlines(): if line.startswith("Header ("): in_table = True continue if not in_table: continue m = re.match(r"^ +(\d+) +(\d+) +(\S+) +(.*)$", line) if m: fields.append((int(m.group(1)), int(m.group(2)), m.group(3), m.group(4).rstrip())) return fields def json_display_value(field): """Rebuild the CLI's display string for a JSON field value.""" v = field["value"] if v is None: return "(beyond header window / EOF)" t = field["type"] if t in ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64"): return str(v) if t in ("f32", "f64"): return "%g" % v if t == "ascii": return '"%s"' % v return v # bytes: space-separated hex def check_parity(name, fixture, text, js): """The JSON object must say the same thing as the text output.""" m = re.search(r"^Format: (.+?) \((\S+)\) — task (\d+)$", text, re.M) if js["identified"]: check(f"{name}: format task", js["format"]["task"] == int(m.group(3)) and js["format"]["ext"] == m.group(2) and js["format"]["name"] == m.group(1)) m2 = re.search(r"^Identified by: (\w+)$", text, re.M) check(f"{name}: identified_by", js["identified_by"] == m2.group(1)) else: check(f"{name}: unidentified", js["identified"] is False) m3 = re.search(r"^Magic: ([0-9a-f ]+)at offset (\d+)$", text, re.M) if m3: check(f"{name}: magic", js["magic"]["bytes"] == m3.group(1).strip() and js["magic"]["offset"] == int(m3.group(2))) elif js.get("magic"): check(f"{name}: magic absent in text", False, "JSON has magic, text does not") text_fields = parse_text_fields(text) json_fields = js.get("header", {}).get("fields", []) check(f"{name}: field count", len(text_fields) == len(json_fields), f"text={len(text_fields)} json={len(json_fields)}") for (toff, tsize, tname, tval), jf in zip(text_fields, json_fields): same = (toff == jf["offset"] and tsize == jf["size"] and tname == jf["name"]) if jf["type"] in ("f32", "f64") and jf["value"] is not None: try: same = same and math.isclose(float(tval), jf["value"], rel_tol=1e-5) # text uses %g (6 sig. digits) except ValueError: same = False else: same = same and tval == json_display_value(jf) check(f"{name}: field {tname}", same, f"text={tval!r} json={jf}") m4 = re.search(r"^Document type: (\w+)$", text, re.M) if m4: doc = js.get("document", {}) check(f"{name}: document type", doc.get("type") == m4.group(1).lower()) for key, pat in (("declaration", r"^XML declaration: (.*)$"), ("root_element", r"^Root element: (.*)$"), ("version", r"^Version attribute: (.*)$"), ("first_key", r"^First key: (.*)$"), ("first_line", r"^First line: (.*)$")): mm = re.search(pat, text, re.M) if mm: check(f"{name}: document {key}", doc.get(key) == mm.group(1)) elif key in doc: check(f"{name}: document {key} absent in text", False) m5 = re.search(r"^First 64 bytes:\n (.*)$", text, re.M) if m5: check(f"{name}: hexdump", js.get("hexdump") == m5.group(1).strip()) # Geotagging section (text) vs "geotags" array (JSON) — both come # from geotag_scan(), so they must agree. lats = re.findall(r"^ gps_latitude: (-?[\d.]+)", text, re.M) lons = re.findall(r"^ gps_longitude: (-?[\d.]+)", text, re.M) srcs = re.findall(r"^ source: (.*)$", text, re.M) alts = re.findall(r"^ gps_altitude_m: (-?[\d.]+)", text, re.M) datums = re.findall(r"^ gps_datum: (.*)$", text, re.M) whens = re.findall(r"^ gps_datetime_utc: (.*)$", text, re.M) has_section = "Geotagging:\n" in text if has_section: g = js.get("geotags") check(f"{name}: geotags present", isinstance(g, list)) if isinstance(g, list): check(f"{name}: geotag count", len(g) == len(lats) == len(lons) == len(srcs), f"json={len(g)} text lat/lon/src={len(lats)}/{len(lons)}/{len(srcs)}") for i, gg in enumerate(g): if i >= len(lats): break check(f"{name}: geotag[{i}] lat/lon", math.isclose(gg["latitude"], float(lats[i]), abs_tol=1e-6) and math.isclose(gg["longitude"], float(lons[i]), abs_tol=1e-6)) check(f"{name}: geotag[{i}] source", gg["source"] == srcs[i]) if alts: check(f"{name}: geotag altitudes", sorted(float(a) for a in alts) == sorted(gg.get("altitude_m") for gg in g if "altitude_m" in gg)) if datums: check(f"{name}: geotag datums", sorted(datums) == sorted(gg.get("datum") for gg in g if "datum" in gg)) if whens: check(f"{name}: geotag datetimes", sorted(whens) == sorted(gg.get("datetime_utc") for gg in g if "datetime_utc" in gg)) if "none found (searched" in text: check(f"{name}: geotags empty", g == []) else: check(f"{name}: no geotags key", "geotags" not in js) def main(): tmp = tempfile.mkdtemp(prefix="sfile-json-test-") fx = build_fixtures(tmp) missing = os.path.join(tmp, "does-not-exist.bin") print(f"sfile: {SFILE}") print(f"fixtures: {tmp}") # --- one file at a time: JSON parses, parity holds, exit codes match for key in ("png", "sps", "json", "xml", "txt", "unknown", "empty_png", "webm", "wab"): path = fx[key] text = run([SFILE, path]) js_run = run([SFILE, "--json", path]) check(f"{key}: exit code", text.returncode == js_run.returncode, f"text={text.returncode} json={js_run.returncode}") lines = [ln for ln in js_run.stdout.splitlines() if ln.strip()] check(f"{key}: one JSON object", len(lines) == 1, f"{len(lines)} lines") if len(lines) != 1: continue try: obj = json.loads(lines[0]) except json.JSONDecodeError as exc: check(f"{key}: JSON parses", False, str(exc)) continue check(f"{key}: JSON parses", True) check(f"{key}: file/size", obj["file"] == path and obj["size"] == os.path.getsize(path)) check_parity(key, path, text.stdout, obj) # --- geotags come from geotag_scan(), not from header fields: # the SPS fixture carries latitude/longitude FIELDS but task 678 # has no geotagging mechanism, so there is no "geotags" key. obj = json.loads(run([SFILE, "--json", fx["sps"]]).stdout.splitlines()[0]) check("sps: no geotags key (no mechanism)", "geotags" not in obj) # This PNG has a mechanism (eXIf/XMP) but carries no location. obj = json.loads(run([SFILE, "--json", fx["png"]]).stdout.splitlines()[0]) check("png: geotags empty (none found)", obj.get("geotags") == []) # --- real geotags, from tests/geotag/ (EXIF GPS JPEG, two-result # MP4, JPEG with a mechanism but no location) geo_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "geotag") for fname, want in ( ("test-gps.jpg", {"n": 1, "source": "EXIF GPS IFD (JPEG APP1 segment)", "lat": 37.7749, "lon": -122.4194, "alt": 10.0, "datum": "WGS-84", "when": "2026-12-01 12:34:56"}), ("test-gps.mp4", {"n": 2, "lat": 37.7749, "lon": -122.4194}), ("test-gps-no-gps.jpg", {"n": 0}), ): path = os.path.join(geo_dir, fname) text = run([SFILE, path]) js_run = run([SFILE, "--json", path]) check(f"{fname}: exit code", text.returncode == js_run.returncode == 0, f"text={text.returncode} json={js_run.returncode}") lines = [ln for ln in js_run.stdout.splitlines() if ln.strip()] check(f"{fname}: one JSON object", len(lines) == 1) if len(lines) != 1: continue obj = json.loads(lines[0]) g = obj.get("geotags") check(f"{fname}: geotag count", isinstance(g, list) and len(g) == want["n"], str(g)[:200]) if want["n"] > 0 and isinstance(g, list) and len(g) == want["n"]: check(f"{fname}: lat/lon", all(math.isclose(x["latitude"], want["lat"], abs_tol=1e-6) and math.isclose(x["longitude"], want["lon"], abs_tol=1e-6) for x in g)) if "source" in want: check(f"{fname}: source", g[0]["source"] == want["source"], str(g[0].get("source"))) if "alt" in want: check(f"{fname}: altitude", math.isclose(g[0].get("altitude_m", -1), want["alt"], abs_tol=1e-6)) if "datum" in want: check(f"{fname}: datum", g[0].get("datum") == want["datum"]) if "when" in want: check(f"{fname}: datetime", g[0].get("datetime_utc") == want["when"]) check_parity(fname, path, text.stdout, obj) # --- shared magic: the XML fixture's JSON lists the other candidates obj = json.loads(run([SFILE, "--json", fx["xml"]]).stdout.splitlines()[0]) check("xml: other_candidates listed", len(obj.get("other_candidates", [])) > 0 and all("ext" in c and "task" in c for c in obj["other_candidates"]), str(obj.get("other_candidates"))[:120]) # --- unreadable file: JSON error object, exit 2, stdout stays JSON r = run([SFILE, "--json", missing]) check("missing: exit 2", r.returncode == 2, f"got {r.returncode}") try: obj = json.loads(r.stdout.splitlines()[0]) check("missing: JSON error object", obj["identified"] is False and obj["size"] is None and isinstance(obj.get("error"), str) and obj["error"]) except (IndexError, json.JSONDecodeError) as exc: check("missing: JSON error object", False, str(exc)) # --- several files: one JSON object per line, worst exit code wins r = run([SFILE, "--json", fx["png"], fx["sps"], fx["unknown"]]) lines = [ln for ln in r.stdout.splitlines() if ln.strip()] check("multi: three JSON lines", len(lines) == 3, f"{len(lines)} lines") check("multi: exit 3 (one unknown)", r.returncode == 3, f"got {r.returncode}") try: objs = [json.loads(ln) for ln in lines] check("multi: all parse", True) check("multi: tasks in order", [o.get("format", {}).get("task") for o in objs] == [564, 678, None]) except json.JSONDecodeError as exc: check("multi: all parse", False, str(exc)) r = run([SFILE, "--json", fx["png"], missing]) check("multi: exit 2 beats 3", r.returncode == 2, f"got {r.returncode}") print() if FAILURES: print(f"FAILED: {len(FAILURES)} check(s): {', '.join(FAILURES)}") return 1 print("test_json: all checks passed") return 0 if __name__ == "__main__": sys.exit(main())