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.
fix(google): close the gaps left by #387, #393 and #386; add nlp --language
Agrici Daniel2d849c241d3d
diff --git a/scripts/dataforseo_merchant.py b/scripts/dataforseo_merchant.pyindex f4e0ca9..43aaeef 100755--- a/scripts/dataforseo_merchant.py+++ b/scripts/dataforseo_merchant.py@@ -159,8 +159,13 @@ def _poll_results(task_status = tasks[0].get("status_code") if tasks else Noneif task_status and task_status not in (40601, 40602):# 40601 = "Task Handed", 40602 = "Task In Queue" -- keep polling- # Other errors: return the error- return data+ # Any other code is terminal. Return it as an error so callers+ # do not read a failed task (result: null) as zero results.+ return {+ "error": "task_error",+ "status_code": task_status,+ "message": tasks[0].get("status_message") or "Task failed",+ }delay = min(delay * POLL_MULTIPLIER, POLL_MAX_DELAY)diff --git a/scripts/ga4_report.py b/scripts/ga4_report.pyindex 383b1aa..63bfdec 100644--- a/scripts/ga4_report.py+++ b/scripts/ga4_report.py@@ -402,7 +402,7 @@ def main():property_group = parser.add_mutually_exclusive_group()property_group.add_argument("--property", "-p",- help="GA4 property ID (numeric, e.g., 123456789). Uses config default if not specified.",+ help="GA4 property ID (numeric, e.g., 123456789). Without --property or --domain the config default is used, unless a sites mapping is configured.",)property_group.add_argument("--domain",@@ -420,21 +420,40 @@ def main():args = parser.parse_args()- # Resolve property+ # Resolve property. An empty flag value (an unset shell variable, say) must+ # not fall through to the global default and report another site's data.+ for flag, value in (("--property", args.property), ("--domain", args.domain)):+ if value is not None and not value.strip():+ print(f"Error: {flag} was given an empty value.", file=sys.stderr)+ sys.exit(1)prop = args.property- if not prop:+ if prop is None:config = load_config()- if args.domain:+ if args.domain is not None:try:prop = resolve_site_property(config, "ga4", args.domain)except ValueError as error:print(f"Error: {error}", file=sys.stderr)sys.exit(1)+ elif config.get("sites"):+ print(+ "Error: A sites mapping is configured, so the default GA4 property is "+ "not assumed. Pass --domain <audited-domain> or --property <id>.",+ file=sys.stderr,+ )+ sys.exit(1)else:prop = config.get("ga4_property_id") or ""# Strip 'properties/' prefix if present for consistencyif prop and prop.startswith("properties/"):prop = prop[len("properties/"):]+ if prop and args.domain is None:+ print(+ f"Note: no --domain or --property given; using the default GA4 "+ f"property {prop} from config. Pass --domain <audited-domain> to "+ "bind the report to the audited site.",+ file=sys.stderr,+ )if not prop:print("Error: No GA4 property specified. Use --property or set ga4_property_id in config.",diff --git a/scripts/google_properties.py b/scripts/google_properties.pyindex b2dda90..203ca4d 100644--- a/scripts/google_properties.py+++ b/scripts/google_properties.py@@ -20,12 +20,69 @@ def _property_domain(value: str) -> str:return normalize_site_domain(value)+def _without_www(host: str) -> str:+ return host[len("www."):] if host.startswith("www.") else host+++def _covered_domain(values: object) -> str | None:+ """Return D when a sites entry's ``gsc_property`` is ``sc-domain:D``."""+ prop = values.get("gsc_property") if isinstance(values, dict) else None+ if not isinstance(prop, str) or not prop.startswith("sc-domain:"):+ return None+ try:+ return _property_domain(prop)+ except ValueError:+ return None+++def _match_site_entry(sites: dict, host: str) -> list:+ """Return the one sites entry for ``host`` in a list, or an empty list.++ Order: exact host, then the same host with or without ``www.``, then an+ entry whose domain property covers ``host`` as a subdomain. Cover is a+ dot-suffix match, so ``notexample.com`` never matches ``example.com``.+ The most specific covering domain wins, and among entries sharing it the+ one keyed by that domain.+ """+ entries = [(normalize_site_domain(key), values) for key, values in sites.items()]+ matches = [values for key, values in entries if key == host]+ if not matches:+ matches = [+ values for key, values in entries if _without_www(key) == _without_www(host)+ ]+ if len(matches) > 1:+ raise ValueError(f"Multiple sites entries normalize to {host!r}")+ if matches:+ return matches++ covering = [+ (covered, key, values)+ for covered, key, values in (+ (_covered_domain(values), key, values) for key, values in entries+ )+ if covered and host.endswith("." + covered)+ ]+ if not covering:+ return []+ domain = max((covered for covered, _, _ in covering), key=len)+ best = [(key, values) for covered, key, values in covering if covered == domain]+ if len(best) > 1:+ best = [(key, values) for key, values in best if _without_www(key) == domain]+ if len(best) != 1:+ raise ValueError(+ f"Multiple sites entries cover {host!r}; add an entry for that exact host"+ )+ return [best[0][1]]++def resolve_site_property(config: dict, service: str, domain: str) -> str:- """Resolve an exact site's GSC or GA4 property without crossing sites.+ """Resolve a site's GSC or GA4 property without crossing sites.``sites`` maps hostnames to ``gsc_property`` and/or- ``ga4_property_id``. The legacy single-site fields are used only when the- requested domain matches the domain of ``default_property``.+ ``ga4_property_id``. A key matches its own host with or without a leading+ ``www.``, and an entry whose ``gsc_property`` is ``sc-domain:D`` also+ covers subdomains of D. The legacy single-site fields are used only when+ the requested domain matches the domain of ``default_property``."""fields = {"gsc": "gsc_property", "ga4": "ga4_property_id"}if service not in fields:@@ -35,12 +92,7 @@ def resolve_site_property(config: dict, service: str, domain: str) -> str:if not isinstance(sites, dict):raise ValueError("sites must be an object keyed by site domain")- matches = []- for configured_domain, values in sites.items():- if normalize_site_domain(configured_domain) == host:- matches.append(values)- if len(matches) > 1:- raise ValueError(f"Multiple sites entries normalize to {host!r}")+ matches = _match_site_entry(sites, host)if matches:values = matches[0]if not isinstance(values, dict) or not values.get(fields[service]):@@ -53,7 +105,7 @@ def resolve_site_property(config: dict, service: str, domain: str) -> str:default_text = str(default_property)default_host = _property_domain(default_text)is_domain_property = default_text.startswith("sc-domain:")- matches_default = host == default_host or (+ matches_default = _without_www(host) == _without_www(default_host) or (is_domain_property and host.endswith("." + default_host))if matches_default:diff --git a/scripts/google_report.py b/scripts/google_report.pyindex 361c7fd..73b303a 100644--- a/scripts/google_report.py+++ b/scripts/google_report.py@@ -1512,7 +1512,10 @@ def _build_cwv_section(psi_data, crux_data, chart_paths, history_data=None, sectelse ("status-fail" if direction == "degrading" else ""))lines.append(f' <tr><td>{t.get("label", name)}</td>'f'<td class="{cls}">{direction.upper()}</td>')- lines.append(f' <td>{t.get("change_pct", 0):+.1f}%</td>'+ # crux_history returns None for an increase from a zero baseline.+ change = t.get("change_pct", 0)+ change_text = f"{change:+.1f}%" if change is not None else "n/a"+ lines.append(f' <td>{change_text}</td>'f'<td>{t.get("earliest_avg", "?")}</td>'f'<td>{t.get("latest_avg", "?")}</td></tr>')lines.append(' </tbody>')diff --git a/scripts/gsc_inspect.py b/scripts/gsc_inspect.pyindex 82152a6..1d80a75 100644--- a/scripts/gsc_inspect.py+++ b/scripts/gsc_inspect.py@@ -271,12 +271,17 @@ def main():args = parser.parse_args()# Resolve the property against the requested site's domain when possible.+ # An empty flag value (an unset shell variable, say) is an error, not "unset".+ for flag, value in (("--site-url", args.site_url), ("--domain", args.domain)):+ if value is not None and not value.strip():+ print(f"Error: {flag} was given an empty value.", file=sys.stderr)+ sys.exit(1)site_url = args.site_url- if args.batch and not args.site_url and not args.domain:+ if args.batch and args.site_url is None and args.domain is None:parser.error("--batch requires --site-url or --domain to identify the site's property")- if not site_url:+ if site_url is None:config = load_config()- domain = args.domain or args.url+ domain = args.domain if args.domain is not None else args.urlif domain:try:site_url = resolve_site_property(config, "gsc", domain)diff --git a/scripts/gsc_query.py b/scripts/gsc_query.pyindex 13fc771..475c112 100644--- a/scripts/gsc_query.py+++ b/scripts/gsc_query.py@@ -441,7 +441,7 @@ def main():property_group = parser.add_mutually_exclusive_group()property_group.add_argument("--property", "-p",- help="Explicit GSC property (e.g., sc-domain:example.com). Uses config default if not specified.",+ help="Explicit GSC property (e.g., sc-domain:example.com). Without --property or --domain the config default is used, unless a sites mapping is configured.",)property_group.add_argument("--domain",@@ -467,18 +467,37 @@ def main():args = parser.parse_args()- # Resolve property+ # Resolve property. An empty flag value (an unset shell variable, say) must+ # not fall through to the global default and report another site's data.+ for flag, value in (("--property", args.property), ("--domain", args.domain)):+ if value is not None and not value.strip():+ print(f"Error: {flag} was given an empty value.", file=sys.stderr)+ sys.exit(1)prop = args.property- if not prop:+ if prop is None and args.command != "sites":config = load_config()- if args.domain and args.command != "sites":+ if args.domain is not None:try:prop = resolve_site_property(config, "gsc", args.domain)except ValueError as error:print(f"Error: {error}", file=sys.stderr)sys.exit(1)- elif not args.domain:+ elif config.get("sites"):+ print(+ "Error: A sites mapping is configured, so the default property is "+ "not assumed. Pass --domain <audited-domain> or --property <property>.",+ file=sys.stderr,+ )+ sys.exit(1)+ else:prop = config.get("default_property")+ if prop:+ print(+ f"Note: no --domain or --property given; using the default GSC "+ f"property {prop} from config. Pass --domain <audited-domain> to "+ "bind the query to the audited site.",+ file=sys.stderr,+ )if not prop and args.command != "sites":print("Error: No property specified. Use --property or set default_property in config.", file=sys.stderr)sys.exit(1)diff --git a/scripts/nlp_analyze.py b/scripts/nlp_analyze.pyindex c3a1b40..a6f9214 100644--- a/scripts/nlp_analyze.py+++ b/scripts/nlp_analyze.py@@ -10,10 +10,12 @@ Usage:python nlp_analyze.py --text "Your content here" --jsonpython nlp_analyze.py --url https://example.com --jsonpython nlp_analyze.py --text "Your content" --features entities,sentiment,classify+ python nlp_analyze.py --url https://example.com.br --language pt-BR --json"""import argparseimport json+import reimport sysfrom typing import Optional@@ -55,12 +57,25 @@ FEATURES = {"moderate": "moderateText",}+# Loose BCP-47 shape (en, pt-BR, zh-Hant); the API decides what it supports.+LANGUAGE_CODE = re.compile(r"[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*")+++def language_code(value: str) -> str:+ """argparse type for --language: reject anything that is not a language tag."""+ code = value.strip()+ if not LANGUAGE_CODE.fullmatch(code):+ raise argparse.ArgumentTypeError(+ f"{value!r} is not a language code; use a BCP-47 tag such as en or pt-BR"+ )+ return code+def analyze_text(text: str,features: Optional[list] = None,api_key: Optional[str] = None,- language: str = "en",+ language: Optional[str] = None,) -> dict:"""Analyze text using Google Cloud Natural Language API.@@ -69,7 +84,8 @@ def analyze_text(text: Text content to analyze (max 1M characters).features: List of features: entities, sentiment, classify, moderate.api_key: Google API key.- language: Language code (default: en).+ language: BCP-47 language code. Omitted by default so the API+ detects the language; the result then reports the detected code.Returns:Dictionary with entities, sentiment, categories, and moderation results.@@ -95,14 +111,13 @@ def analyze_text(document = {"type": "PLAIN_TEXT","content": text[:100000], # API limit- "languageCode": language,- }- # v1 names the field "language" and rejects "languageCode" with HTTP 400.- v1_document = {- "type": "PLAIN_TEXT",- "content": document["content"],- "language": language,}+ v1_document = dict(document)+ # Without a language field the API auto-detects. v1 names the field+ # "language" and rejects "languageCode" with HTTP 400.+ if language:+ document["languageCode"] = language+ v1_document["language"] = language# Entities still use v1 because it returns Knowledge Graph metadata# and salience consistently. Other features stay on v2 annotateText.@@ -151,6 +166,7 @@ def analyze_text(})result["entities"].sort(key=lambda e: e["salience"], reverse=True)+ result["language"] = result["language"] or entity_data.get("language")feature_map = {}for f in features:@@ -193,6 +209,8 @@ def analyze_text(result["error"] = f"NLP API request failed: {redact_google_api_key(e)}"return result+ result["language"] = result["language"] or data.get("languageCode")+# Document sentimentdoc_sentiment = data.get("documentSentiment", {})if doc_sentiment:@@ -247,6 +265,7 @@ def analyze_url(url: str,features: Optional[list] = None,api_key: Optional[str] = None,+ language: Optional[str] = None,) -> dict:"""Fetch a URL's text content and analyze it.@@ -255,6 +274,7 @@ def analyze_url(url: URL to fetch and analyze.features: NLP features to extract.api_key: API key override.+ language: BCP-47 language code (default: auto-detect).Returns:Dictionary with NLP analysis results.@@ -295,7 +315,7 @@ def analyze_url(if not text or len(text) < 50:return {"error": "Extracted text too short for meaningful NLP analysis."}- result = analyze_text(text, features=features, api_key=api_key)+ result = analyze_text(text, features=features, api_key=api_key, language=language)result["source_url"] = urlresult["extracted_text_length"] = len(text)return result@@ -312,6 +332,11 @@ def main():default="entities,sentiment,classify",help="Comma-separated features: entities, sentiment, classify, moderate (default: entities,sentiment,classify)",)+ parser.add_argument(+ "--language", "-l",+ type=language_code,+ help="Content language as a BCP-47 code, e.g. en or pt-BR (default: auto-detect)",+ )parser.add_argument("--api-key", help="API key override")parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")@@ -324,9 +349,13 @@ def main():features = [f.strip() for f in args.features.split(",")]if args.url:- result = analyze_url(args.url, features=features, api_key=args.api_key)+ result = analyze_url(+ args.url, features=features, api_key=args.api_key, language=args.language+ )else:- result = analyze_text(args.text, features=features, api_key=args.api_key)+ result = analyze_text(+ args.text, features=features, api_key=args.api_key, language=args.language+ )if result.get("error"):print(f"Error: {result['error']}", file=sys.stderr)diff --git a/skills/seo-google/SKILL.md b/skills/seo-google/SKILL.mdindex 8a3a422..adfa734 100644--- a/skills/seo-google/SKILL.md+++ b/skills/seo-google/SKILL.md@@ -120,7 +120,9 @@ Output includes per-metric trend direction, percentage change, and weekly p75 vaSearch Analytics: clicks, impressions, CTR, position for last 28 days.-**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run gsc_query.py --domain <audited-domain> --json`+**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run gsc_query.py --property <property> --json`+**Site URL or host instead of a property** (every site audit): `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run gsc_query.py --domain <audited-domain> --json`+**Which flag:** a GSC property (`sc-domain:example.com`, or a URL-prefix property the user named as such) goes to `--property`; a site URL or host goes to `--domain`, which looks up that site's property and refuses another site's. Never pass a property to `--domain` or leave either flag empty. With neither flag the script names the default property on stderr, or exits if a `sites` mapping is configured (`references/auth-setup.md`).**Reference:** `references/search-console-api.md`**Default:** 28 days, dimensions=query,page, type=web, limit=1000.@@ -168,7 +170,8 @@ List submitted sitemaps with status, errors, warnings. Sitemap contents reportsubmitted counts only; URL Inspection API is the indexation truth for whetherspecific URLs are indexed.-**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run gsc_query.py sitemaps --domain <audited-domain> --json`+**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run gsc_query.py sitemaps --property <property> --json`+**Site URL or host instead of a property:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run gsc_query.py sitemaps --domain <audited-domain> --json`---@@ -198,7 +201,9 @@ Batch submit URLs from a file. Tracks quota usage.Organic traffic report: daily sessions, users, pageviews, bounce rate, engagement.-**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run ga4_report.py --domain <audited-domain> --json`+**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run ga4_report.py --property <property-id> --json`+**Site URL or host, or no property ID given** (every site audit): `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run ga4_report.py --domain <audited-domain> --json`+**Which flag:** a numeric GA4 property ID goes to `--property`; a site URL or host goes to `--domain`. Same rules as `gsc` above.**Reference:** `references/ga4-data-api.md`**Default:** 28 days, filtered to Organic Search channel group.@@ -208,7 +213,8 @@ Organic traffic report: daily sessions, users, pageviews, bounce rate, engagemenTop organic landing pages ranked by sessions.-**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run ga4_report.py --domain <audited-domain> --report top-pages --json`+**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run ga4_report.py --property <property-id> --report top-pages --json`+**Site URL or host, or no property ID given:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run ga4_report.py --domain <audited-domain> --report top-pages --json`---@@ -243,6 +249,7 @@ Full NLP analysis: entities, sentiment, content classification.**Script:** `"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run nlp_analyze.py --url <url> --json` or `--text "..."`**Reference:** `references/nlp-api.md`+**Language:** auto-detected by default; add `--language <code>` (BCP-47, e.g. `pt-BR`) only to override the detection. The JSON `language` field reports the code used.**Free tier:** 5,000 units/month. Requires billing enabled on GCP project.### `/seo google entities <url-or-text>`diff --git a/skills/seo-google/references/auth-setup.md b/skills/seo-google/references/auth-setup.mdindex 030fa3e..531f2e1 100644--- a/skills/seo-google/references/auth-setup.md+++ b/skills/seo-google/references/auth-setup.md@@ -106,14 +106,21 @@ Save to `~/.config/claude-seo/google-api.json`:}```-For site audits, pass `--domain <audited-domain>` to `gsc_query.py` and-`ga4_report.py`; `gsc_inspect.py` accepts the same flag (or derives the host-from a single inspected URL). `sites` keys are exact hostnames and-map to that site's properties. If no exact mapping exists, a legacy global-property is usable only when its GSC domain matches the requested domain;-otherwise the script fails closed rather than querying another site's data.-Keep explicit `--property` / `--site-url` for intentional direct property-queries outside a domain-specific audit.+For site audits, pass `--domain <audited-domain>` (a host or site URL, never a+property) to `gsc_query.py` and `ga4_report.py`; `gsc_inspect.py` accepts the+same flag (or derives the host from a single inspected URL). `sites` keys are+hostnames and map to that site's properties. A key matches its host with or+without `www.`, and an entry whose `gsc_property` is `sc-domain:D` also covers+subdomains of D (`shop.example.com`, never `notexample.com`). If no entry+matches, a legacy global property is usable only when its GSC domain matches+the requested domain; otherwise the script fails closed rather than querying+another site's data. Keep explicit `--property` / `--site-url` for intentional+direct property queries outside a domain-specific audit.++With neither flag, `gsc_query.py` and `ga4_report.py` use the global default+and name it on stderr and in the JSON `property` field. Once a `sites` mapping+exists they exit instead and ask for `--domain` or `--property`. An empty flag+value (`--domain ""`) is always an error.### Property URL Formatsdiff --git a/skills/seo-google/references/nlp-api.md b/skills/seo-google/references/nlp-api.mdindex 58a25b8..87c1f9e 100644--- a/skills/seo-google/references/nlp-api.md+++ b/skills/seo-google/references/nlp-api.md@@ -10,6 +10,15 @@ Sentiment, classification, and moderation useSend the API key in the `X-Goog-Api-Key` header, not in the URL.+## Language++`nlp_analyze.py` sends no language by default, so the API detects it and the+JSON `language` field reports the detected code. Pass `--language <code>`+(BCP-47, e.g. `en`, `pt-BR`, `zh-Hant`) to override detection. The v1 entity+call takes the code as `document.language`, the v2 call as+`document.languageCode`. Language support differs per feature, so an+unsupported language returns an API error for that feature.+## Features| Feature | What It Does | SEO Use |diff --git a/tests/test_dataforseo_merchant_polling.py b/tests/test_dataforseo_merchant_polling.pyindex 8e17049..80f4489 100644--- a/tests/test_dataforseo_merchant_polling.py+++ b/tests/test_dataforseo_merchant_polling.py@@ -9,6 +9,7 @@ had finished and ``_extract_items`` crashed iterating ``None``.from __future__ import annotations+import jsonimport osimport sysfrom unittest.mock import patch@@ -63,9 +64,49 @@ def test_keeps_polling_while_task_is_handed_or_queued():def test_returns_a_real_task_error_without_waiting():- data, calls = _poll([_task_get(40102, None)])+ body = _task_get(40102, None)+ body["tasks"][0]["status_message"] = "No Search Results."+ data, calls = _poll([body])assert calls == 1- assert data["tasks"][0]["status_code"] == 40102+ assert data == {+ "error": "task_error",+ "status_code": 40102,+ "message": "No Search Results.",+ }++[email protected]("command", ["search", "sellers", "compare"])+def test_cli_surfaces_a_terminal_task_error_instead_of_empty_success(+ command, capsys, monkeypatch+):+ """A failed task has ``result: null``; it must not print 0 results as success."""+ monkeypatch.setenv("DATAFORSEO_USERNAME", "user")+ monkeypatch.setenv("DATAFORSEO_PASSWORD", "DUMMY")+ failed = _task_get(40501, None)+ failed["tasks"][0]["status_message"] = "Invalid Field."+ posted = {"status_code": 20000, "tasks": [{"id": "task-1"}]}+ argv = ["dataforseo_merchant.py", command, "standing desk"]+ with patch.object(sys, "argv", argv), patch.object(+ dataforseo_merchant.time, "sleep"+ ), patch.object(+ dataforseo_merchant.requests, "post", side_effect=lambda *a, **k: FakeResponse(posted)+ ), patch.object(+ dataforseo_merchant.requests, "get", side_effect=lambda *a, **k: FakeResponse(failed)+ ):+ dataforseo_merchant.main()++ output = json.loads(capsys.readouterr().out)+ if command == "compare":+ assert output["comparison"] == {+ "google": {"error": "Invalid Field."},+ "amazon": {"error": "Invalid Field."},+ }+ else:+ assert output == {+ "error": "task_error",+ "status_code": 40501,+ "message": "Invalid Field.",+ }def test_extract_items_tolerates_null_result():diff --git a/tests/test_google_property_cli.py b/tests/test_google_property_cli.pynew file mode 100644index 0000000..d7b4676--- /dev/null+++ b/tests/test_google_property_cli.py@@ -0,0 +1,195 @@+"""CLI-level property selection for ga4_report, gsc_query and gsc_inspect.++Issue #337: a Google report must never silently use another site's property.+Every test runs ``main()`` with a mocked config and no API client, so the JSON+result carries the chosen property next to a "could not build client" error.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import pytest++_SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"+if str(_SCRIPTS) not in sys.path:+ sys.path.insert(0, str(_SCRIPTS))++pytest.importorskip("googleapiclient")+pytest.importorskip("google.analytics.data_v1beta")++import ga4_report # noqa: E402+import gsc_inspect # noqa: E402+import gsc_query # noqa: E402++LEGACY = {+ "default_property": "sc-domain:primary.example",+ "ga4_property_id": "properties/100",+}+MAPPED = {+ **LEGACY,+ "sites": {+ "example.com": {+ "gsc_property": "sc-domain:example.com",+ "ga4_property_id": "properties/200",+ }+ },+}+PAGE = "https://example.com/page"++# script -> (module, leading args, explicit property flag, explicit value,+# property the example.com sites entry resolves to)+SCRIPTS = {+ "ga4": (ga4_report, [], "--property", "999", "200"),+ "gsc": (gsc_query, [], "--property", "sc-domain:other.example", "sc-domain:example.com"),+ "sitemaps": (+ gsc_query, ["sitemaps"], "--property", "sc-domain:other.example", "sc-domain:example.com",+ ),+ "inspect": (+ gsc_inspect, [PAGE], "--site-url", "sc-domain:other.example", "sc-domain:example.com",+ ),+}+ALL = pytest.mark.parametrize("script", sorted(SCRIPTS))+++def run(monkeypatch, capsys):+ """Run a script's main() offline; return (exit code, parsed stdout, stderr)."""+ built = []++ def no_client():+ built.append(True)+ return None++ monkeypatch.setattr(ga4_report, "_build_ga4_client", no_client)+ monkeypatch.setattr(gsc_query, "_build_gsc_service", no_client)+ monkeypatch.setattr(gsc_inspect, "_build_inspection_service", no_client)+ monkeypatch.setattr(gsc_inspect, "validate_url", lambda url: True)++ def _run(script, extra: list[str], config: dict):+ """``script`` is a SCRIPTS key or a (module, leading args) pair."""+ module, leading = (SCRIPTS[script] if isinstance(script, str) else script)[:2]+ monkeypatch.setattr(module, "load_config", lambda: dict(config))+ monkeypatch.setattr(sys, "argv", [f"{module.__name__}.py", *leading, *extra, "--json"])+ del built[:]+ code = 0+ try:+ module.main()+ except SystemExit as exit_info:+ code = exit_info.code+ captured = capsys.readouterr()+ output = json.loads(captured.out) if captured.out.strip() else None+ if code:+ assert output is None and not built, "a refused run must not reach the API"+ return code, output, captured.err++ return _run+++@ALL+def test_explicit_property_wins_over_sites_and_default(run, script):+ flag, explicit = SCRIPTS[script][2:4]+ code, output, err = run(script, [flag, explicit], MAPPED)+ assert code == 0+ assert output["property"] == explicit+ assert "Note:" not in err+++@ALL[email protected]("value", ["", " "])+def test_empty_domain_is_an_error_not_the_default(run, script, value):+ code, output, err = run(script, ["--domain", value], LEGACY)+ assert code == 1+ assert "--domain was given an empty value" in err+++@ALL+def test_empty_explicit_property_is_an_error_not_the_default(run, script):+ flag = SCRIPTS[script][2]+ code, output, err = run(script, [flag, ""], LEGACY)+ assert code == 1+ assert f"{flag} was given an empty value" in err+++@ALL+ "domain",+ [+ "example.com",+ "https://www.example.com/pricing", # www is the same site as the key+ "shop.example.com", # sc-domain:example.com covers its subdomains+ ],+)+def test_domain_resolves_to_the_sites_entry(run, script, domain):+ code, output, err = run(script, ["--domain", domain], MAPPED)+ assert code == 0+ assert output["property"] == SCRIPTS[script][4]+++@ALL+def test_www_key_matches_the_bare_host(run, script):+ config = {**LEGACY, "sites": {"www.example.com": MAPPED["sites"]["example.com"]}}+ code, output, err = run(script, ["--domain", "example.com"], config)+ assert code == 0+ assert output["property"] == SCRIPTS[script][4]+++@ALL[email protected]("domain", ["notexample.com", "example.com.evil.test", "example.co"])+def test_lookalike_host_is_refused(run, script, domain):+ code, output, err = run(script, ["--domain", domain], MAPPED)+ assert code == 1+ assert "refusing to use a different site's default" in err++[email protected]("script", ["ga4", "gsc", "sitemaps"])+def test_no_flag_with_sites_mapping_requires_a_choice(run, script):+ code, output, err = run(script, [], MAPPED)+ assert code == 1+ assert "--domain" in err and "--property" in err+ assert "sites mapping" in err+++ ("script", "default"),+ [("ga4", "100"), ("gsc", "sc-domain:primary.example"), ("sitemaps", "sc-domain:primary.example")],+)+def test_no_flag_without_sites_names_the_default_property(run, script, default):+ code, output, err = run(script, [], LEGACY)+ assert code == 0+ assert output["property"] == default+ assert f"property {default} from config" in err++[email protected]("script", ["ga4", "gsc"])+def test_no_flag_and_no_default_still_errors(run, script):+ code, output, err = run(script, [], {})+ assert code == 1+ assert "No " in err and "property specified" in err+++def test_gsc_sites_listing_needs_no_property(run):+ code, output, err = run((gsc_query, ["sites"]), [], MAPPED)+ assert code == 0+ assert output["sites"] == []+++def test_inspect_without_flags_binds_to_the_inspected_url(run):+ code, output, err = run("inspect", [], MAPPED)+ assert code == 0+ assert output["property"] == "sc-domain:example.com"++ code, output, err = run((gsc_inspect, ["https://notexample.com/page"]), [], MAPPED)+ assert code == 1+ assert "refusing to use a different site's default" in err++[email protected]("flags", [[], ["--domain", ""]])+def test_inspect_batch_requires_a_non_empty_site(run, tmp_path, flags):+ batch = tmp_path / "urls.txt"+ batch.write_text(PAGE + "\n")+ code, output, err = run((gsc_inspect, ["--batch", str(batch)]), flags, LEGACY)+ assert code in (1, 2)+ assert "--domain" in errdiff --git a/tests/test_google_property_resolution.py b/tests/test_google_property_resolution.pyindex fa71ccb..05de2ee 100644--- a/tests/test_google_property_resolution.py+++ b/tests/test_google_property_resolution.py@@ -75,3 +75,86 @@ def test_duplicate_normalized_site_keys_are_rejected() -> None:with pytest.raises(ValueError, match="Multiple sites entries"):resolve_site_property(config, "gsc", "example.com")+++def _site(domain: str, ga4: str = "properties/200", prop: str | None = None) -> dict:+ return {"gsc_property": prop or f"sc-domain:{domain}", "ga4_property_id": ga4}+++def test_www_is_the_same_site_on_either_side_of_the_mapping() -> None:+ bare_key = {"sites": {"example.com": _site("example.com")}}+ www_key = {"sites": {"www.example.com": _site("example.com", prop="https://www.example.com/")}}++ assert resolve_site_property(bare_key, "gsc", "https://www.example.com") == "sc-domain:example.com"+ assert resolve_site_property(bare_key, "ga4", "www.example.com") == "properties/200"+ assert resolve_site_property(www_key, "gsc", "example.com") == "https://www.example.com/"+++def test_exact_key_beats_its_www_twin() -> None:+ config = {+ "sites": {+ "example.com": _site("example.com", prop="https://example.com/"),+ "www.example.com": _site("example.com", prop="https://www.example.com/"),+ }+ }++ assert resolve_site_property(config, "gsc", "example.com") == "https://example.com/"+ assert resolve_site_property(config, "gsc", "www.example.com") == "https://www.example.com/"+++def test_domain_property_entry_covers_subdomains_by_dot_suffix_only() -> None:+ config = {+ "default_property": "sc-domain:primary.example",+ "ga4_property_id": "properties/100",+ "sites": {"example.com": _site("example.com")},+ }++ assert resolve_site_property(config, "gsc", "shop.example.com") == "sc-domain:example.com"+ assert resolve_site_property(config, "ga4", "https://a.b.example.com/x") == "properties/200"+ for lookalike in ("notexample.com", "example.com.evil.test", "example.co"):+ with pytest.raises(ValueError, match="refusing to use a different site's default"):+ resolve_site_property(config, "gsc", lookalike)+++def test_url_prefix_entry_does_not_cover_subdomains() -> None:+ config = {"sites": {"example.com": _site("example.com", prop="https://example.com/")}}++ with pytest.raises(ValueError, match="refusing to use a different site's default"):+ resolve_site_property(config, "gsc", "shop.example.com")+++def test_most_specific_covering_entry_wins() -> None:+ config = {+ "sites": {+ "example.com": _site("example.com", ga4="properties/1"),+ "blog.example.com": _site("blog.example.com", ga4="properties/2"),+ }+ }++ assert resolve_site_property(config, "ga4", "a.blog.example.com") == "properties/2"+ assert resolve_site_property(config, "ga4", "shop.example.com") == "properties/1"+++def test_entries_sharing_a_domain_property_prefer_the_domains_own_entry() -> None:+ shared = {+ "example.com": _site("example.com", ga4="properties/1"),+ "blog.example.com": _site("example.com", ga4="properties/2"),+ }++ assert resolve_site_property({"sites": shared}, "ga4", "shop.example.com") == "properties/1"+ assert resolve_site_property({"sites": shared}, "ga4", "blog.example.com") == "properties/2"++ ambiguous = {+ "blog.example.com": _site("example.com", ga4="properties/2"),+ "docs.example.com": _site("example.com", ga4="properties/3"),+ }+ with pytest.raises(ValueError, match="Multiple sites entries cover"):+ resolve_site_property({"sites": ambiguous}, "ga4", "shop.example.com")+++def test_legacy_url_prefix_default_treats_www_as_the_same_site() -> None:+ config = {"default_property": "https://www.example.com/", "ga4_property_id": "properties/123"}++ assert resolve_site_property(config, "gsc", "example.com") == "https://www.example.com/"+ with pytest.raises(ValueError, match="refusing to use a different site's default"):+ resolve_site_property(config, "gsc", "shop.example.com")diff --git a/tests/test_google_report_full_audit.py b/tests/test_google_report_full_audit.pyindex 097b23c..bf9b3d0 100644--- a/tests/test_google_report_full_audit.py+++ b/tests/test_google_report_full_audit.py@@ -9,6 +9,8 @@ import sysfrom pathlib import Pathfrom unittest.mock import patch+import pytest+_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")if _SCRIPTS not in sys.path:sys.path.insert(0, _SCRIPTS)@@ -221,3 +223,25 @@ def test_full_audit_categories_dict_finding_keeps_explicit_severity() -> None:html = google_report._build_full_audit_categories(data)assert '<h4>Canonical mismatch <span class="status-warn">Critical</span></h4>' in html+++def test_cwv_trend_table_renders_zero_baseline_change_as_not_available() -> None:+ """crux_history reports change_pct None for a rise from zero (PR #393)."""+ pytest.importorskip("requests")+ import crux_history++ trends = crux_history.detect_trends({+ "cumulative_layout_shift": {+ "p75_values": [0] * 4 + [0.2] * 4, "label": "CLS", "unit": "",+ },+ "largest_contentful_paint": {+ "p75_values": [2000] * 4 + [3000] * 4, "label": "LCP", "unit": "ms",+ },+ })+ assert trends["cumulative_layout_shift"]["change_pct"] is None++ html, _ = google_report._build_cwv_section({}, {}, {}, history_data={"trends": trends})++ assert '<td class="status-fail">DEGRADING</td>\n <td>n/a</td>' in html+ assert "<td>+50.0%</td>" in html+ assert "None" not in htmldiff --git a/tests/test_nlp_analyze.py b/tests/test_nlp_analyze.pyindex 7521765..9d94612 100644--- a/tests/test_nlp_analyze.py+++ b/tests/test_nlp_analyze.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonimport osimport sysfrom unittest.mock import patch@@ -117,3 +118,75 @@ def test_each_endpoint_gets_its_own_language_field_name() -> None:assert v2_document["languageCode"] == "pt"assert "language" not in v2_documentassert v1_document["content"] == v2_document["content"]+++def _capture_bodies(bodies: dict[str, dict]):+ def fake_post(url: str, **kwargs):+ bodies[url] = kwargs["json"]+ if url == nlp_analyze.NLP_V1_ENTITIES_ENDPOINT:+ return FakeResponse({"entities": [], "language": "pt"})+ return FakeResponse({+ "documentSentiment": {"score": 0.0, "magnitude": 0.0},+ "languageCode": "pt",+ })++ return fake_post++[email protected]("features", [["entities", "sentiment"], ["entities"], ["sentiment"]])+def test_language_is_omitted_by_default_so_the_api_detects_it(features) -> None:+ """Issue #322: the language was hard-coded to "en" for every document."""+ bodies: dict[str, dict] = {}++ with patch.object(nlp_analyze.requests, "post", side_effect=_capture_bodies(bodies)):+ result = nlp_analyze.analyze_text(+ "O Quenia tem corredores de maratona.",+ features=features,+ api_key="AI" + "zaSyDUMMYSECRET",+ )++ assert bodies+ for body in bodies.values():+ assert "language" not in body["document"]+ assert "languageCode" not in body["document"]+ assert result["language"] == "pt"+ assert result["error"] is None++[email protected]("source", ["text", "url"])+def test_cli_language_option_reaches_both_request_bodies(source, capsys) -> None:+ bodies: dict[str, dict] = {}+ page = "<html><body><p>" + "O Quenia tem corredores de maratona. " * 3 + "</p></body></html>"+ argv = ["nlp_analyze.py", "--language", "pt-BR", "--features", "entities,sentiment",+ "--api-key", "AI" + "zaSyDUMMYSECRET", "--json"]+ argv += ["--text", "O Quenia tem corredores."] if source == "text" else ["--url", "https://example.com/"]++ with patch.object(sys, "argv", argv), \+ patch.object(nlp_analyze, "validate_url", return_value=True), \+ patch.object(nlp_analyze, "safe_requests_get", return_value=FakeResponse({})), \+ patch.object(nlp_analyze, "decode_response_text", return_value=page), \+ patch.object(nlp_analyze.requests, "post", side_effect=_capture_bodies(bodies)):+ nlp_analyze.main()++ assert bodies[nlp_analyze.NLP_V1_ENTITIES_ENDPOINT]["document"]["language"] == "pt-BR"+ assert bodies[nlp_analyze.NLP_ENDPOINT]["document"]["languageCode"] == "pt-BR"+ assert json.loads(capsys.readouterr().out)["language"] == "pt-BR"++[email protected]("value", ["", "english!", "pt_BR", "e", "en-", "en us"])+def test_cli_rejects_a_value_that_is_not_a_language_code(value, capsys) -> None:+ argv = ["nlp_analyze.py", "--text", "Kenya has marathon runners.", "--language", value]++ with patch.object(sys, "argv", argv), \+ patch.object(nlp_analyze.requests, "post") as post, \+ pytest.raises(SystemExit) as exit_info:+ nlp_analyze.main()++ assert exit_info.value.code == 2+ assert "not a language code" in capsys.readouterr().err+ post.assert_not_called()++[email protected]("value", ["en", "pt-BR", "zh-Hant", "zh-Hant-TW", "fil", "es-419"])+def test_language_code_accepts_bcp47_looking_tags(value) -> None:+ assert nlp_analyze.language_code(f" {value} ") == value