Files

771 lines
38 KiB
Python
Executable File

#!/usr/bin/env python3
"""Unit tests for the Meta Business live plugin (stdlib only).
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
``/proxy/tools/plugins/meta/*`` endpoints: it enforces the manifest's proxy
allowlist and ``denyParams`` like the real proxy, answers like the Graph API,
and serves the per-user data dir and config. The CLI is imported and run
in-process; the handlers, the snapshot job and the migration script run as
subprocesses, the way the hub runs them.
python3 tests/test_meta_plugin.py # or: python3 -m unittest discover tests
"""
from __future__ import annotations
import contextlib
import datetime as dt
import importlib.machinery
import importlib.util
import io
import json
import os
import pathlib
import re
import stat
import subprocess
import sys
import tempfile
import threading
import unittest
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest import mock
ROOT = pathlib.Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "skill" / "scripts"
sys.dont_write_bytecode = True
sys.path.insert(0, str(SCRIPTS))
import metalib as ml # noqa: E402
MANIFEST = json.loads((ROOT / "plugin.json").read_text())
RUN_TOKEN = "run-token-abcdef"
META_KEY = "EAA" + "x" * 60 # the hub's stored key: must never reach a script
def load_cli():
loader = importlib.machinery.SourceFileLoader("meta_cli", str(SCRIPTS / "meta"))
spec = importlib.util.spec_from_loader("meta_cli", loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
CLI = load_cli()
def today() -> dt.date:
return ml.Clock(ml.DEFAULT_TZ).today()
def end_time(day: dt.date) -> str:
return (day + dt.timedelta(days=1)).isoformat() + "T08:00:00+0000"
def gerr(code: int, message: str, status: int = 400):
return status, {"error": {"message": message, "type": "OAuthException", "code": code,
"fbtrace_id": "abc"}}
# ── the fake Graph API ───────────────────────────────────────────────────────
class FakeGraph:
def __init__(self):
self.scopes = list(ml.SCOPES_ASKED)
self.ads_full_fails = False
self.dead_key = False
self.bad_ig_metric = "website_clicks"
self.page_wants_page_key = False
def __call__(self, path: str, q: dict):
if self.dead_key:
return gerr(190, "Error validating access token: the session has been invalidated")
y = today() - dt.timedelta(days=1)
if path == "me":
return 200, {"id": "9001", "name": "ai-agent"}
if path == "me/permissions":
return 200, {"data": [{"permission": s, "status": "granted"} for s in self.scopes]
+ [{"permission": "email", "status": "declined"}]}
if path == "me/adaccounts":
return 200, {"data": [{"id": "act_111", "account_id": "111", "name": "ACME ads",
"currency": "EUR", "timezone_name": "Europe/Paris",
"account_status": 1}]}
if path == "me/accounts":
if "after" in q:
return 200, {"data": []}
return 200, {"data": [{"id": "222", "name": "Acme Page",
"access_token": "PAGE-KEY-should-never-show",
"instagram_business_account": {
"id": "333", "username": "alice_example",
"followers_count": 150}}],
"paging": {"cursors": {"after": "z"},
"next": "https://graph.facebook.com/v27.0/me/accounts?"
"access_token=PAGE-KEY-should-never-show&after=z"}}
if path == "act_111/insights":
if self.ads_full_fails and "video_avg_time_watched_actions" in q.get("fields", ""):
return gerr(100, "(#100) video_avg_time_watched_actions is not valid")
rng = json.loads(q["time_range"])
day = rng["since"] if "after" not in q else rng["until"]
row = {"date_start": day, "date_stop": day, "campaign_name": "Camp",
"adset_name": "Set", "ad_name": "Ad 1", "ad_id": "5", "age": "18-24",
"gender": "female", "spend": "12.50", "impressions": "1000", "reach": "800",
"inline_link_clicks": "9",
"actions": [{"action_type": "video_view", "value": "300"},
{"action_type": "like", "value": "7"}],
"cost_per_action_type": [{"action_type": "video_view", "value": "0.04"}]}
if "video_thruplay_watched_actions" in q.get("fields", ""):
row["video_thruplay_watched_actions"] = [{"action_type": "video_view",
"value": "40"}]
if "after" not in q:
return 200, {"data": [row], "paging": {"cursors": {"after": "c1"},
"next": "https://x/?after=c1"}}
return 200, {"data": [row], "paging": {"cursors": {"after": "c2"}}}
if path == "333/insights":
metric = q.get("metric", "")
if metric == "follower_count":
return 200, {"data": [{"name": "follower_count", "period": "day", "values": [
{"value": 3, "end_time": end_time(y - dt.timedelta(days=i))}
for i in range(40)]}]}
if metric == "follows_and_unfollows":
return 200, {"data": [{"name": metric, "total_value": {"breakdowns": [
{"dimension_keys": ["follow_type"], "results": [
{"dimension_values": ["FOLLOWER"], "value": 5},
{"dimension_values": ["NON_FOLLOWER"], "value": 2}]}]}}]}
if metric == "follower_demographics":
bd = q.get("breakdown")
if bd == "age,gender":
return gerr(100, "(#100) breakdown not supported together")
return 200, {"data": [{"name": metric, "total_value": {"breakdowns": [
{"results": [{"dimension_values": [f"{bd}-a"], "value": 60},
{"dimension_values": [f"{bd}-b"], "value": 40}]}]}}]}
names = metric.split(",")
if self.bad_ig_metric in names:
return gerr(100, f"(#100) metric[{self.bad_ig_metric}] must be one of …")
return 200, {"data": [{"name": m, "total_value": {"value": 10}} for m in names]}
if path == "222/insights":
if self.page_wants_page_key:
return gerr(190, "(#190) This method must be called with a Page Access Token")
return 200, {"data": [{"name": m, "values": [
{"value": 4, "end_time": end_time(y - dt.timedelta(days=i))} for i in range(100)]}
for m in q.get("metric", "").split(",")]}
if path == "333/media":
recent = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=2)).strftime(
"%Y-%m-%dT%H:%M:%S+0000")
old = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=60)).strftime(
"%Y-%m-%dT%H:%M:%S+0000")
return 200, {"data": [
{"id": "444", "media_product_type": "REELS", "media_type": "VIDEO",
"timestamp": recent, "caption": "New reel\nline 2", "permalink": "https://i/p/1",
"like_count": 12, "comments_count": 3},
{"id": "445", "media_product_type": "FEED", "timestamp": old, "caption": "old"}]}
if path in ("444/insights", "445/insights"):
return 200, {"data": [{"name": m, "values": [{"value": 21}]}
for m in q.get("metric", "").split(",")]}
if path == "333":
return 200, {"id": "333", "username": "alice_example", "followers_count": 150,
"follows_count": 10, "media_count": 42}
if path == "act_111/campaigns":
return 200, {"data": [{"id": "77", "name": "Camp", "status": "ACTIVE"}]}
return gerr(803, f"unknown path {path} in the fake")
# ── the fake hub ─────────────────────────────────────────────────────────────
class FakeHub:
def __init__(self, base: pathlib.Path, default_uid: str = "carol"):
self.base = base
self.default_uid = default_uid
self.graph = FakeGraph()
self.requests: list[dict] = []
self.config = {"timezone": "Europe/Paris"}
allow = [(r["method"], re.compile(r["path"])) for r in MANIFEST["proxy"]["allow"]]
deny = {p.lower() for p in MANIFEST["proxy"]["denyParams"]}
hub = self
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _send(self, status: int, obj=None, raw: bytes | None = None):
body = raw if raw is not None else json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _err(self, status: int, message: str, kind: str = "error"):
self._send(status, {"error": {"message": message, "kind": kind}})
def _route(self, method: str):
u = urllib.parse.urlsplit(self.path)
q = dict(urllib.parse.parse_qsl(u.query))
hub.requests.append({"method": method, "path": u.path, "q": q,
"headers": {k.lower(): v for k, v in self.headers.items()}})
if self.headers.get("Authorization") != f"Bearer {RUN_TOKEN}":
return self._err(401, "unknown or expired tool token", "auth")
prefix = "/plugins/meta/"
if not u.path.startswith(prefix):
return self._err(404, "no such route")
rest = urllib.parse.unquote(u.path[len(prefix):])
uid = (self.headers.get("X-Plugin-As") or "").strip() or hub.default_uid
data_dir = hub.base / uid
data_dir.mkdir(parents=True, exist_ok=True)
if rest.startswith("proxy/"):
gpath = rest[len("proxy/"):]
if not any(m == method and rx.fullmatch(gpath) for m, rx in allow):
return self._err(403, f"plugin proxy refuses {method} /{gpath}")
for k in q:
if k.lower() in deny:
return self._err(403, f"query parameter '{k}' is forbidden by "
"plugin policy")
status, obj = hub.graph(gpath, q)
raw = json.dumps(obj).encode().replace(META_KEY.encode(), b"***")
return self._send(status, raw=raw)
if rest == "config":
return self._send(200, {"config": hub.config, "id": "meta"})
if rest == "data" and method == "GET":
files = [{"path": p.name, "size": p.stat().st_size, "mtime": 0}
for p in sorted(data_dir.iterdir()) if p.is_file()]
return self._send(200, {"files": files})
if rest.startswith("data/"):
rel = rest[len("data/"):]
if ".." in rel.split("/"):
return self._err(400, "invalid data path")
target = data_dir / rel
if method == "GET":
if not target.is_file():
return self._err(404, "file not found")
return self._send(200, raw=target.read_bytes())
if method == "PUT":
n = int(self.headers.get("Content-Length") or 0)
target.write_bytes(self.rfile.read(n))
return self._send(200, {"ok": True})
return self._err(404, "no such route")
def do_GET(self):
self._route("GET")
def do_PUT(self):
self._route("PUT")
def do_POST(self):
self._route("POST")
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
threading.Thread(target=self.server.serve_forever, daemon=True).start()
def close(self):
self.server.shutdown()
self.server.server_close()
def proxied(self) -> list[dict]:
return [r for r in self.requests if "/proxy/" in r["path"]]
class Base(unittest.TestCase):
def setUp(self):
ml._BAD.clear()
self.tmp = tempfile.TemporaryDirectory()
self.base = pathlib.Path(self.tmp.name)
self.hub = FakeHub(self.base / "hubdata")
self.env = mock.patch.dict(os.environ, {"AIA_TOOLS_URL": self.hub.url,
"AIA_TOOLS_TOKEN": RUN_TOKEN})
self.env.start()
os.environ.pop("CLAUDE_CODE_SESSION_ID", None)
def tearDown(self):
self.env.stop()
self.hub.close()
self.tmp.cleanup()
def data(self, uid: str = "carol") -> pathlib.Path:
d = self.base / "hubdata" / uid
d.mkdir(parents=True, exist_ok=True)
return d
def cli(self, *argv) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
code = 0
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
try:
code = CLI.main(list(argv)) or 0
except SystemExit as e:
code = e.code if isinstance(e.code, int) else 1
return code, out.getvalue(), err.getvalue()
def run_script(self, rel: str, payload: dict | None = None, uid: str = "carol"):
env = {"PATH": os.environ.get("PATH", ""), "AIA_TOOLS_URL": self.hub.url,
"AIA_TOOLS_TOKEN": RUN_TOKEN, "AIA_PLUGIN_ID": "meta",
"AIA_PLUGIN_DIR": str(ROOT), "AIA_PLUGIN_DATA_DIR": str(self.data(uid)),
"AIA_PLUGIN_CONFIG": json.dumps({"timezone": "Europe/Paris"}),
"AIA_USER_CONTEXT": json.dumps({"uid": uid, "isOwner": False, "domains": ""})}
p = subprocess.run([sys.executable, str(ROOT / rel)], input=json.dumps(payload or {}),
capture_output=True, text=True, env=env, cwd=str(ROOT), timeout=120)
return p
def connect(self, uid: str = "carol"):
"""A saved connection, as the inspect action leaves it."""
p = self.run_script("handlers/inspect.py", uid=uid)
self.assertEqual(p.returncode, 0, p.stderr)
self.hub.requests.clear()
def assert_no_key_sent(self):
for r in self.hub.requests:
self.assertNotIn("access_token", r["q"])
self.assertEqual(r["headers"].get("authorization"), f"Bearer {RUN_TOKEN}")
# ── the manifest ─────────────────────────────────────────────────────────────
class ManifestTest(unittest.TestCase):
def test_shape(self):
m = MANIFEST
self.assertEqual((m["schema"], m["id"], m["name"]), (1, "meta", "Meta Business"))
self.assertEqual(m["skill"], {"dir": "skill", "name": "meta"})
self.assertEqual([(s["key"], s["scope"]) for s in m["secrets"]], [("token", "user")])
st = m["settings"]
self.assertEqual((st["testAction"], st["statusAction"]), ("inspect", "status"))
self.assertIn("System users", st["instructions"])
self.assertEqual([f["key"] for f in st["fields"]], ["timezone"])
self.assertEqual(m["storage"], {"maxMb": 100})
self.assertEqual([(s["cron"], s["script"]) for s in m["schedules"]],
[("0 7 * * *", "jobs/snapshot.py")])
self.assertEqual({k: v["script"] for k, v in m["actions"].items()},
{"inspect": "handlers/inspect.py", "status": "handlers/status.py"})
for rel in ("handlers/inspect.py", "handlers/status.py", "jobs/snapshot.py",
"skill/SKILL.md", "skill/scripts/hubclient.py", "skill/scripts/metalib.py"):
self.assertTrue((ROOT / rel).is_file(), rel)
self.assertTrue(os.access(SCRIPTS / "meta", os.X_OK))
def test_proxy_read_only(self):
pr = MANIFEST["proxy"]
self.assertEqual(pr["baseUrl"], "https://graph.facebook.com/v27.0")
self.assertEqual(pr["auth"]["secret"], "token")
self.assertEqual({r["method"] for r in pr["allow"]}, {"GET"})
for p in ("access_token", "method", "appsecret_proof", "batch"):
self.assertIn(p, pr["denyParams"])
self.assertEqual(set(pr["inspect"]["requireOnlyScopes"]), set(ml.READ_SCOPES))
self.assertEqual(pr["inspect"]["path"], "me/permissions")
def test_allowlist_matches_legacy_paths(self):
rules = [re.compile(r["path"]) for r in MANIFEST["proxy"]["allow"]]
cases = ["me", "me/adaccounts", "me/accounts", "me/permissions", "act_123",
"act_123/insights", "act_1/adcreatives", "1789", "1789/insights", "1789/media",
"1789/video_reels", "12_34", "12_34/comments",
# refused
"me/feed", "act_x/insights", "act_1/users", "1789/feed", "12_34/likes",
"debug_token", "", "1789/insights/extra", "me/adaccounts/x", "../me"]
for c in cases:
self.assertEqual(any(r.fullmatch(c) for r in rules), ml.path_ok(c), c)
def test_backend_validator_if_available(self):
backend = pathlib.Path.home() / "projects" / "ai-agent" / "backend"
if not (backend / "plugins" / "manifest.py").is_file():
self.skipTest("ai-agent backend not on this machine")
sys.path.insert(0, str(backend)) # manifest.py imports cron.scheduler
spec = importlib.util.spec_from_file_location("aia_manifest",
backend / "plugins" / "manifest.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
out = mod.validate_manifest(ROOT)
self.assertEqual(out["id"], "meta")
self.assertEqual(len(out["proxy"]["allow"]), 4)
# ── the CLI ──────────────────────────────────────────────────────────────────
class AdsTest(Base):
def test_ads_csv(self):
self.connect()
y = today() - dt.timedelta(days=1)
since = y - dt.timedelta(days=6)
dest = self.base / "ads.csv"
code, out, err = self.cli("ads", "--since", since.isoformat(), "--csv", str(dest))
self.assertEqual(code, 0, err)
import csv
with dest.open() as f:
rows = list(csv.DictReader(f))
self.assertEqual([r["date"] for r in rows], [since.isoformat(), y.isoformat()])
r = rows[0]
self.assertEqual((r["account"], r["adset_name"], r["age"], r["gender"]),
("act_111", "Set", "18-24", "female"))
self.assertEqual((r["spend"], r["action:video_view"], r["cost_per:video_view"],
r["video_thruplay_watched_actions"]), ("12.5", "300", "0.04", "40"))
ins = [x for x in self.hub.proxied() if x["path"].endswith("act_111/insights")]
self.assertEqual(len(ins), 2) # followed the cursor
self.assertEqual(ins[1]["q"]["after"], "c1")
self.assertEqual(ins[0]["q"]["breakdowns"], "age,gender")
self.assertEqual(json.loads(ins[0]["q"]["time_range"]),
{"since": since.isoformat(), "until": y.isoformat()})
self.assert_no_key_sent()
def test_ads_fewer_fields_fallback(self):
self.connect()
self.hub.graph.ads_full_fails = True
code, out, err = self.cli("ads")
self.assertEqual(code, 0, err)
self.assertIn("fewer fields", err)
self.assertIn("action:video_view", out.splitlines()[0])
def test_ads_json_and_until_capped_at_yesterday(self):
self.connect()
code, out, err = self.cli("ads", "--until", (today() + dt.timedelta(days=3)).isoformat(),
"--json")
self.assertEqual(code, 0, err)
d = json.loads(out)
self.assertEqual(d["until"], (today() - dt.timedelta(days=1)).isoformat())
def test_too_many_days(self):
self.connect()
code, _, err = self.cli("ads", "--since", (today() - dt.timedelta(days=200)).isoformat())
self.assertEqual(code, 1)
self.assertIn("at most 92 days", err)
class InstagramPageTest(Base):
def test_instagram_csv_with_metric_fallback(self):
self.connect()
code, out, err = self.cli("instagram")
self.assertEqual(code, 0, err)
lines = out.strip().splitlines()
self.assertEqual(len(lines), 8) # header + 7 days
head = lines[0].split(",")
for col in ("date", "account", "follower_count", "reach", "follows", "unfollows",
"profile_views"):
self.assertIn(col, head)
self.assertNotIn("website_clicks", head)
self.assertIn("note: instagram website_clicks", err)
# the refused metric is asked once alone, then skipped
alone = [r for r in self.hub.proxied() if r["q"].get("metric") == "website_clicks"]
self.assertEqual(len(alone), 1)
row = dict(zip(head, lines[1].split(",")))
self.assertEqual((row["account"], row["follows"], row["unfollows"], row["reach"]),
("333", "5", "2", "10"))
def test_page_csv(self):
self.connect()
dest = self.base / "page.csv"
code, _, err = self.cli("page", "--csv", str(dest))
self.assertEqual(code, 0, err)
lines = dest.read_text().strip().splitlines()
self.assertTrue(lines[0].startswith("date,page,page_follows"))
self.assertEqual(len(lines), 8)
self.assertIn(",222,4,", lines[1])
class MediaAudienceTest(Base):
def test_media_csv(self):
self.connect()
dest = self.base / "reels.csv"
code, _, err = self.cli("media", "--csv", str(dest))
self.assertEqual(code, 0, err)
import csv
with dest.open() as f:
rows = list(csv.DictReader(f))
self.assertEqual([r["id"] for r in rows], ["444"]) # the 60-day-old one is out
r = rows[0]
self.assertEqual((r["type"], r["caption"], r["reach"], r["ig_reels_avg_watch_time"]),
("REELS", "New reel line 2", "21", "21"))
def test_audience_splits_age_gender(self):
self.connect()
code, out, err = self.cli("audience")
self.assertEqual(code, 0, err)
d = json.loads(out)["instagram"]["333"]
self.assertEqual(set(d), {"profile", "age", "gender", "country", "city"})
self.assertEqual(d["profile"]["followers_count"], 150)
self.assertEqual(d["country"][0], {"key": ["country-a"], "value": 60})
class HistoryTest(Base):
def seed(self, uid: str = "carol", n: int = 5):
y = today() - dt.timedelta(days=1)
names = []
for i in range(n):
day = (y - dt.timedelta(days=i)).isoformat()
names.append(day)
(self.data(uid) / f"{day}.json").write_text(json.dumps({
"date": day, "takenAt": "2026-11-25T06:00:00Z",
"ads": {"act_111": [{"ad_name": "Ad", "spend": "3", "age": "25-34",
"gender": "male", "actions": [
{"action_type": "like", "value": "2"}]}]},
"instagram": {"333": {"follower_count": i, "reach": 100 + i}},
"media": {"333": []}}))
(self.data(uid) / "connection.json").write_text("{}")
return sorted(names)
def test_history_parts_and_range(self):
names = self.seed()
code, out, err = self.cli("history", "--since", names[1], "--until", names[3],
"--parts", "instagram")
self.assertEqual(code, 0, err)
d = json.loads(out)
self.assertEqual(sorted(d["days"]), names[1:4])
self.assertEqual(set(d["days"][names[1]]), {"date", "takenAt", "instagram"})
self.assertEqual(d["stored"], {"days": 5, "first": names[0], "last": names[-1]})
self.assertEqual(self.hub.proxied(), []) # nothing asked of Meta
def test_ads_history_csv_and_out(self):
names = self.seed()
code, out, err = self.cli("ads", "--history", "--since", names[0])
self.assertEqual(code, 0, err)
lines = out.strip().splitlines()
self.assertEqual(len(lines), 6)
self.assertIn("action:like", lines[0])
outdir = self.base / "out"
code, _, err = self.cli("history", "--since", names[0], "--out", str(outdir))
self.assertEqual(code, 0, err)
self.assertEqual(sorted(p.stem for p in outdir.iterdir()), names)
def test_as_reads_a_guests_data(self):
names = self.seed(uid="bob", n=2)
code, out, err = self.cli("--as", "bob", "history", "--since", names[0])
self.assertEqual(code, 0, err)
self.assertEqual(sorted(json.loads(out)["days"]), names)
self.assertTrue(all(r["headers"].get("x-plugin-as") == "bob" for r in self.hub.requests))
class GetStatusTest(Base):
def test_get_scrubs_page_keys(self):
self.connect()
code, out, err = self.cli("get", "me/accounts", "-p", "fields=id,name")
self.assertEqual(code, 0, err)
self.assertNotIn("PAGE-KEY", out)
d = json.loads(out)
self.assertNotIn("access_token", d["data"][0])
self.assertEqual(d["paging"]["more"], True)
self.assertNotIn("next", d["paging"])
def test_get_campaigns(self):
self.connect()
code, out, err = self.cli("get", "act_111/campaigns", "-p", "fields=name,status")
self.assertEqual(code, 0, err)
self.assertEqual(json.loads(out)["data"][0]["name"], "Camp")
self.assertEqual(self.hub.proxied()[0]["q"], {"fields": "name,status"})
def test_get_refusals(self):
self.connect()
for argv, want in ((("get", "me/feed"), "isn't a path"),
(("get", "act_999/campaigns"), "isn't this connection's ad account"),
(("get", "me", "-p", "access_token=x"), "isn't allowed"),
(("get", "me", "-p", "method=post"), "isn't allowed"),
(("get", "me", "-p", "nokv"), "KEY=VALUE")):
code, _, err = self.cli(*argv)
self.assertNotEqual(code, 0, argv)
self.assertIn(want, err, argv)
self.assertEqual(self.hub.proxied(), [])
def test_hub_refuses_denied_param_too(self):
h = ml.Hub()
with self.assertRaises(ml.MetaError) as cm:
h.graph("me", {"batch": "[]"})
self.assertEqual(cm.exception.kind, "hub")
self.assertIn("forbidden", cm.exception.message)
def test_status_first_run_checks_and_saves(self):
code, out, err = self.cli("status")
self.assertEqual(code, 0, err)
self.assertIn("ad account act_111 ACME ads", out)
self.assertIn("instagram 333 @alice_example", out)
self.assertIn("saved days: 0", out)
saved = json.loads((self.data() / "connection.json").read_text())
self.assertEqual(saved["user"]["name"], "ai-agent")
self.assertNotIn("PAGE-KEY", json.dumps(saved))
self.hub.requests.clear()
code, out, _ = self.cli("status", "--json") # second time: offline
self.assertEqual(json.loads(out)["connected"], True)
self.assertEqual(self.hub.proxied(), [])
def test_dead_key_message(self):
self.connect()
self.hub.graph.dead_key = True
code, _, err = self.cli("ads")
self.assertEqual(code, 1)
self.assertIn("no longer works", err)
# ── handlers and the job ─────────────────────────────────────────────────────
class HandlersTest(Base):
def test_inspect_ok(self):
p = self.run_script("handlers/inspect.py")
self.assertEqual(p.returncode, 0, p.stderr)
d = json.loads(p.stdout)
self.assertTrue(d["ok"])
self.assertIn("ACME ads", d["message"])
self.assertEqual(d["sees"], {"ads": True, "instagram": True, "page": True})
saved = (self.data() / "connection.json").read_text()
self.assertNotIn("PAGE-KEY", saved)
self.assertNotIn(META_KEY, saved)
self.assertEqual(json.loads(saved)["instagram"][0]["username"], "alice_example")
def test_inspect_refuses_write_scopes(self):
self.connect()
self.hub.graph.scopes = list(ml.SCOPES_ASKED) + ["ads_management"]
p = self.run_script("handlers/inspect.py")
self.assertEqual(p.returncode, 1)
self.assertIn("can do more than read (ads_management)", p.stderr)
saved = json.loads((self.data() / "connection.json").read_text())
self.assertEqual(saved["error"]["kind"], "scopes")
def test_inspect_missing_scopes_still_connects(self):
self.hub.graph.scopes = ["ads_read"]
p = self.run_script("handlers/inspect.py")
self.assertEqual(p.returncode, 0, p.stderr)
d = json.loads(p.stdout)
self.assertEqual(d["sees"], {"ads": True, "instagram": False, "page": False})
self.assertIn("instagram_basic", d["missing"])
def test_status(self):
p = self.run_script("handlers/status.py")
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(json.loads(p.stdout)["connected"], False)
self.connect()
(self.data() / "2026-11-01.json").write_text("{}")
p = self.run_script("handlers/status.py")
d = json.loads(p.stdout)
self.assertTrue(d["ok"])
self.assertEqual(d["stored"]["days"], 1)
self.assertIn("1 ad account(s), 1 Instagram, 1 Page(s) · 1 saved day(s)", d["message"])
self.assertEqual(self.hub.proxied(), [])
class SnapshotTest(Base):
def test_backfill_then_refresh(self):
p = self.run_script("jobs/snapshot.py", {"trigger": "schedule"})
self.assertEqual(p.returncode, 0, p.stderr)
d = json.loads(p.stdout)
y = (today() - dt.timedelta(days=1)).isoformat()
self.assertEqual((d["ok"], d["backfill"], d["day"], d["days"]), (True, True, y, 28))
files = sorted(x.name for x in self.data().iterdir() if ml.DAY_FILE_RE.match(x.name))
self.assertEqual(len(files), 28)
last = json.loads((self.data() / f"{y}.json").read_text())
self.assertEqual(set(last) >= {"ads", "instagram", "page", "media", "audience", "date",
"takenAt"}, True)
self.assertEqual(last["media"]["333"][0]["id"], "444")
older = json.loads((self.data() / files[0]).read_text())
self.assertNotIn("media", older)
self.assertTrue(json.loads((self.data() / "snapshot.json").read_text())["ok"])
for f in self.data().iterdir():
self.assertNotIn("PAGE-KEY", f.read_text())
# the next morning-style run: a week only, the morning parts kept
self.hub.requests.clear()
p = self.run_script("jobs/snapshot.py", {"trigger": "schedule"})
d = json.loads(p.stdout)
self.assertEqual((d["ok"], d["backfill"], d["days"]), (True, False, 28))
ads = [r for r in self.hub.proxied() if r["path"].endswith("act_111/insights")]
since = json.loads(ads[0]["q"]["time_range"])["since"]
self.assertEqual(since, (today() - dt.timedelta(days=7)).isoformat())
def test_a_page_wanting_its_own_key_skips_the_page_only(self):
# A system-user key reads ads and Instagram, but Page insights want the
# Page's key, which the hub strips: Meta's #190 there is no dead key.
self.connect()
self.hub.graph.page_wants_page_key = True
p = self.run_script("jobs/snapshot.py")
self.assertEqual(p.returncode, 0, p.stderr)
snap = json.loads((self.data() / "snapshot.json").read_text())
self.assertTrue(snap["ok"])
self.assertIn("meta-page-key", [ml.graph_error({"code": 190, "message":
"(#190) This method must be called with a Page Access Token"}).kind])
self.assertTrue(any(e.get("part") == "page" and "Page key" in e["message"]
for e in snap["errors"]))
conn = json.loads((self.data() / "connection.json").read_text())
self.assertIsNone(conn.get("error"))
day = json.loads((self.data() / sorted(f.name for f in self.data().iterdir()
if re.match(r"\d{4}-", f.name))[-1]).read_text())
self.assertTrue(day.get("ads") and day.get("instagram"))
def test_dead_key_fails_and_records(self):
self.connect()
self.hub.graph.dead_key = True
p = self.run_script("jobs/snapshot.py")
self.assertEqual(p.returncode, 1)
self.assertIn("no longer works", p.stderr)
snap = json.loads((self.data() / "snapshot.json").read_text())
self.assertEqual((snap["ok"], snap["kind"]), (False, "meta-token"))
conn = json.loads((self.data() / "connection.json").read_text())
self.assertEqual(conn["error"]["kind"], "meta-token")
# ── the one-shot migration ───────────────────────────────────────────────────
class MigrateTest(unittest.TestCase):
TOKEN = "EAAlegacy" + "k" * 80
PAGE_TOKEN = "EAApage" + "p" * 80
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.d = pathlib.Path(self.tmp.name)
(self.d / "tools-meta.json").write_text(json.dumps({
"carol": {"token": self.TOKEN, "pageTokens": {"222": self.PAGE_TOKEN},
"user": {"id": "9", "name": "ai-agent"}, "scopes": list(ml.SCOPES_ASKED),
"adAccounts": [{"id": "act_111", "name": "ACME"}], "pages": [],
"instagram": [], "connectedAt": "2026-10-28T10:00:00Z",
"checkedAt": "2026-11-20T10:00:00Z", "error": None,
"snapshot": {"at": "2026-11-25T06:00:00Z", "ok": True, "day": "2026-11-24"}},
"nokey": {"user": {"id": "1"}},
}))
os.chmod(self.d / "tools-meta.json", 0o600)
snaps = self.d / "meta-snapshots" / "carol"
snaps.mkdir(parents=True)
for day in ("2026-10-28", "2026-10-29", "2026-10-30"):
(snaps / f"{day}.json").write_text(json.dumps({"date": day, "ads": {}}))
(snaps / "notes.txt").write_text("not a day")
def tearDown(self):
self.tmp.cleanup()
def run_it(self, *args):
p = subprocess.run([sys.executable, str(ROOT / "scripts" / "migrate_legacy.py"),
"--data-dir", str(self.d), *args],
capture_output=True, text=True, timeout=60)
for s in (self.TOKEN, self.PAGE_TOKEN):
self.assertNotIn(s, p.stdout + p.stderr)
return p
def test_migrate_idempotent(self):
before = (self.d / "tools-meta.json").read_bytes()
p = self.run_it("--dry-run")
self.assertEqual(p.returncode, 0, p.stderr)
self.assertIn("secret=would copy", p.stdout)
self.assertFalse((self.d / "plugins").exists())
p = self.run_it()
self.assertEqual(p.returncode, 0, p.stderr)
self.assertIn("carol: secret=copied, connection=written, days_copied=3, days_kept=0", p.stdout)
sec = self.d / "plugins" / "secrets" / "carol" / "meta.json"
self.assertEqual(json.loads(sec.read_text()), {"token": self.TOKEN})
self.assertEqual(stat.S_IMODE(sec.stat().st_mode), 0o600)
self.assertEqual(stat.S_IMODE(sec.parent.stat().st_mode), 0o700)
dest = self.d / "plugins" / "data" / "carol" / "meta"
self.assertEqual(sorted(x.name for x in dest.iterdir()),
["2026-10-28.json", "2026-10-29.json", "2026-10-30.json",
"connection.json", "snapshot.json"])
conn = (dest / "connection.json").read_text()
self.assertNotIn(self.TOKEN, conn)
self.assertNotIn(self.PAGE_TOKEN, conn)
self.assertNotIn("pageTokens", conn)
self.assertEqual(json.loads(conn)["adAccounts"][0]["id"], "act_111")
self.assertFalse((self.d / "plugins" / "secrets" / "nokey").exists())
# the status action reads what it left
st = ml.status(ml.DirStore(dest))
self.assertEqual((st["connected"], st["stored"]["days"]), (True, 3))
p = self.run_it()
self.assertIn("carol: secret=already there, connection=already there, days_copied=0, "
"days_kept=3", p.stdout)
self.assertEqual((self.d / "tools-meta.json").read_bytes(), before)
def test_keeps_a_newer_key_and_other_secrets(self):
sec = self.d / "plugins" / "secrets" / "carol" / "meta.json"
sec.parent.mkdir(parents=True)
sec.write_text(json.dumps({"token": "EAAnewer" + "n" * 60, "other": "x"}))
p = self.run_it("--uid", "carol")
self.assertIn("secret=kept the newer key already there", p.stdout)
self.assertEqual(json.loads(sec.read_text())["token"], "EAAnewer" + "n" * 60)
p = self.run_it("--uid", "carol", "--overwrite-secret")
self.assertIn("secret=copied", p.stdout)
self.assertEqual(json.loads(sec.read_text()), {"token": self.TOKEN, "other": "x"})
self.assertEqual(stat.S_IMODE(sec.stat().st_mode), 0o600)
if __name__ == "__main__":
unittest.main(verbosity=2)