#!/usr/bin/env python3 """Tests for the NativePort Web-Access API Benchmarks dataset package. Standard library only: python3 -m unittest discover -s tests -v Tests that exercise the generator against the real snapshot look for it at /tmp/nativeport-evals-current.json, overridable with the NP_EVALS_JSON environment variable. Determinism and exact-number behaviour are additionally proven against an embedded fixture, so those properties are covered even without the snapshot at hand. """ from __future__ import annotations import csv import hashlib import importlib.util import json import os import re import tempfile import unicodedata import unittest from pathlib import Path ROOT = Path(__file__).resolve().parent.parent DATA = ROOT / "data" CSV_PATH = DATA / "benchmarks.csv" METRIC_ROWS_PATH = DATA / "metric_rows.jsonl" JSONL_PATH = DATA / "benchmarks.jsonl" SUMMARY_PATH = DATA / "summary.json" DATA_FILE_NAMES = ("metric_rows.jsonl", "benchmarks.csv", "benchmarks.jsonl", "summary.json") # The Hugging Face configs declared in the card's front matter and the file backing # each. Both must be JSONL: the Hub resolves one packaged loader for the whole # repository from the declared config data files and applies it to every config, so # mixing formats parses one config with the other's reader. The CSV backs no config. HUB_CONFIG_DATA_FILES = { "metric_rows": "data/metric_rows.jsonl", "evaluations": "data/benchmarks.jsonl", } README_PATH = ROOT / "README.md" LICENSE_PATH = ROOT / "LICENSE" MAKEFILE_PATH = ROOT / "Makefile" SOURCE_PATH = Path(os.environ.get("NP_EVALS_JSON", "/tmp/nativeport-evals-current.json")) BACKLINK = ( "https://nativeport.ai/methodology/" "?utm_source=huggingface&utm_medium=referral" "&utm_campaign=backlink_hf_web_access_benchmarks_20260811" ) # The licence approved for publication. These three values must agree with each other # and with the LICENSE file; nothing in the package may assert a different licence. LICENSE_HUB_ID = "cc-by-4.0" # Hugging Face front-matter identifier LICENSE_SPDX_ID = "CC-BY-4.0" # SPDX identifier LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/" LICENSE_LEGALCODE_URL = "https://creativecommons.org/licenses/by/4.0/legalcode" # SHA-256 of the CC BY 4.0 legal code reduced to its alphanumeric words (see # normalise_legal_text). Pinning the normalised form makes the assertion insensitive to # line wrapping, indentation and quote style while still detecting any change of # wording, however small. The digest was taken from the legal code served by # https://creativecommons.org/licenses/by/4.0/legalcode.en and independently # cross-checked against the SPDX license-list text for CC-BY-4.0; the two agree word # for word apart from list enumerators the CC page renders with CSS counters. CC_BY_4_0_NORMALISED_SHA256 = ( "b94bf421a55fe7bc2d698d314ee46b5e22bfcc7afbf93301978a35fd8bddd9ba" ) # Files that ship to the public Hugging Face repository. PUBLIC_UPLOAD_SET = ( "README.md", "LICENSE", "data/metric_rows.jsonl", "data/benchmarks.csv", "data/benchmarks.jsonl", "data/summary.json", "scripts/build_dataset.py", "tests/test_dataset.py", "Makefile", ) # Review and tooling documents that stay internal. They may be absent — this suite # ships with the public set and must pass without them. INTERNAL_ONLY = ("APPROVAL.md", "VALIDATION.md", "scripts/validate.py") def normalise_legal_text(text): """Reduce legal text to lowercase alphanumeric words separated by single spaces.""" return " ".join(re.findall(r"[a-z0-9]+", unicodedata.normalize("NFKC", text).lower())) def load_builder(): spec = importlib.util.spec_from_file_location( "build_dataset", ROOT / "scripts" / "build_dataset.py" ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module build_dataset = load_builder() def read_csv_rows(): with CSV_PATH.open(encoding="utf-8", newline="") as handle: return list(csv.DictReader(handle)) def read_jsonl_records(): with JSONL_PATH.open(encoding="utf-8") as handle: return [json.loads(line) for line in handle] def read_metric_row_records(): with METRIC_ROWS_PATH.open(encoding="utf-8") as handle: return [json.loads(line) for line in handle] def csv_text_of(value): """The CSV rendering of one typed tidy value, per the generator's contract.""" if isinstance(value, bool): return "true" if value else "false" if isinstance(value, (int, float)): return json.dumps(value) return value def read_summary(): return json.loads(SUMMARY_PATH.read_text(encoding="utf-8")) def sha256_of(path): return hashlib.sha256(path.read_bytes()).hexdigest() # A miniature snapshot exercising the shapes that matter: a trailing-zero float, an # integer-valued float, a small decimal, a zero, an empty note and a unicode label. FIXTURE = { "schema_version": 1, "source": "https://nativeport.ai/evals.json", "latest_run": "2026-08-05", "verbs": { "search": {"label": "Search", "description": "A query in, ranked links out"}, "extract_ai": {"label": "Extract · AI/schema", "description": "Fields from a page"}, }, "providers": { "beta": { "name": "Beta", "group": "Search", "category": "Search API", "page": "https://nativeport.ai/providers/beta/", "evals": [ { "verb": "search", "label": "Search", "composite": 7.5, "rank": 2, "of": 2, "top": False, "measured": "2026-08-05", "note": "", "metrics": [ {"key": "recall_at_10", "label": "Recall@10", "raw": 0.588, "value": "0.59"}, {"key": "latency_p50_ms", "label": "Latency p50", "raw": 886.0, "value": "886 ms"}, {"key": "error_rate_pct", "label": "Errors", "raw": 0, "value": "0%"}, ], } ], }, "alpha": { "name": "Alpha", "group": "Search", "category": "Search API", "page": "https://nativeport.ai/providers/alpha/", "evals": [ { "verb": "search", "label": "Search", "composite": 9.13, "rank": 1, "of": 2, "top": True, "measured": "2026-08-04", "note": "Comma, and \"quotes\" in the note.", "metrics": [ {"key": "recall_at_10", "label": "Recall@10", "raw": 0.62, "value": "0.62"}, {"key": "latency_p50_ms", "label": "Latency p50", "raw": 815.5, "value": "816 ms"}, { "key": "cost_per_useful_usd", "label": "Cost", "raw": 0.000484, "value": "$0.00048 / useful result", }, {"key": "error_rate_pct", "label": "Errors", "raw": 0.0, "value": "0%"}, ], }, { "verb": "extract_ai", "label": "Extract · AI/schema", "composite": 0.0, "rank": 1, "of": 1, "top": True, "measured": "2026-08-05", "note": "Every extraction failed.", "metrics": [ {"key": "field_accuracy", "label": "Field accuracy", "raw": 0.0, "value": "0.00"}, {"key": "latency_p50_ms", "label": "Latency p50", "raw": 0.0, "value": "0 ms"}, {"key": "error_rate_pct", "label": "Errors", "raw": 100.0, "value": "100%"}, ], }, ], }, "unscored": { "name": "Unscored", "group": "Search", "category": "Search API", "page": "https://nativeport.ai/providers/unscored/", "evals": [], }, }, "run": { "name": "2026-08-05", "scored_providers": 2, "catalog_providers": 3, "scorecards": 3, "capabilities": 2, "unscored_pairs": [], }, } def write_fixture(directory, document=None): path = Path(directory) / "fixture-evals.json" path.write_text( json.dumps(document if document is not None else FIXTURE, ensure_ascii=False), encoding="utf-8", ) return path class GeneratorDeterminismTest(unittest.TestCase): """The generator must be a pure function of its input bytes.""" def test_two_builds_from_the_fixture_are_byte_identical(self): with tempfile.TemporaryDirectory() as workspace: source = write_fixture(workspace) digests = [] for run in ("first", "second"): out = Path(workspace) / run build_dataset.build(source, out) digests.append( tuple( sha256_of(out / name) for name in DATA_FILE_NAMES ) ) self.assertEqual(digests[0], digests[1]) def test_outputs_carry_no_wall_clock_timestamp(self): with tempfile.TemporaryDirectory() as workspace: source = write_fixture(workspace) out = Path(workspace) / "out" summary = build_dataset.build(source, out) blob = json.dumps(summary) for field in ("generated_at", "timestamp", "build_time", "created_at"): self.assertNotIn(field, blob) def test_ordering_is_stable_and_independent_of_source_order(self): """Records sort by (capability, rank, provider), not by dict insertion order.""" def records_without_snapshot_hash(path): # Reordering the source changes its bytes, so the snapshot hash legitimately # differs; everything else must be identical. out = [] for line in path.read_text(encoding="utf-8").splitlines(): record = json.loads(line) record.pop("snapshot_sha256") out.append(record) return out with tempfile.TemporaryDirectory() as workspace: out = Path(workspace) / "out" build_dataset.build(write_fixture(workspace), out) first = records_without_snapshot_hash(out / "benchmarks.jsonl") shuffled = json.loads(json.dumps(FIXTURE)) shuffled["providers"] = { key: shuffled["providers"][key] for key in ("unscored", "alpha", "beta") } other = Path(workspace) / "shuffled" build_dataset.build(write_fixture(other.parent, shuffled), other) second = records_without_snapshot_hash(other / "benchmarks.jsonl") self.assertEqual(first, second) self.assertEqual( [record["evaluation_id"] for record in first], ["alpha:extract_ai", "alpha:search", "beta:search"], ) @unittest.skipUnless(SOURCE_PATH.exists(), f"snapshot not available at {SOURCE_PATH}") def test_committed_artifacts_match_a_fresh_rebuild(self): with tempfile.TemporaryDirectory() as workspace: out = Path(workspace) / "out" build_dataset.build(SOURCE_PATH, out) for name in DATA_FILE_NAMES: self.assertEqual( sha256_of(out / name), sha256_of(DATA / name), f"{name} differs from a rebuild of the recorded snapshot", ) class ExactNumericPreservationTest(unittest.TestCase): """Measured values must survive the pipeline character for character.""" def test_refuses_a_token_it_cannot_reproduce_exactly(self): document = json.loads(json.dumps(FIXTURE)) document["providers"]["alpha"]["evals"][0]["metrics"][0]["raw"] = 1.10 with tempfile.TemporaryDirectory() as workspace: # 1.10 must reach the parser as text, so patch the serialised form directly. path = Path(workspace) / "fixture-evals.json" blob = json.dumps(document, ensure_ascii=False).replace('"raw": 1.1,', '"raw": 1.10,', 1) self.assertIn('"raw": 1.10,', blob) path.write_text(blob, encoding="utf-8") with self.assertRaises(build_dataset.BuildError) as caught: build_dataset.build(path, Path(workspace) / "out") self.assertIn("round-trip", str(caught.exception)) def test_exact_number_keeps_the_source_token(self): for token in ("0.938", "886.0", "0.0003", "0.000484", "0", "100.0", "9.13"): text, value = build_dataset.exact_number(token, "$.test") self.assertEqual(text, token) self.assertEqual(json.dumps(value), token) @unittest.skipUnless(SOURCE_PATH.exists(), f"snapshot not available at {SOURCE_PATH}") def test_every_published_number_equals_its_source_token(self): document = json.loads(SOURCE_PATH.read_text(encoding="utf-8"), parse_float=str, parse_int=str) expected = {} for provider_id, provider in document["providers"].items(): for entry in provider.get("evals", []): key = f"{provider_id}:{entry['verb']}" expected[key] = { "composite": entry["composite"], "rank": entry["rank"], "of": entry["of"], "metrics": {m["key"]: m["raw"] for m in entry["metrics"]}, } self.assertTrue(expected) seen = set() for row in read_csv_rows(): reference = expected[row["evaluation_id"]] self.assertEqual(row["composite_score"], reference["composite"]) self.assertEqual(row["rank"], reference["rank"]) self.assertEqual(row["rank_of"], reference["of"]) self.assertEqual(row["metric_raw"], reference["metrics"][row["metric_key"]]) seen.add((row["evaluation_id"], row["metric_key"])) self.assertEqual( len(seen), sum(len(value["metrics"]) for value in expected.values()) ) for record in read_jsonl_records(): reference = expected[record["evaluation_id"]] self.assertEqual(json.dumps(record["composite_score"]), reference["composite"]) self.assertEqual(json.dumps(record["rank"]), reference["rank"]) self.assertEqual(json.dumps(record["rank_of"]), reference["of"]) for metric in record["metrics"]: self.assertEqual( json.dumps(metric["raw_value"]), reference["metrics"][metric["metric_key"]], f"{record['evaluation_id']}/{metric['metric_key']}", ) def test_display_values_are_not_substituted_for_measurements(self): for row in read_csv_rows(): self.assertNotEqual(row["metric_raw"], "") float(row["metric_raw"]) # parses as a number, unlike "816 ms" or "$0.0003 / call" class SchemaAndCountConsistencyTest(unittest.TestCase): def setUp(self): self.summary = read_summary() self.rows = read_csv_rows() self.records = read_jsonl_records() def test_csv_header_matches_the_generator_contract(self): with CSV_PATH.open(encoding="utf-8", newline="") as handle: header = next(csv.reader(handle)) self.assertEqual(header, build_dataset.TIDY_FIELDS) def test_row_counts_agree_across_artifacts(self): self.assertEqual(len(self.rows), self.summary["metric_row_count"]) self.assertEqual(len(read_metric_row_records()), self.summary["metric_row_count"]) self.assertEqual(len(self.records), self.summary["evaluation_count"]) self.assertEqual( sum(len(record["metrics"]) for record in self.records), self.summary["metric_row_count"], ) self.assertEqual( len({row["evaluation_id"] for row in self.rows}), self.summary["evaluation_count"], ) def test_counts_are_computed_not_asserted(self): summary = self.summary self.assertEqual( summary["provider_count_represented"], len({row["provider_id"] for row in self.rows}), ) self.assertEqual( summary["capability_count"], len({row["capability_id"] for row in self.rows}) ) self.assertEqual( summary["provider_count_in_catalog_without_evaluations"], summary["provider_count_in_source_catalog"] - summary["provider_count_represented"], ) self.assertTrue(all(summary["cross_check"].values()), summary["cross_check"]) def test_coverage_is_not_overstated(self): """The catalog is larger than the scored set; the dataset must say so.""" summary = self.summary self.assertLess( summary["provider_count_represented"], summary["provider_count_in_source_catalog"] ) self.assertGreater(summary["provider_count_in_catalog_without_evaluations"], 0) def test_measured_date_range_is_derived_from_the_rows(self): dates = sorted({row["measured_date"] for row in self.rows}) self.assertEqual(self.summary["measured_date_min"], dates[0]) self.assertEqual(self.summary["measured_date_max"], dates[-1]) self.assertEqual(self.summary["measured_dates"], dates) for value in dates: self.assertRegex(value, r"^\d{4}-\d{2}-\d{2}$") def test_summary_records_matching_output_hashes(self): for name, entry in self.summary["outputs"].items(): self.assertEqual(entry["sha256"], sha256_of(DATA / name), name) self.assertEqual(entry["bytes"], (DATA / name).stat().st_size, name) def test_every_csv_row_maps_onto_a_jsonl_record(self): nested = { record["evaluation_id"]: {m["metric_key"]: m for m in record["metrics"]} for record in self.records } for row in self.rows: metric = nested[row["evaluation_id"]][row["metric_key"]] self.assertEqual(row["metric_label"], metric["metric_label"]) self.assertEqual(row["metric_display"], metric["display_value"]) self.assertEqual(int(row["metric_index"]), metric["metric_index"]) def test_capability_metric_keys_are_documented_in_the_summary(self): for capability in self.summary["capabilities"]: observed = { row["metric_key"] for row in self.rows if row["capability_id"] == capability["capability_id"] } self.assertEqual(observed, set(capability["metric_keys"])) self.assertEqual( capability["evaluation_count"], len( { row["evaluation_id"] for row in self.rows if row["capability_id"] == capability["capability_id"] } ), ) def test_excluded_commercial_fields_did_not_leak(self): blob = "".join( (DATA / name).read_text(encoding="utf-8") for name in DATA_FILE_NAMES ) for field in ( "pricing_entry", "choose_if", "avoid_if", "latency_note", "call_body", "call_method", "Authorization", "sign_up", ): self.assertNotIn(field, blob, f"{field} leaked into the published data") class HubConfigFormatTest(unittest.TestCase): """Both declared configs must be backed by the same data format. The Hub resolves one packaged loader for the whole repository from the declared config data files and applies it to every config. A repository that mixes CSV and JSONL across configs therefore has one config parsed by the other's reader: `load_dataset(..., "evaluations")` failed on the published revision, and the datasets-server first-rows call for it failed with it. These tests pin the fix. """ def setUp(self): self.front = README_PATH.read_text(encoding="utf-8") self.front = self.front[4 : self.front.find("\n---\n", 4)] def declared_configs(self): """(config_name, path) pairs read from the front matter, in declared order.""" pairs, config_name = [], None for line in self.front.splitlines(): stripped = line.strip() if stripped.startswith("- config_name:"): config_name = stripped.split(":", 1)[1].strip() elif stripped.startswith("path:"): pairs.append((config_name, stripped.split(":", 1)[1].strip())) return pairs def test_front_matter_declares_the_expected_config_to_file_mapping(self): self.assertEqual(dict(self.declared_configs()), HUB_CONFIG_DATA_FILES) self.assertEqual(self.declared_configs(), list(HUB_CONFIG_DATA_FILES.items())) def test_generator_and_card_agree_on_the_config_mapping(self): self.assertEqual(build_dataset.HUB_CONFIG_DATA_FILES, HUB_CONFIG_DATA_FILES) self.assertEqual(read_summary()["hub_config_data_files"], HUB_CONFIG_DATA_FILES) def test_every_config_data_file_is_jsonl(self): """The regression itself: one format across all declared configs.""" suffixes = {Path(path).suffix for _, path in self.declared_configs()} self.assertEqual(suffixes, {".jsonl"}, f"configs mix formats: {suffixes}") for _, relative in self.declared_configs(): self.assertTrue((ROOT / relative).is_file(), relative) def test_no_config_points_at_the_csv(self): for _, relative in self.declared_configs(): self.assertNotEqual(relative, "data/benchmarks.csv") self.assertEqual( read_summary()["downloadable_only_artifacts"], ["data/benchmarks.csv"] ) def test_every_config_data_file_parses_as_json_lines(self): """Not just the extension: every line of every config file is one JSON object.""" for config_name, relative in self.declared_configs(): path = ROOT / relative with path.open(encoding="utf-8") as handle: lines = handle.read().splitlines() self.assertTrue(lines, relative) for number, line in enumerate(lines, start=1): try: record = json.loads(line) except json.JSONDecodeError as exc: self.fail(f"{config_name} ({relative}) line {number}: {exc}") self.assertIsInstance(record, dict, f"{relative} line {number}") def test_config_records_are_uniform_in_fields_and_types(self): """One type per field across every record. The loader infers one Arrow column type per field from the records it reads. A field that is an integer on one line and a float or a string on another is the other common way a config loads locally but fails the viewer's first-rows call. """ for config_name, relative in self.declared_configs(): lines = (ROOT / relative).read_text(encoding="utf-8").splitlines() records = [json.loads(line) for line in lines] types = {} for index, record in enumerate(records): self.assertEqual( list(record), list(records[0]), f"{config_name} record {index}: field set or order differs", ) for field, value in record.items(): types.setdefault(field, set()).add(type(value).__name__) mixed = {field: sorted(seen) for field, seen in types.items() if len(seen) > 1} self.assertEqual(mixed, {}, f"{config_name}: fields change type between records") def test_csv_is_still_published_as_a_downloadable_artifact(self): self.assertTrue(CSV_PATH.is_file()) self.assertIn("benchmarks.csv", read_summary()["outputs"]) self.assertIn("data/benchmarks.csv", PUBLIC_UPLOAD_SET) readme = " ".join(README_PATH.read_text(encoding="utf-8").split()) self.assertIn("`data/benchmarks.csv` is a download rather than a config", readme) self.assertIn("| `data/benchmarks.csv` | 297 |", readme) class TidyMirrorEquivalenceTest(unittest.TestCase): """data/benchmarks.csv and data/metric_rows.jsonl are the same tidy rows. The CSV is the approved artifact; the JSONL is what the `metric_rows` config loads. They are written from one row builder, and these tests hold them to that: same fields in the same order, same count, same order of rows, and every value equal — numbers compared as text, so a rounded or reformatted measurement fails here. """ def setUp(self): self.rows = read_csv_rows() self.records = read_metric_row_records() def test_both_tidy_views_carry_the_same_row_count(self): summary = read_summary() self.assertEqual(len(self.rows), summary["metric_row_count"]) self.assertEqual(len(self.records), summary["metric_row_count"]) self.assertEqual(len(self.rows), len(self.records)) def test_field_names_and_order_are_identical(self): with CSV_PATH.open(encoding="utf-8", newline="") as handle: header = next(csv.reader(handle)) self.assertEqual(header, build_dataset.TIDY_FIELDS) for index, record in enumerate(self.records): self.assertEqual(list(record), build_dataset.TIDY_FIELDS, f"record {index}") def test_rows_are_semantically_identical_in_the_same_order(self): for index, (row, record) in enumerate(zip(self.rows, self.records)): self.assertEqual( (record["evaluation_id"], record["metric_key"]), (row["evaluation_id"], row["metric_key"]), f"row {index}: the two tidy views are ordered differently", ) for field in build_dataset.TIDY_FIELDS: self.assertEqual( csv_text_of(record[field]), row[field], f"row {index} field {field}", ) def test_numbers_are_preserved_exactly_not_reformatted(self): """Every numeric field is a JSON number whose text is the CSV token verbatim.""" numeric = ("metric_raw", "composite_score", "metric_index", "rank", "rank_of", "composite_scale_max") compared = 0 for row, record in zip(self.rows, self.records): for field in numeric: value = record[field] self.assertIsInstance(value, (int, float), field) self.assertNotIsInstance(value, bool, field) self.assertEqual(json.dumps(value), row[field], f"{field} in {row['evaluation_id']}") compared += 1 self.assertIsInstance(record["is_capability_top"], bool) self.assertEqual(csv_text_of(record["is_capability_top"]), row["is_capability_top"]) self.assertEqual(compared, len(self.rows) * len(numeric)) def test_tidy_jsonl_agrees_with_the_nested_evaluations(self): """The third view must carry the same measurements as the other two.""" nested = { record["evaluation_id"]: {m["metric_key"]: m for m in record["metrics"]} for record in read_jsonl_records() } seen = set() for record in self.records: metric = nested[record["evaluation_id"]][record["metric_key"]] self.assertEqual(json.dumps(record["metric_raw"]), json.dumps(metric["raw_value"])) self.assertEqual(record["metric_display"], metric["display_value"]) self.assertEqual(record["metric_label"], metric["metric_label"]) self.assertEqual(record["metric_index"], metric["metric_index"]) seen.add((record["evaluation_id"], record["metric_key"])) self.assertEqual(len(seen), len(self.records)) self.assertEqual( len(seen), sum(len(metrics) for metrics in nested.values()) ) def test_generator_emits_both_tidy_views_from_one_builder(self): """A fixture build: change nothing, and the two files still agree row for row.""" with tempfile.TemporaryDirectory() as workspace: out = Path(workspace) / "out" build_dataset.build(write_fixture(workspace), out) with (out / "benchmarks.csv").open(encoding="utf-8", newline="") as handle: rows = list(csv.DictReader(handle)) records = [ json.loads(line) for line in (out / "metric_rows.jsonl").read_text(encoding="utf-8").splitlines() ] self.assertEqual(len(rows), len(records)) self.assertEqual(len(rows), 10) # 3 + 4 + 3 metrics in the fixture for row, record in zip(rows, records): self.assertEqual(list(record), build_dataset.TIDY_FIELDS) for field in build_dataset.TIDY_FIELDS: self.assertEqual(csv_text_of(record[field]), row[field], field) class RankingIntegrityTest(unittest.TestCase): def setUp(self): self.records = read_jsonl_records() def test_rank_is_within_bounds(self): for record in self.records: self.assertGreaterEqual(record["rank"], 1, record["evaluation_id"]) self.assertLessEqual(record["rank"], record["rank_of"], record["evaluation_id"]) def test_top_flag_agrees_with_rank(self): for record in self.records: self.assertEqual( record["is_capability_top"], record["rank"] == 1, record["evaluation_id"] ) def test_composite_is_inside_the_declared_scale(self): for record in self.records: self.assertEqual(record["composite_scale_max"], 10) self.assertGreaterEqual(record["composite_score"], 0, record["evaluation_id"]) self.assertLessEqual(record["composite_score"], 10, record["evaluation_id"]) def test_ranks_are_unique_and_complete_within_each_capability(self): by_capability = {} for record in self.records: by_capability.setdefault(record["capability_id"], []).append(record) for capability_id, group in by_capability.items(): ranks = sorted(record["rank"] for record in group) self.assertEqual(ranks, list(range(1, len(group) + 1)), capability_id) self.assertEqual( {record["rank_of"] for record in group}, {len(group)}, capability_id ) def test_no_duplicate_evaluation_keys(self): keys = [record["evaluation_id"] for record in self.records] self.assertEqual(len(keys), len(set(keys))) pairs = [(record["provider_id"], record["capability_id"]) for record in self.records] self.assertEqual(len(pairs), len(set(pairs))) for record in self.records: self.assertEqual( record["evaluation_id"], f"{record['provider_id']}:{record['capability_id']}", ) def test_metric_keys_are_unique_within_an_evaluation(self): for record in self.records: keys = [metric["metric_key"] for metric in record["metrics"]] self.assertEqual(len(keys), len(set(keys)), record["evaluation_id"]) self.assertEqual( [metric["metric_index"] for metric in record["metrics"]], list(range(len(keys))), record["evaluation_id"], ) class UrlPolicyTest(unittest.TestCase): URL_FIELDS = ("provider_page_url", "source_url") def test_data_urls_are_https(self): for row in read_csv_rows() + read_metric_row_records() + read_jsonl_records(): for field in self.URL_FIELDS: self.assertTrue(row[field].startswith("https://"), f"{field}={row[field]}") def test_summary_urls_are_https(self): summary = read_summary() for field in ("source_url", "methodology_url", "leaderboards_url"): self.assertTrue(summary[field].startswith("https://"), field) def test_no_plain_http_anywhere_in_the_package(self): offenders = [] for path in sorted(ROOT.rglob("*")): if not path.is_file() or "__pycache__" in path.parts: continue try: text = path.read_text(encoding="utf-8") except (UnicodeDecodeError, OSError): continue # self-avoiding pattern: matches "http://" but not this line offenders.extend( f"{path.relative_to(ROOT)}: {hit}" for hit in re.findall(r"htt[p]://[^\s\"'<>)\]]+", text) ) self.assertEqual(offenders, []) def test_data_files_carry_no_campaign_tagged_urls(self): for name in DATA_FILE_NAMES: self.assertNotIn("utm_", (DATA / name).read_text(encoding="utf-8"), name) class ReadmeCardTest(unittest.TestCase): def setUp(self): self.text = README_PATH.read_text(encoding="utf-8") def front_matter(self): return self.text[4 : self.text.find("\n---\n", 4)] def section(self, heading): """Body of one `## ` section, up to the next one.""" start = self.text.index(heading) + len(heading) rest = self.text[start:] end = rest.find("\n## ") return rest if end == -1 else rest[:end] def flat(self, heading): """Section body with all runs of whitespace collapsed, so prose assertions do not depend on where the source happens to wrap.""" return " ".join(self.section(heading).split()) def test_front_matter_is_well_formed(self): self.assertTrue(self.text.startswith("---\n")) end = self.text.find("\n---\n", 4) self.assertNotEqual(end, -1, "front matter is not closed") front = self.text[4:end] self.assertNotIn("\t", front) top_keys = [ line.split(":", 1)[0] for line in front.splitlines() if line and not line.startswith((" ", "-", "#")) ] self.assertEqual( top_keys, ["license", "pretty_name", "language", "tags", "size_categories", "configs"], ) for line in front.splitlines(): if line and not line.startswith((" ", "-")): self.assertIn(":", line, line) def test_title_and_pretty_name_match(self): self.assertIn("pretty_name: NativePort Web-Access API Benchmarks", self.text) self.assertIn("\n# NativePort Web-Access API Benchmarks\n", self.text) def test_front_matter_declares_the_approved_licence(self): """Exactly one licence key, carrying exactly the approved identifier.""" front = self.front_matter() license_lines = [line for line in front.splitlines() if line.startswith("license")] self.assertEqual(license_lines, [f"license: {LICENSE_HUB_ID}"]) # license_name / license_link belong to `license: other`; they must not appear. for key in ("license_name", "license_link", "license_details"): self.assertNotIn(key, front, key) for competing in ( "cc-by-nc", "cc-by-sa", "cc-by-nd", "cc0-1.0", "odc-by", "odbl", "apache-2.0", "unlicense", "all-rights-reserved", ): self.assertNotIn(competing, front, competing) def test_licensing_section_names_cc_by_4_0_and_the_canonical_urls(self): section = self.flat("## Licensing") self.assertIn("Creative Commons Attribution 4.0 International", section) self.assertIn("CC BY 4.0", section) self.assertIn(LICENSE_URL, section) self.assertIn(LICENSE_LEGALCODE_URL, section) self.assertIn(LICENSE_SPDX_ID, section) self.assertIn("[`LICENSE`](LICENSE)", section) self.assertIn(f"license: {LICENSE_HUB_ID}", section) def test_licensing_section_no_longer_defers_the_decision(self): section = self.flat("## Licensing") for stale in ( "not been finalised", "not finalised", "all-rights-reserved", "no open-data licence is asserted", "seek permission before redistribution", "Until a licence is published", ): self.assertNotIn(stale, section, stale) def test_licensing_section_scopes_the_grant_to_what_nativeport_can_license(self): section = self.flat("## Licensing") for phrase in ( "NativePort licenses what it is in a position to license", "this dataset as a compilation", "the benchmark measurements NativePort itself produced", "The grant extends only to those rights and only to the extent NativePort holds them.", ): self.assertIn(phrase, section, phrase) def test_licensing_section_does_not_overstate_trademark_rights(self): """The licence covers NativePort's compilation, never third-party marks.""" section = self.flat("## Licensing") lowered = section.lower() for overstatement in ( "trademarks are licensed", "trademark rights are licensed", "licenses the trademarks", "licences the trademarks", "grants you the trademarks", "grant of trademark", "including any trademarks", "trademark licence is granted", "trademark license is granted", ): self.assertNotIn(overstatement, lowered, overstatement) # Every sentence that touches marks must withhold rather than grant: it carries # a negation, or it attributes the marks to their owners. denials = ("not ", "no ", "nor ", "never ", "remain the property", "outside what") sentences = [ sentence for sentence in re.split(r"(?<=[.;])\s+", lowered) if "trademark" in sentence or " marks" in sentence ] self.assertTrue(sentences, "the licensing section must address trademarks") for sentence in sentences: self.assertTrue( any(denial in sentence for denial in denials), f"trademark sentence does not withhold a grant: {sentence}", ) def test_licensing_section_states_attribution_and_warranty_terms(self): section = self.flat("## Licensing") for phrase in ( "Credit *NativePort*", "state that the material is under CC BY 4.0 with a link to the licence", "indicate whether you modified it", "as-is and as-available, without warranties or conditions of any kind", ): self.assertIn(phrase, section, phrase) def test_trademark_notice_denies_any_licence_grant_in_marks(self): section = self.flat("## Trademark notice") self.assertIn( "The CC BY 4.0 licence described under [Licensing](#licensing) grants " "**no** rights in any of these marks", section, ) def test_declared_data_files_exist(self): front = self.front_matter() for relative in re.findall(r"path:\s*(\S+)", front): self.assertTrue((ROOT / relative).is_file(), relative) def test_backlink_is_exact_and_appears_once(self): self.assertEqual(self.text.count(BACKLINK), 1) self.assertEqual(len(re.findall(r"utm_source=", self.text)), 1) self.assertEqual(len(re.findall(r"utm_campaign=", self.text)), 1) self.assertIn( f"[How we measure]({BACKLINK})", self.text.replace("\n", " ").replace(" ", " "), ) def test_backlink_is_contextual_not_the_point_of_the_page(self): """The card must stand on its own: the link sits inside the methodology prose.""" index = self.text.index(BACKLINK) self.assertGreater(index, len(self.text) // 3, "backlink appears too early to be contextual") self.assertIn("## Methodology", self.text[:index]) def test_required_sections_exist(self): for heading in ( "## Disclosure", "## Dataset structure", "## Usage", "## Methodology", "## Provenance and reproducibility", "## Limitations and scope", "## Update policy", "## Licensing", "## Trademark notice", "## Citation", ): self.assertIn(heading, self.text, heading) def test_first_party_disclosure_is_explicit(self): for phrase in ( "produced by **NativePort**", "own first-party benchmark", "not an independent third-party evaluation", ): self.assertIn(phrase, self.text, phrase) def test_limitations_cover_the_known_risks(self): section = self.text[self.text.index("## Limitations and scope") :] section = section[: section.index("## Update policy")] for phrase in ( "Coverage is partial", "Composites are capability-local", "Single point in time", "First-party measurement", "uptime", ): self.assertIn(phrase, section, phrase) def test_card_does_not_claim_the_whole_catalog_is_benchmarked(self): summary = read_summary() represented = summary["provider_count_represented"] catalog = summary["provider_count_in_source_catalog"] self.assertIn(f"**{represented} commercial web-access", self.text) self.assertIn(f"{represented} of the {catalog} providers in the source catalog", self.text) def test_headline_counts_match_the_generated_summary(self): summary = read_summary() self.assertIn(f"**{summary['evaluation_count']} provider × capability", self.text) self.assertIn(f"**{summary['capability_count']} capabilities**", self.text) self.assertIn(f"**{summary['metric_row_count']} metric rows**", self.text) self.assertIn(summary["snapshot_sha256"], self.text) self.assertIn(summary["latest_run"], self.text) def test_capability_comparison_caveat_is_present(self): self.assertIn("Latency and cost are not comparable across capabilities", self.text) self.assertIn("averaging a provider's composites across capabilities", self.text) def test_trademark_notice_disclaims_endorsement(self): section = self.text[self.text.index("## Trademark notice") :] for phrase in ("trademarks of their respective owners", "does not\nimply any affiliation"): self.assertIn(phrase, section, phrase) class LicenseFileTest(unittest.TestCase): """LICENSE must be the complete, unmodified CC BY 4.0 legal code.""" def setUp(self): self.assertTrue(LICENSE_PATH.is_file(), "LICENSE is missing from the package") self.raw = LICENSE_PATH.read_bytes() self.text = self.raw.decode("utf-8") self.normalised = normalise_legal_text(self.text) def test_license_file_is_plain_unix_utf8_text(self): self.assertNotIn(b"\r", self.raw, "LICENSE must use unix line endings") self.assertTrue(self.raw.endswith(b"\n"), "LICENSE must end with a newline") self.assertNotIn("\t", self.text, "LICENSE must not contain tab characters") self.assertGreater( len(self.raw), 16000, "LICENSE is too short to be the full legal code" ) def test_license_text_is_the_canonical_cc_by_4_0_legal_code(self): digest = hashlib.sha256(self.normalised.encode("utf-8")).hexdigest() self.assertEqual( digest, CC_BY_4_0_NORMALISED_SHA256, "LICENSE wording differs from the canonical CC BY 4.0 legal code", ) def test_license_carries_every_section_of_the_legal_code(self): self.assertIn( "creative commons attribution 4 0 international public license", self.normalised ) for number, title in ( (1, "definitions"), (2, "scope"), (3, "license conditions"), (4, "sui generis database rights"), (5, "disclaimer of warranties and limitation of liability"), (6, "term and termination"), (7, "other terms and conditions"), (8, "interpretation"), ): self.assertIn(f"section {number} {title}", self.normalised, title) self.assertTrue( self.text.rstrip().endswith("Creative Commons may be contacted at creativecommons.org."), "LICENSE is truncated before the closing paragraph", ) def test_license_keeps_the_clauses_the_card_relies_on(self): for clause in ( "worldwide royalty free non sublicensable non exclusive irrevocable license", "reproduce and share the licensed material in whole or in part", "produce reproduce and share adapted material", "patent and trademark rights are not licensed under this public license", "extract reuse reproduce and share all or a substantial portion of the " "contents of the database", "as is and as available", ): self.assertIn(clause, self.normalised, clause) def test_license_is_not_a_different_creative_commons_flavour(self): for wrong in ( "noncommercial", "non commercial", "sharealike", "share alike", "noderivatives", "no derivatives", "cc0", ): self.assertNotIn(wrong, self.normalised, wrong) def test_license_agrees_with_the_identifier_declared_in_the_card(self): readme = README_PATH.read_text(encoding="utf-8") front = readme[4 : readme.find("\n---\n", 4)] self.assertIn(f"license: {LICENSE_HUB_ID}", front) self.assertIn("Creative Commons Attribution 4.0 International", self.text) class PublicUploadSetTest(unittest.TestCase): """The approved upload set must be complete and self-sufficient. APPROVAL.md, VALIDATION.md and scripts/validate.py are internal review and tooling documents that do not ship, so nothing in the public set may depend on them. """ def test_every_public_file_is_present(self): for relative in PUBLIC_UPLOAD_SET: self.assertTrue((ROOT / relative).is_file(), f"{relative} is missing") def test_card_does_not_point_at_internal_documents(self): readme = README_PATH.read_text(encoding="utf-8") for relative in INTERNAL_ONLY: self.assertNotIn(Path(relative).name, readme, relative) def test_makefile_tolerates_the_internal_validator_being_absent(self): makefile = MAKEFILE_PATH.read_text(encoding="utf-8") self.assertIn("scripts/build_dataset.py", makefile) self.assertIn( "if [ -f scripts/validate.py ]", makefile, "make validate must degrade gracefully when the internal validator does not ship", ) self.assertIn("LICENSE", makefile, "make hashes must cover LICENSE") def test_make_hashes_covers_every_data_file(self): makefile = MAKEFILE_PATH.read_text(encoding="utf-8") for name in DATA_FILE_NAMES: self.assertIn(name, makefile, f"make hashes must cover {name}") class NoSecretsOrStandInsTest(unittest.TestCase): """Patterns are written self-avoidingly so this file can be scanned by its own rules.""" PATTERNS = [ ("openai-style key", r"sk-[A-Za-z0-9]{16,}"), ("aws access key id", r"AKIA[0-9A-Z]{16}"), ("github token", r"gh[pousr]_[A-Za-z0-9]{20,}"), ("hugging face token", r"hf_[A-Za-z0-9]{20,}"), ("private key block", r"BEGIN [A-Z ]*PRIVATE KEY"), ("bearer credential", r"(?i)bearer\s+[A-Za-z0-9._\-]{16,}"), ( "assigned credential", r"(?i)(api[_-]?key|secret|passwd|password|access[_-]?token)" r"\s*[:=]\s*[\"']?[A-Za-z0-9._\-]{12,}", ), ("unfinished-work marker", r"\bT[O]DO\b"), ("unfinished-work marker", r"\bFIX[M]E\b"), ("unfinished-work marker", r"\bX[X]X\b"), ("unresolved stand-in", r"\bT[B]D\b"), ("unresolved stand-in", r"CHANGE[M]E"), ("unresolved stand-in", r"(?i)\bplace[h]older\b"), ("template slot", r"