Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/CheckAdExposureReports.py

Source at documentation-generation time. See Test catalog for fixture associations.

1"""Reconcile cumulative policy-5 creative summaries with placement snapshots.
2
3Run after AdViewability11Tests, or pass a directory of completed diagnostic logs.
4This does not sum repeated checkpoints into exposure or infer missing data.
5"""
6import argparse
7import csv
8import math
9from collections import defaultdict
10from pathlib import Path
11
12
13METRICS = (
14 "measured_seconds", "visible_seconds", "screen_percentage_seconds",
15 "above_1_5_screen_percentage_seconds", "readable_screen_percentage_seconds",
16 "angle_screen_percentage_seconds", "eligible_screen_percentage_seconds",
17 "qualified_screen_percentage_seconds",
18)
19
20
21def check(path):
22 with path.open(newline="", encoding="utf-8") as stream:
23 reader = csv.DictReader(stream)
24 if "screen_percentage_seconds" not in (reader.fieldnames or []):
25 return None # Older diagnostic policy.
26 rows = list(reader)
27 summary_path = path.with_name(path.stem + "-summary.csv")
28 with summary_path.open(newline="", encoding="utf-8") as stream:
29 summaries = list(csv.DictReader(stream))
30 assert summaries, "missing summary checkpoint"
31 groups = defaultdict(list)
32 for row in rows:
33 assert None not in row and None not in row.values(), "incomplete placement row"
34 groups[(row["snapshot_sequence"], row["kind"], row["creative"], row["creative_hash"])].append(row)
35 assert row["session_id"] and row["session_start_utc"].endswith("Z") and row["snapshot_utc"].endswith("Z"), "missing run dates"
36 assert bool(row["session_end_utc"]) == (row["final_snapshot"] == "1"), "incorrect final checkpoint date"
37 for name in METRICS:
38 assert math.isfinite(float(row[name])) and float(row[name]) >= 0, "invalid metric: " + name
39 raw = float(row["screen_percentage_seconds"])
40 high = float(row["above_1_5_screen_percentage_seconds"])
41 qualified = float(row["qualified_screen_percentage_seconds"])
42 assert qualified <= high + 1e-8 and high <= raw + 1e-8, "incorrect nested exposure totals"
43 for summary in summaries:
44 assert None not in summary and None not in summary.values(), "incomplete summary row"
45 key = (summary["snapshot_sequence"], summary["kind"], summary["creative"], summary["creative_hash"])
46 placements = groups.get(key, [])
47 assert int(summary["observed_placements"]) == len(placements), "incorrect observed placement count"
48 assert int(summary["visible_placements"]) == sum(bool(row["first_visible_utc"]) for row in placements), "incorrect visible placement count"
49 assert int(summary["qualified_placements"]) == sum(row["qualified_once"] == "1" for row in placements), "incorrect qualified placement count"
50 for name in METRICS:
51 expected = sum(float(row[name]) for row in placements)
52 assert math.isclose(float(summary[name]), expected, rel_tol=1e-9, abs_tol=1e-8), "summary mismatch: " + name
53 for row in placements:
54 for name in ("session_id", "session_start_utc", "snapshot_utc", "session_end_utc", "final_snapshot"):
55 assert row[name] == summary[name], "checkpoint identity mismatch: " + name
56 seen = [row for row in placements if row["first_visible_utc"]]
57 assert summary["first_visible_utc"] == (min(row["first_visible_utc"] for row in seen) if seen else ""), "incorrect first exposure date"
58 assert summary["last_visible_utc"] == (max(row["last_visible_utc"] for row in seen) if seen else ""), "incorrect last exposure date"
59 return len(summaries)
60
61
62def main():
63 parser = argparse.ArgumentParser(description=__doc__)
64 parser.add_argument("directory", nargs="?", type=Path, default=Path(__file__).resolve().parent.parent / "outputs")
65 args = parser.parse_args()
66 files = checkpoints = 0
67 for path in sorted(args.directory.glob("ad-viewability-*.csv")):
68 if path.stem.endswith("-summary"):
69 continue
70 try:
71 count = check(path)
72 except (AssertionError, KeyError, ValueError, OSError) as error:
73 raise SystemExit(f"FAIL {path.name}: {error}") from error
74 if count is not None:
75 files += 1
76 checkpoints += count
77 if not files:
78 raise SystemExit("FAIL: no policy-5 exposure logs found; run AdViewability11Tests first")
79 print(f"{files} paired policy-5 logs validated; {checkpoints} creative snapshots reconcile with placement totals and counts")
80
81
82if __name__ == "__main__":
83 main()
SCRIPT_CONTROL SCRIPT_STATE const void int