Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
matomo sub-agent bugfixes
Tim J. Peters63bbb19a48a3
diff --git a/scripts/matomo_auth.py b/scripts/matomo_auth.pyindex 62b394a..cbef6c6 100644--- a/scripts/matomo_auth.py+++ b/scripts/matomo_auth.py@@ -151,6 +151,11 @@ def _probe_version(url: str, token: str, timeout: int = DEFAULT_TIMEOUT) -> dictif isinstance(payload, str):return {"ok": True, "version": payload}+ if isinstance(payload, dict):+ # Matomo 5+ wraps the version: {"value": "5.13.0"}+ value = payload.get("value")+ if isinstance(value, str):+ return {"ok": True, "version": value}return {"ok": True, "version": json.dumps(payload)[:80]}diff --git a/scripts/matomo_report.py b/scripts/matomo_report.pyindex 88ddfdd..6e2ea9f 100644--- a/scripts/matomo_report.py+++ b/scripts/matomo_report.py@@ -144,11 +144,51 @@ def _bounded_int(value: Any, default: int = 0) -> int:return default-def _bounded_float(value: Any, default: float = 0.0) -> float:- try:- return float(value)- except (TypeError, ValueError):- return default+def _rows(data: Any) -> list:+ """+ Normalize a Matomo DataTable into a list of row dicts.++ Multi-row tables arrive as JSON arrays. Date-indexed summaries (e.g.+ VisitsSummary.get with period=day) arrive as objects keyed by date;+ the key is preserved on each row as ``row_key``. Non-dict values are+ skipped so flat single-object responses yield no rows instead of+ crashing.+ """+ if isinstance(data, list):+ return [r for r in data if isinstance(r, dict)]+ if isinstance(data, dict):+ rows = []+ for key, val in data.items():+ if isinstance(val, dict):+ row = dict(val)+ row.setdefault("row_key", key)+ rows.append(row)+ return rows+ return []+++def _uniq(row: dict) -> int:+ """Unique visitors across either day-period or range-period field names."""+ if "nb_uniq_visitors" in row:+ return _bounded_int(row.get("nb_uniq_visitors"))+ return _bounded_int(row.get("sum_daily_nb_uniq_visitors"))+++def _bounce_rate_pct(bounce_count: Any, visits: int) -> float:+ """Matomo ships bounce counts, not rates; compute the percentage."""+ count = _bounded_int(bounce_count)+ if visits <= 0:+ return 0.0+ return round(count / visits * 100.0, 1)+++def _segment_value(row: dict, name: str) -> str:+ """Extract the value of ``name==value`` from a row's segment string."""+ segment = row.get("segment") or ""+ for part in segment.split(";"):+ if part.startswith(f"{name}=="):+ return part[len(name) + 2:]+ return ""def _resolve_site_id(args: argparse.Namespace) -> Optional[str]:@@ -190,32 +230,29 @@ def organic_traffic_report(site_id: str, url: str, token: str,daily_data = []totals = {"visits": 0, "unique_visitors": 0, "pageviews": 0,"bounce_count": 0, "sum_visit_length": 0, "actions": 0}- if isinstance(raw, dict):- for date_str in sorted(raw.keys()):- row = raw[date_str] or {}- visits = _bounded_int(row.get("nb_visits"))- uniq = _bounded_int(row.get("nb_uniq_visitors"))- actions = _bounded_int(row.get("nb_actions"))- pageviews = _bounded_int(row.get("nb_pageviews"), actions)- bounce_count = _bounded_int(row.get("bounce_count"))- sum_visit_length = _bounded_int(row.get("sum_visit_length"))- bounce_rate = (bounce_count / visits * 100.0) if visits else 0.0- avg_time = (sum_visit_length / visits) if visits else 0.0- daily_data.append({- "date": date_str,- "visits": visits,- "unique_visitors": uniq,- "pageviews": pageviews,- "actions": actions,- "bounce_rate": round(bounce_rate, 1),- "avg_time_on_site": round(avg_time, 1),- })- totals["visits"] += visits- totals["unique_visitors"] += uniq- totals["pageviews"] += pageviews- totals["bounce_count"] += bounce_count- totals["sum_visit_length"] += sum_visit_length- totals["actions"] += actions+ for row in sorted(_rows(raw), key=lambda r: r.get("row_key", "")):+ date_str = row.get("row_key", "")+ visits = _bounded_int(row.get("nb_visits"))+ uniq = _uniq(row)+ actions = _bounded_int(row.get("nb_actions"))+ pageviews = _bounded_int(row.get("nb_pageviews"), actions)+ bounce_count = _bounded_int(row.get("bounce_count"))+ sum_visit_length = _bounded_int(row.get("sum_visit_length"))+ daily_data.append({+ "date": date_str,+ "visits": visits,+ "unique_visitors": uniq,+ "pageviews": pageviews,+ "actions": actions,+ "bounce_rate": _bounce_rate_pct(bounce_count, visits),+ "avg_time_on_site": round(sum_visit_length / visits, 1) if visits else 0.0,+ })+ totals["visits"] += visits+ totals["unique_visitors"] += uniq+ totals["pageviews"] += pageviews+ totals["bounce_count"] += bounce_count+ totals["sum_visit_length"] += sum_visit_length+ totals["actions"] += actionsif totals["visits"]:totals["bounce_rate"] = round(totals["bounce_count"] / totals["visits"] * 100.0, 1)@@ -239,29 +276,21 @@ def organic_traffic_report(site_id: str, url: str, token: str,top_pages = []pages_error: Optional[str] = Noneif pages_resp["status"] == "success":- raw_pages = pages_resp["data"]- if isinstance(raw_pages, list):- for entry in raw_pages:- if not isinstance(entry, dict):- continue- top_pages.append({- "url": entry.get("label", ""),- "visits": _bounded_int(entry.get("nb_visits")),- "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),- "actions": _bounded_int(entry.get("nb_actions")),- "bounce_rate": round(_bounded_float(entry.get("bounce_rate")) * 100, 1),- })- elif isinstance(raw_pages, dict):- for url_key, entry in raw_pages.items():- if not isinstance(entry, dict):- continue- top_pages.append({- "url": entry.get("label") or url_key,- "visits": _bounded_int(entry.get("nb_visits")),- "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),- "actions": _bounded_int(entry.get("nb_actions")),- "bounce_rate": round(_bounded_float(entry.get("bounce_rate")) * 100, 1),- })+ # Real shape (verified against Matomo 5): JSON array of rows with+ # entry_nb_visits / entry_bounce_count / entry_nb_actions and no+ # precomputed bounce_rate. Bounce rate is derived from the counts.+ for row in _rows(pages_resp["data"]):+ entry_visits = _bounded_int(row.get("entry_nb_visits"))+ top_pages.append({+ "url": row.get("label", ""),+ "visits": _bounded_int(row.get("nb_visits")),+ "unique_visitors": _uniq(row),+ "actions": _bounded_int(row.get("entry_nb_actions")),+ "bounce_rate": _bounce_rate_pct(+ row.get("entry_bounce_count"), entry_visits),+ "hits": _bounded_int(row.get("nb_hits")),+ })+ top_pages.sort(key=lambda p: p["visits"], reverse=True)else:pages_error = pages_resp.get("error")@@ -313,17 +342,14 @@ def device_breakdown(site_id: str, url: str, token: str,raw = resp["data"]devices = []- if isinstance(raw, dict):- for device_type, entry in raw.items():- if not isinstance(entry, dict):- continue- visits = _bounded_int(entry.get("nb_visits"))- devices.append({- "device_type": entry.get("label") or device_type,- "visits": visits,- "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),- "bounce_rate": round(_bounded_float(entry.get("bounce_rate")) * 100, 1),- })+ for row in _rows(raw):+ visits = _bounded_int(row.get("nb_visits"))+ devices.append({+ "device_type": row.get("label") or row.get("row_key", ""),+ "visits": visits,+ "unique_visitors": _uniq(row),+ "bounce_rate": _bounce_rate_pct(row.get("bounce_count"), visits),+ })devices.sort(key=lambda d: d["visits"], reverse=True)return _envelope("success", {@@ -354,16 +380,14 @@ def country_breakdown(site_id: str, url: str, token: str,raw = resp["data"]countries = []- if isinstance(raw, dict):- for code, entry in raw.items():- if not isinstance(entry, dict):- continue- countries.append({- "country_code": code,- "country": entry.get("label", code),- "visits": _bounded_int(entry.get("nb_visits")),- "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),- })+ for row in _rows(raw):+ countries.append({+ "country_code": row.get("code") or _segment_value(row, "countryCode") \+ or row.get("row_key", ""),+ "country": row.get("label", ""),+ "visits": _bounded_int(row.get("nb_visits")),+ "unique_visitors": _uniq(row),+ })countries.sort(key=lambda c: c["visits"], reverse=True)return _envelope("success", {@@ -379,12 +403,17 @@ def referrers_report(site_id: str, url: str, token: str,"""Channel breakdown: direct, search, websites, social, campaigns.Plus top search engines for the search channel.++ Method note: ``Referrers.getReferrerType`` (singular "Referrer") is the+ correct Reporting API method in Matomo 4 and 5; ``getReferrersType``+ does not exist. Labels are localized on non-English instances, so the+ machine-readable channel code comes from the row's ``segment`` field."""start, end = _date_range(days)date_arg = f"{start},{end}"types_resp = _request(url, token, {- "method": "Referrers.getReferrersType",+ "method": "Referrers.getReferrerType","idSite": site_id,"period": "range","date": date_arg,@@ -392,18 +421,16 @@ def referrers_report(site_id: str, url: str, token: str,if types_resp["status"] != "success":return types_resp- raw = types_resp["data"]channels = []- if isinstance(raw, dict):- for key, entry in raw.items():- if not isinstance(entry, dict):- continue- channels.append({- "channel": entry.get("label") or key,- "visits": _bounded_int(entry.get("nb_visits")),- "unique_visitors": _bounded_int(entry.get("nb_uniq_visitors")),- "actions": _bounded_int(entry.get("nb_actions")),- })+ for row in _rows(types_resp["data"]):+ channels.append({+ "channel_code": _segment_value(row, "referrerType") \+ or row.get("referrer_type", ""),+ "channel": row.get("label", ""),+ "visits": _bounded_int(row.get("nb_visits")),+ "unique_visitors": _uniq(row),+ "actions": _bounded_int(row.get("nb_actions")),+ })channels.sort(key=lambda c: c["visits"], reverse=True)engines_resp = _request(url, token, {@@ -415,15 +442,11 @@ def referrers_report(site_id: str, url: str, token: str,engines: list = []engines_error: Optional[str] = Noneif engines_resp["status"] == "success":- raw_engines = engines_resp["data"]- if isinstance(raw_engines, dict):- for key, entry in raw_engines.items():- if not isinstance(entry, dict):- continue- engines.append({- "search_engine": entry.get("label") or key,- "visits": _bounded_int(entry.get("nb_visits")),- })+ for row in _rows(engines_resp["data"]):+ engines.append({+ "search_engine": row.get("label", ""),+ "visits": _bounded_int(row.get("nb_visits")),+ })engines.sort(key=lambda e: e["visits"], reverse=True)else:engines_error = engines_resp.get("error")@@ -436,14 +459,37 @@ def referrers_report(site_id: str, url: str, token: str,}, engines_error, method="Referrers.getReferrersType")+# Matomo labels anonymized keywords with localized strings; the row's+# ``segment`` field (``referrerKeyword==`` with empty value) is the+# locale-independent signal and takes precedence.+_ANONYMIZED_LABELS = {+ "",+ "(not provided)",+ "(no keyword)",+ "Keyword not defined",+ "Keyword (not defined)",+ "Keyword nicht definiert",+ "Suchbegriff nicht definiert",+}+++def _is_anonymized_keyword(row: dict, label: str) -> bool:+ if label in _ANONYMIZED_LABELS:+ return True+ segment = row.get("segment") or ""+ return any(part == "referrerKeyword==" for part in segment.split(";"))++def keywords_report(site_id: str, url: str, token: str,days: int = DEFAULT_DAYS,limit: int = 50) -> dict:"""- Organic search keywords. Many entries will be '(not provided)' or- '(no keyword)' due to browser privacy and Matomo's keyword anonymization.- The report surfaces the raw distribution and flags when >50% of entries- are anonymized, which is the norm on modern browsers.+ Organic search keywords. Most traffic surfaces as anonymized+ ("Keyword not defined" / "Suchbegriff nicht definiert" / ...) due to+ browser privacy and Matomo's keyword anonymization rules. The report+ collapses all anonymized variants into one "(not provided)" row and+ flags when >50% of visits are anonymized, which is the norm on+ modern browsers."""start, end = _date_range(days)date_arg = f"{start},{end}"@@ -459,20 +505,16 @@ def keywords_report(site_id: str, url: str, token: str,if resp["status"] != "success":return resp- raw = resp["data"]keywords_by_label: dict[str, dict] = {}anonymized_count = 0- if isinstance(raw, dict):- for kw, entry in raw.items():- if not isinstance(entry, dict):- continue- visits = _bounded_int(entry.get("nb_visits"))- label = entry.get("label") or kw- if label in ("", "(not provided)", "(no keyword)"):- anonymized_count += visits or 0- label = "(not provided)"- bucket = keywords_by_label.setdefault(label, {"keyword": label, "visits": 0})- bucket["visits"] += visits+ for row in _rows(resp["data"]):+ visits = _bounded_int(row.get("nb_visits"))+ label = row.get("label", "")+ if _is_anonymized_keyword(row, label):+ anonymized_count += visits+ label = "(not provided)"+ bucket = keywords_by_label.setdefault(label, {"keyword": label, "visits": 0})+ bucket["visits"] += visitskeywords = list(keywords_by_label.values())keywords.sort(key=lambda k: k["visits"], reverse=True)total_visits = sum(k["visits"] for k in keywords)@@ -493,14 +535,14 @@ def keywords_report(site_id: str, url: str, token: str,}, None, method="Referrers.getKeywords")-def check_command() -> dict:+def check_command(site_id_override: Optional[str] = None) -> dict:"""Lightweight probe: who am I + version, used by --check subcommand."""from matomo_auth import _probe_version, _sanity_check_instance_urlconfig = load_config()url = _sanity_check_instance_url(config.get("matomo_url") or "")token = config.get("matomo_token")- site_id = config.get("matomo_site_id")+ site_id = site_id_override or config.get("matomo_site_id")if not url or not token:return _envelope("error", None,@@ -550,7 +592,7 @@ def main() -> int:args = parser.parse_args()if args.command == "check":- result = check_command()+ result = check_command(site_id_override=args.site_id)else:url = get_matomo_url()token = get_matomo_token()diff --git a/tests/test_matomo_report.py b/tests/test_matomo_report.pyindex feb0e50..efe8e36 100644--- a/tests/test_matomo_report.py+++ b/tests/test_matomo_report.py@@ -149,6 +149,19 @@ def test_check_credentials_probes_version(monkeypatch, tmp_path):assert "token_auth" not in call.kwargs.get("params", {})+def test_check_credentials_handles_matomo5_version_object(monkeypatch, tmp_path):+ """Matomo 5+ returns API.getMatomoVersion as {"value": "5.13.0"}."""+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))+ monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)++ resp = _mock_response(200, {"value": "5.13.0"})+ with patch.object(matomo_auth.requests, "post", return_value=resp):+ status = matomo_auth.check_credentials()+ assert status["available"] is True+ assert status["version"] == "5.13.0"++def test_check_credentials_surfaces_auth_failure(monkeypatch, tmp_path):monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")@@ -243,7 +256,11 @@ def test_cli_errors_when_url_missing(monkeypatch):def test_organic_report_builds_daily_and_pages(monkeypatch):- """organic_traffic_report rolls daily VisitsSummary into totals + pages."""+ """organic_traffic_report rolls daily VisitsSummary into totals + pages.++ Uses the real Matomo 5 shapes: date-keyed object for the daily summary,+ JSON array with entry_* fields for entry pages (no precomputed rate).+ """daily = {"2026-01-01": {"nb_visits": 100, "nb_uniq_visitors": 80,"nb_actions": 150, "nb_pageviews": 200,@@ -253,10 +270,12 @@ def test_organic_report_builds_daily_and_pages(monkeypatch):"bounce_count": 10, "sum_visit_length": 3000},}pages = [- {"label": "https://m.test/", "nb_visits": 80, "nb_uniq_visitors": 70,- "nb_actions": 120, "bounce_rate": 0.3},- {"label": "https://m.test/blog/x", "nb_visits": 40, "nb_uniq_visitors": 30,- "nb_actions": 60, "bounce_rate": 0.5},+ {"label": "en", "nb_visits": 146, "nb_hits": 181,+ "entry_nb_visits": 111, "entry_nb_actions": 583,+ "entry_bounce_count": 23},+ {"label": "blog", "nb_visits": 90, "nb_hits": 120,+ "entry_nb_visits": 60, "entry_nb_actions": 240,+ "entry_bounce_count": 6},]responses = [_mock_response(200, daily),@@ -272,84 +291,153 @@ def test_organic_report_builds_daily_and_pages(monkeypatch):assert data["totals"]["visits"] == 150assert data["totals"]["unique_visitors"] == 120assert len(data["daily_data"]) == 2+ assert data["daily_data"][0]["bounce_rate"] == 30.0assert len(data["top_pages"]) == 2- assert data["top_pages"][0]["url"] == "https://m.test/"---def test_device_breakdown_sorts_by_visits(monkeypatch):- raw = {- "desktop": {"label": "Desktop", "nb_visits": 100,- "nb_uniq_visitors": 80, "bounce_rate": 0.4},- "smartphone": {"label": "Smartphone", "nb_visits": 200,- "nb_uniq_visitors": 170, "bounce_rate": 0.5},- "tablet": {"label": "Tablet", "nb_visits": 20,- "nb_uniq_visitors": 18, "bounce_rate": 0.3},- }+ top = data["top_pages"][0]+ assert top["url"] == "en"+ assert top["visits"] == 146+ assert top["actions"] == 583+ assert top["hits"] == 181+ # 23 bounces / 111 entry visits+ assert top["bounce_rate"] == 20.7+ assert top["bounce_rate"] == round(23 / 111 * 100, 1)+++def test_device_breakdown_handles_matomo5_array(monkeypatch):+ """DevicesDetection.getType returns a JSON array with bounce_count."""+ raw = [+ {"label": "Desktop", "nb_visits": 672, "nb_actions": 6222,+ "bounce_count": 250, "sum_daily_nb_uniq_visitors": 549},+ {"label": "Smartphone", "nb_visits": 214, "nb_actions": 680,+ "bounce_count": 81, "sum_daily_nb_uniq_visitors": 190},+ {"label": "Tablet", "nb_visits": 20, "nb_actions": 60,+ "bounce_count": 3, "sum_daily_nb_uniq_visitors": 18},+ ]with patch.object(matomo_report.requests, "post",return_value=_mock_response(200, raw)):env = matomo_report.device_breakdown("1", "https://m.test",SECRET_TOKEN, days=7)assert env["status"] == "success"devices = env["data"]["devices"]- assert [d["device_type"] for d in devices] == ["Smartphone", "Desktop", "Tablet"]---def test_country_breakdown_caps_limit(monkeypatch):- raw = {f"C{i}": {"label": f"Country {i}", "nb_visits": 100 - i,- "nb_uniq_visitors": 50} for i in range(30)}+ assert [d["device_type"] for d in devices] == ["Desktop", "Smartphone", "Tablet"]+ assert devices[0]["unique_visitors"] == 549+ # 250 / 672 = 37.2%+ assert devices[0]["bounce_rate"] == round(250 / 672 * 100, 1)+++def test_country_breakdown_handles_matomo5_array(monkeypatch):+ """UserCountry.getCountry returns an array with a ``code`` field and+ localized labels; country_code comes from ``code``, not the array index."""+ raw = [+ {"label": "Deutschland", "code": "de", "nb_visits": 434,+ "sum_daily_nb_uniq_visitors": 374},+ {"label": "Vereinigte Staaten", "code": "us", "nb_visits": 79,+ "sum_daily_nb_uniq_visitors": 70},+ ]with patch.object(matomo_report.requests, "post",return_value=_mock_response(200, raw)):env = matomo_report.country_breakdown("1", "https://m.test",SECRET_TOKEN, days=7, limit=5)assert env["status"] == "success"- assert len(env["data"]["countries"]) == 5- assert env["data"]["countries"][0]["country_code"] == "C0"+ countries = env["data"]["countries"]+ assert [c["country_code"] for c in countries] == ["de", "us"]+ assert countries[0]["country"] == "Deutschland"+ assert countries[0]["unique_visitors"] == 374+++def test_referrers_report_uses_matomo5_method_and_shapes(monkeypatch):+ """Referrers.getReferrerType (singular) is the real method name; rows+ arrive as an array with localized labels and machine-readable segment."""+ types = [+ {"label": "Direkte Zugriffe", "nb_visits": 535, "nb_actions": 3991,+ "bounce_count": 280, "sum_daily_nb_uniq_visitors": 426,+ "segment": "referrerType==direct", "referrer_type": "1"},+ {"label": "Suchmaschinen", "nb_visits": 314, "nb_actions": 2443,+ "bounce_count": 51, "sum_daily_nb_uniq_visitors": 290,+ "segment": "referrerType==search", "referrer_type": "2"},+ ]+ engines = [+ {"label": "Google", "nb_visits": 142},+ {"label": "Bing", "nb_visits": 95},+ ]+ with patch.object(matomo_report.requests, "post",+ side_effect=[_mock_response(200, types),+ _mock_response(200, engines)]) as post:+ env = matomo_report.referrers_report("1", "https://m.test",+ SECRET_TOKEN, days=7)+ assert env["status"] == "success"+ # Correct Matomo 4/5 method name (getReferrersType does not exist).+ first_method = post.call_args_list[0].kwargs["data"]["method"]+ assert first_method == "Referrers.getReferrerType"+ channels = env["data"]["channels"]+ assert [c["channel_code"] for c in channels] == ["direct", "search"]+ assert channels[0]["channel"] == "Direkte Zugriffe"+ assert channels[0]["unique_visitors"] == 426+ engines_out = env["data"]["search_engines"]+ assert [e["search_engine"] for e in engines_out] == ["Google", "Bing"]def test_keywords_report_flags_anonymized_share(monkeypatch):- raw = {- "kw1": {"label": "kw1", "nb_visits": 10},- "kw2": {"label": "kw2", "nb_visits": 5},- "(not provided)": {"label": "(not provided)", "nb_visits": 80},- "(no keyword)": {"label": "(no keyword)", "nb_visits": 5},- }+ """Anonymized keywords collapse into one "(not provided)" row.++ Real Matomo 5 shape: JSON array; the localized label+ ("Suchbegriff nicht definiert") and the locale-independent segment+ (``referrerKeyword==``) both mark anonymized rows.+ """+ raw = [+ {"label": "Suchbegriff nicht definiert", "nb_visits": 80,+ "segment": "referrerType==search;referrerKeyword=="},+ {"label": "(no keyword)", "nb_visits": 5,+ "segment": "referrerType==search;referrerKeyword=="},+ {"label": "kw1", "nb_visits": 10,+ "segment": "referrerType==search;referrerKeyword==kw1"},+ {"label": "kw2", "nb_visits": 5,+ "segment": "referrerType==search;referrerKeyword==kw2"},+ ]with patch.object(matomo_report.requests, "post",return_value=_mock_response(200, raw)):env = matomo_report.keywords_report("1", "https://m.test",SECRET_TOKEN, days=7, limit=10)assert env["status"] == "success"data = env["data"]- assert data["anonymized_share_pct"] > 80.0+ assert data["anonymized_share_pct"] == 85.0assert "anonymization" in data["note"].lower()- # Anonymized entries collapse to "(not provided)" but their visits are summed.anonymized = [k for k in data["keywords"] if k["keyword"] == "(not provided)"]- assert anonymized and anonymized[0]["visits"] == 85+ assert len(anonymized) == 1+ assert anonymized[0]["visits"] == 85+ # Real keywords keep their own rows, sorted by visits.+ real = [k for k in data["keywords"] if k["keyword"] != "(not provided)"]+ assert [(k["keyword"], k["visits"]) for k in real] == [("kw1", 10), ("kw2", 5)]+++def test_keywords_report_english_anonymized_label(monkeypatch):+ """English instances label the row "Keyword not defined"."""+ raw = [+ {"label": "Keyword not defined", "nb_visits": 70,+ "segment": "referrerType==search;referrerKeyword=="},+ {"label": "best seo tool", "nb_visits": 30,+ "segment": "referrerType==search;referrerKeyword==best%20seo%20tool"},+ ]+ with patch.object(matomo_report.requests, "post",+ return_value=_mock_response(200, raw)):+ env = matomo_report.keywords_report("1", "https://m.test",+ SECRET_TOKEN, days=7, limit=10)+ data = env["data"]+ assert data["anonymized_share_pct"] == 70.0-def test_referrers_report_includes_search_engines(monkeypatch):- types = {- "direct": {"label": "Direct Entry", "nb_visits": 30, "nb_uniq_visitors": 25,- "nb_actions": 40},- "search": {"label": "Search Engines", "nb_visits": 70, "nb_uniq_visitors": 60,- "nb_actions": 100},- "social": {"label": "Social Networks", "nb_visits": 20, "nb_uniq_visitors": 18,- "nb_actions": 25},- }- engines = {- "Google": {"label": "Google", "nb_visits": 50},- "Bing": {"label": "Bing", "nb_visits": 20},+def test_device_breakdown_supports_legacy_dict_shape(monkeypatch):+ """Dict-keyed responses (older Matomo / single-row objects) still parse."""+ raw = {+ "desktop": {"label": "Desktop", "nb_visits": 100,+ "nb_uniq_visitors": 80, "bounce_rate": 0.4},}with patch.object(matomo_report.requests, "post",- side_effect=[_mock_response(200, types),- _mock_response(200, engines)]):- env = matomo_report.referrers_report("1", "https://m.test",+ return_value=_mock_response(200, raw)):+ env = matomo_report.device_breakdown("1", "https://m.test",SECRET_TOKEN, days=7)assert env["status"] == "success"- channels = env["data"]["channels"]- assert [c["channel"] for c in channels] == [- "Search Engines", "Direct Entry", "Social Networks"]- engines_out = env["data"]["search_engines"]- assert [e["search_engine"] for e in engines_out] == ["Google", "Bing"]+ assert env["data"]["devices"][0]["device_type"] == "Desktop"def test_main_returns_nonzero_on_envelope_error(monkeypatch, capsys):@@ -377,6 +465,21 @@ def test_main_json_emits_envelope(monkeypatch):assert rc == 0+def test_check_command_honors_site_id_override(monkeypatch, tmp_path):+ """`check --site-id N` must surface N even when config has no default."""+ config_file = tmp_path / "matomo.json"+ config_file.write_text(json.dumps({+ "matomo_url": "https://m.test",+ "matomo_token": SECRET_TOKEN,+ }))+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(config_file))+ resp = _mock_response(200, {"value": "5.13.0"})+ with patch.object(matomo_auth.requests, "post", return_value=resp):+ env = matomo_report.check_command(site_id_override="5")+ assert env["status"] == "success"+ assert env["data"]["site_id"] == "5"++def test_main_missing_site_id_exits_one(monkeypatch, capsys):monkeypatch.setenv("MATOMO_URL", "https://m.test")monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)