Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add ahrefs link intersect, brand radar and top domains tables (#119199)

Tom Owers62262916a31a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 20ecafa05327..149363af5d03 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -299,6 +299,11 @@ Diffed against: <https://docs.ahrefs.com/openapi.json>
- [ ] `Referring domains (GET /v3/site-explorer/refdomains)` — measures unique linking domains and their authority (medium)
- [ ] `Top pages (GET /v3/site-explorer/top-pages)` — identifies pages that drive organic traffic and revenue opportunities (medium)
- [ ] `Brand Radar mentions history (GET /v3/brand-radar/mentions-history)` — measures brand visibility trends across AI search platforms (medium)
+- [x] `Link intersect referring domains (POST /v3/competitive-analysis/link-intersect-refdomains)` — finds domains that link to competitors, for link building (medium)
+- [x] `Link intersect referring pages (POST /v3/competitive-analysis/link-intersect-refpages)` — finds pages that link to competitors, for link building (medium)
+- [x] `Brand Radar web pages (POST /v3/brand-radar/web-pages)` — web pages that mention the tracked brands or competitors (medium)
+- [x] `Domain Rating top domains (GET /v3/public/domain-rating-top-domains)` — free top 1M domains by Domain Rating, a dimension for referring domains (low)
+- [ ] `Content Helper topics (GET /v3/content-helper/topics)` — skipped: needs a keyword per request and costs 1,000 units per call, an on-demand writing aid rather than account data (low)
Note: Fetched the combined official OpenAPI spec and inspected all GET paths. The source calls only three Site Audit endpoints; SEO and Brand Radar reports are absent. New reports need target, project, date, or brand inputs and consume API units. Authentication, crawler infrastructure, and write operations were excluded.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
index 26f1f82579de..c1366d1e4abe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
@@ -3,12 +3,17 @@ from datetime import UTC, date, datetime, timedelta
from typing import Any, cast
import structlog
+from requests import Request, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.settings import (
API_BASE_URL,
ENDPOINTS,
HISTORY_DAYS,
+ MAX_COMPETITORS,
NON_RETRYABLE_ERRORS,
+ TOP_DOMAINS_COUNT,
+ TOP_DOMAINS_PAGE_ROWS,
+ EndpointSettings,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
@@ -19,10 +24,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
create_response_hooks,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ ResponseAction,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -71,19 +80,45 @@ def validate_credentials(api_key: str) -> tuple[bool, str | None]:
return True, None
-def _site_audit_target(api_key: str, project_id: str) -> dict[str, Any]:
+class RankRangePaginator(BasePaginator):
+ def __init__(self, page_rows: int, max_rank: int) -> None:
+ super().__init__()
+ self.page_rows = page_rows
+ self.max_rank = max_rank
+ self.start = 1
+
+ def init_request(self, request: Request) -> None:
+ self._set_range(request)
+
+ def update_state(self, response: Response, data: list[Any] | None = None) -> None:
+ self.start += self.page_rows
+ self._has_next_page = len(data or []) >= self.page_rows and self.start <= self.max_rank
+
+ def update_request(self, request: Request) -> None:
+ self._set_range(request)
+
+ def _set_range(self, request: Request) -> None:
+ end = min(self.start + self.page_rows - 1, self.max_rank)
+ request.params = {**(request.params or {}), "from": self.start, "to": end}
+
+
+def _lookup(api_key: str, path: str, params: dict[str, str], data_selector: str) -> Iterator[dict[str, Any]]:
client = RESTClient(base_url=API_BASE_URL, auth=BearerTokenAuth(token=api_key), request_timeout=(10, 60))
for page in client.paginate(
- path="site-audit/projects",
- params={"output": "json", "project_id": project_id},
- data_selector="healthscores",
+ path=path,
+ params={"output": "json", **params},
+ data_selector=data_selector,
data_selector_required=True,
paginator=SinglePagePaginator(),
hooks=create_response_hooks(RESPONSE_ACTIONS),
):
- for row in page:
- if row.get("target_url"):
- return row
+ yield from page
+
+
+def _site_audit_target(api_key: str, project_id: str) -> dict[str, Any]:
+ for row in _lookup(api_key, "site-audit/projects", {"project_id": project_id}, "healthscores"):
+ if row.get("target_url"):
+ return row
raise ValueError("ahrefs_project_not_found")
@@ -99,6 +134,76 @@ def _target_params(api_key: str, project_id: str, names: list[str]) -> dict[str,
return {name: value for name, value in values.items() if name in names and value}
+def _post(settings: EndpointSettings, body: dict[str, Any]) -> Endpoint:
+ return {"path": settings["path"], "method": "POST", "json": {"output": "json", **settings.get("body", {}), **body}}
+
+
+def _endpoint_requests(
+ api_key: str,
+ project_id: str,
+ endpoint: str,
+ settings: EndpointSettings,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[tuple[Endpoint, dict[str, object]]]:
+ kind = settings.get("kind")
+ if kind == "link_intersect":
+ competitors = [
+ {"url": row["url"], "mode": row.get("mode") or "subdomains", "protocol": "both"}
+ for row in _lookup(api_key, "management/project-competitors", {"project_id": project_id}, "competitors")
+ if row.get("url")
+ ][:MAX_COMPETITORS]
+ if not competitors:
+ logger.info("ahrefs_no_project_competitors", endpoint=endpoint, project_id=project_id)
+ return
+ project = _site_audit_target(api_key, project_id)
+ select = [*settings.get("body", {})["select"]]
+ select.extend(f"links_to_competitor_{position}" for position in range(1, len(competitors) + 1))
+ target = {
+ "url": project["target_url"],
+ "mode": project.get("target_mode") or "subdomains",
+ "protocol": project.get("target_protocol") or "both",
+ }
+ # links_to_competitor_N columns follow the order of this list.
+ competitor_urls: list[str] = [competitor["url"] for competitor in competitors]
+ yield (
+ _post(settings, {"select": select, "target": target, "competitors": competitors}),
+ {"competitors": competitor_urls},
+ )
+ elif kind == "brand_radar":
+ report_ids = [
+ str(row["report_id"])
+ for row in _lookup(api_key, "management/brand-radar-reports", {}, "reports")
+ if row.get("report_id") and str(row.get("project_id")) == project_id
+ ]
+ if not report_ids:
+ logger.info("ahrefs_no_brand_radar_reports", endpoint=endpoint, project_id=project_id)
+ for report_id in report_ids:
+ yield _post(settings, {"report_id": report_id}), {"report_id": report_id}
+ elif kind == "top_domains":
+ yield (
+ {
+ "path": settings["path"],
+ "params": {"output": "json"},
+ "paginator": RankRangePaginator(TOP_DOMAINS_PAGE_ROWS, TOP_DOMAINS_COUNT),
+ },
+ {},
+ )
+ else:
+ params: dict[str, Any] = {
+ "output": "json",
+ **settings["params"],
+ **_target_params(api_key, project_id, settings.get("target_params", [])),
+ }
+ if settings.get("project_scoped", True) and not settings.get("target_params"):
+ params["project_id"] = project_id
+ if settings.get("history", False):
+ params["date_from"] = _history_start(
+ should_use_incremental_field, db_incremental_field_last_value, datetime.now(UTC).date()
+ )
+ yield {"path": settings["path"], "params": params}, {}
+
+
def _history_start(should_use_incremental_field: bool, last_value: Any, today: date) -> str:
if should_use_incremental_field and last_value:
if isinstance(last_value, datetime):
@@ -133,56 +238,55 @@ def ahrefs_source(
normalized_project_id = str(int(project_id))
project_scoped = settings.get("project_scoped", True)
history = settings.get("history", False)
- row_limit = settings["params"].get("limit")
-
- def add_project_id(row: dict[str, object]) -> dict[str, object]:
- return {**row, "project_id": normalized_project_id}
+ row_limit = settings["params"].get("limit") or settings.get("body", {}).get("limit")
def items() -> Iterator[list[dict[str, object]]]:
- params: dict[str, Any] = {
- "output": "json",
- **settings["params"],
- **_target_params(api_key, normalized_project_id, settings.get("target_params", [])),
- }
- if project_scoped and not settings.get("target_params"):
- params["project_id"] = normalized_project_id
- if history:
- params["date_from"] = _history_start(
- should_use_incremental_field, db_incremental_field_last_value, datetime.now(UTC).date()
- )
- config: RESTAPIConfig = {
- "client": {
- "base_url": API_BASE_URL,
- "auth": {"type": "bearer", "token": api_key},
- "paginator": "single_page",
- "request_timeout": (10, 60),
- },
- "resources": [
- {
- "name": endpoint,
- "write_disposition": {"disposition": "merge", "strategy": "upsert"}
- if history and should_use_incremental_field
- else "replace",
- "endpoint": {
- "path": settings["path"],
- "data_selector": settings["data_selector"],
- "data_selector_required": True,
- "params": params,
- "response_actions": RESPONSE_ACTIONS,
- },
- "data_map": add_project_id if project_scoped else None,
- }
- ],
- }
- resource = rest_api_resource(config, team_id, job_id, None)
- for page in resource:
- if row_limit is not None and len(page) >= int(row_limit):
- logger.info("ahrefs_sample_limit_reached", team_id=team_id, endpoint=endpoint, limit=row_limit)
- page = page[: int(row_limit)]
- page = _unique_rows(page, settings["primary_keys"])
- if history:
- page = sorted(page, key=lambda row: str(row.get("date") or ""))
- yield page
+ for request, row_fields in _endpoint_requests(
+ api_key,
+ normalized_project_id,
+ endpoint,
+ settings,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ ):
+
+ def add_project_fields(
+ row: dict[str, object], row_fields: dict[str, object] = row_fields
+ ) -> dict[str, object]:
+ return {**row, "project_id": normalized_project_id, **row_fields}
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": API_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": "single_page",
+ "request_timeout": (10, 60),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if history and should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ **request,
+ "data_selector": settings["data_selector"],
+ "data_selector_required": True,
+ "response_actions": RESPONSE_ACTIONS,
+ },
+ "data_map": add_project_fields if project_scoped else None,
+ }
+ ],
+ }
+ resource = rest_api_resource(config, team_id, job_id, None)
+ for page in resource:
+ if row_limit is not None and len(page) >= int(row_limit):
+ logger.info("ahrefs_sample_limit_reached", team_id=team_id, endpoint=endpoint, limit=row_limit)
+ page = page[: int(row_limit)]
+ page = _unique_rows(page, settings["primary_keys"])
+ if history:
+ page = sorted(page, key=lambda row: str(row.get("date") or ""))
+ yield page
return SourceResponse(
name=endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
index 612aac27dfe0..2741ea1f9459 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
@@ -111,4 +111,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"last_visited": "Date a live link to the target was last verified.",
},
},
+ "link_intersect_refdomains": {
+ "description": "Referring domains that link to the selected project's target or its Ahrefs competitors.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/competitive-analysis/post-link-intersect-refdomains",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "domain": "The referring domain.",
+ "domain_rating": "Domain Rating of the referring domain.",
+ "intersect": "Number of competitors this result links to.",
+ "links_to_target": "Number of links from this result to the project's target.",
+ "competitors": (
+ "Competitor URLs from the Ahrefs project, in the order used by the links_to_competitor_N columns."
+ ),
+ },
+ },
+ "link_intersect_refpages": {
+ "description": "Referring pages that link to the selected project's target or its Ahrefs competitors.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/competitive-analysis/post-link-intersect-refpages",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "url": "URL of the referring page.",
+ "title": "Title of the referring page.",
+ "domain_rating": "Domain Rating of the referring page's domain.",
+ "url_rating": "URL Rating of the referring page.",
+ "intersect": "Number of competitors this result links to.",
+ "links_to_target": "Number of links from this result to the project's target.",
+ "competitors": (
+ "Competitor URLs from the Ahrefs project, in the order used by the links_to_competitor_N columns."
+ ),
+ },
+ },
+ "brand_radar_web_pages": {
+ "description": "Web pages that mention the brands or competitors in the project's Brand Radar reports.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/brand-radar/post-web-pages",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "report_id": "Identifier of the Brand Radar report the page was found for.",
+ "url": "URL of the page that mentions a brand or competitor.",
+ "title": "Title of the page.",
+ "content": "Excerpt of the page content that contains the mention.",
+ "domain_rating": "Domain Rating of the page's domain.",
+ "referring_domains": "Number of unique domains that link to the page.",
+ "traffic": "Estimated monthly organic search traffic of the page.",
+ "traffic_value": "Estimated monthly value of the page's organic search traffic, in USD.",
+ },
+ },
+ "domain_rating_top_domains": {
+ "description": "The top 1 million domains ranked by Ahrefs Domain Rating.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/public/get-domain-rating-top-domains",
+ "columns": {
+ "domain": "Domain name.",
+ "domain_rating": "Current Domain Rating of the domain, on a 100-point logarithmic scale.",
+ "rank": "Position of the domain in the ranking. 1 is the highest Domain Rating.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
index ef6a74f56515..61ff5460a1ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
@@ -1,4 +1,4 @@
-from typing import NotRequired, TypedDict
+from typing import Any, Literal, NotRequired, TypedDict
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -8,6 +8,11 @@ MAX_PAGE_ROWS = 100
MAX_BACKLINK_ROWS = 1000
# History rows cost API units and plans cap how far back history goes, so a first sync reads a bounded window.
HISTORY_DAYS = 180
+# Link intersect requests accept at most 20 competitors.
+MAX_COMPETITORS = 20
+MAX_WEB_PAGE_ROWS = 1000
+TOP_DOMAINS_COUNT = 1_000_000
+TOP_DOMAINS_PAGE_ROWS = 100_000
BACKLINK_FIELDS = (
"url_from",
@@ -45,6 +50,10 @@ class EndpointSettings(TypedDict):
# Site Explorer reports query the selected project's target with these parameters.
target_params: NotRequired[list[str]]
history: NotRequired[bool]
+ # POST reports take their parameters as a JSON body instead of the query string.
+ body: NotRequired[dict[str, Any]]
+ # Reports that need more inputs than the project's target, or more than one request.
+ kind: NotRequired[Literal["link_intersect", "brand_radar", "top_domains"]]
ENDPOINTS: dict[str, EndpointSettings] = {
@@ -119,6 +128,63 @@ ENDPOINTS: dict[str, EndpointSettings] = {
),
"target_params": ["target", "mode", "protocol"],
},
+ "link_intersect_refdomains": {
+ "path": "competitive-analysis/link-intersect-refdomains",
+ "data_selector": "referring-domains",
+ "primary_keys": ["project_id", "domain"],
+ "params": {},
+ "body": {
+ "select": ["domain", "domain_rating", "intersect", "links_to_target"],
+ "order_by": ["intersect:desc", "domain_rating:desc"],
+ "limit": MAX_BACKLINK_ROWS,
+ },
+ "description": (
+ f"Up to {MAX_BACKLINK_ROWS} referring domains that link to the selected project's target "
+ "or its competitors in Ahrefs, most shared first."
+ ),
+ "kind": "link_intersect",
+ },
+ "link_intersect_refpages": {
+ "path": "competitive-analysis/link-intersect-refpages",
+ "data_selector": "referring-pages",
+ "primary_keys": ["project_id", "url"],
+ "params": {},
+ "body": {
+ "select": ["url", "title", "domain_rating", "url_rating", "intersect", "links_to_target"],
+ "order_by": ["intersect:desc", "domain_rating:desc"],
+ "limit": MAX_BACKLINK_ROWS,
+ },
+ "description": (
+ f"Up to {MAX_BACKLINK_ROWS} referring pages that link to the selected project's target "
+ "or its competitors in Ahrefs, most shared first."
+ ),
+ "kind": "link_intersect",
+ },
+ "brand_radar_web_pages": {
+ "path": "brand-radar/web-pages",
+ "data_selector": "pages",
+ "primary_keys": ["project_id", "report_id", "url"],
+ "params": {},
+ "body": {
+ "select": ["url", "title", "content", "domain_rating", "referring_domains", "traffic", "traffic_value"],
+ "order_by": "traffic",
+ "limit": MAX_WEB_PAGE_ROWS,
+ },
+ "description": (
+ f"Up to {MAX_WEB_PAGE_ROWS} web pages with the most traffic that mention the brands "
+ "in each Brand Radar report linked to the selected project."
+ ),
+ "kind": "brand_radar",
+ },
+ "domain_rating_top_domains": {
+ "path": "public/domain-rating-top-domains",
+ "data_selector": "domains",
+ "primary_keys": ["domain"],
+ "params": {},
+ "description": "The top 1 million domains ranked by Ahrefs Domain Rating. Free to sync.",
+ "project_scoped": False,
+ "kind": "top_domains",
+ },
}
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
index 5d4bdc25525f..33e41619ce89 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
@@ -112,7 +112,10 @@ class AhrefsSource(SimpleSource[AhrefsSourceConfig]):
f"Each sync imports the latest crawl, with a sample of up to {MAX_PAGE_ROWS} pages. "
"Page data requires verified project ownership. "
"Domain Rating, metrics history, and backlinks report on the Site Audit project's target. "
- f"History tables start {HISTORY_DAYS} days back, and backlinks import up to {MAX_BACKLINK_ROWS} live links."
+ f"History tables start {HISTORY_DAYS} days back, and backlinks import up to {MAX_BACKLINK_ROWS} live links. "
+ "Link intersect tables compare the target with the project's competitors in Ahrefs. "
+ "Brand Radar web pages come from the Brand Radar reports linked to the project. "
+ "The top domains table is free and has 1 million rows."
),
fields=cast(
list[FieldType],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
index bf447da392b6..cb2abbe9d673 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
@@ -305,3 +305,120 @@ def test_unknown_table_fails_before_request() -> None:
result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="123")).run("unknown", [])
assert isinstance(result.raised, UnknownResourceError)
assert result.requests == []
+
+
+ ("table", "selector", "row", "base_select"),
+ [
+ (
+ "link_intersect_refdomains",
+ "referring-domains",
+ {"domain": "a.example", "intersect": 2},
+ ["domain", "domain_rating", "intersect", "links_to_target"],
+ ),
+ (
+ "link_intersect_refpages",
+ "referring-pages",
+ {"url": "https://a.example/post", "intersect": 1},
+ ["url", "title", "domain_rating", "url_rating", "intersect", "links_to_target"],
+ ),
+ ],
+)
[email protected]("has_competitors", [True, False])
+def test_link_intersect_compares_target_with_project_competitors(
+ table: str, selector: str, row: dict[str, object], base_select: list[str], has_competitors: bool
+) -> None:
+ competitors = (
+ [{"url": "rival.example", "mode": "domain"}, {"url": "https://other.example/blog/", "mode": None}]
+ if has_competitors
+ else []
+ )
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="00123")).run(
+ table,
+ [
+ ScriptedResponse(json={"competitors": competitors}),
+ ScriptedResponse(json={"healthscores": [TARGET]}),
+ ScriptedResponse(json={selector: [row]}),
+ ],
+ )
+
+ assert result.raised is None
+ competitors_request = result.requests[0]
+ assert competitors_request.path == "/v3/management/project-competitors"
+ assert competitors_request.query["project_id"] == ("123",)
+ if not has_competitors:
+ assert result.rows == []
+ assert len(result.requests) == 1
+ return
+ competitor_urls = ["rival.example", "https://other.example/blog/"]
+ assert result.rows == [{**row, "project_id": "123", "competitors": competitor_urls}]
+ _, target_request, report_request = result.requests
+ assert target_request.path == "/v3/site-audit/projects"
+ assert report_request.method == "POST"
+ assert report_request.path == f"/v3/{ENDPOINTS[table]['path']}"
+ assert json.loads(report_request.body or b"") == {
+ "output": "json",
+ "select": [*base_select, "links_to_competitor_1", "links_to_competitor_2"],
+ "order_by": ["intersect:desc", "domain_rating:desc"],
+ "limit": 1000,
+ "target": {"url": "https://example.com/", "mode": "domain", "protocol": "https"},
+ "competitors": [
+ {"url": "rival.example", "mode": "domain", "protocol": "both"},
+ {"url": "https://other.example/blog/", "mode": "subdomains", "protocol": "both"},
+ ],
+ }
+
+
+def test_brand_radar_web_pages_read_each_report_linked_to_the_project() -> None:
+ reports = [
+ {"report_id": "r-1", "project_id": 123},
+ {"report_id": "r-other", "project_id": 999},
+ {"report_id": "r-unlinked", "project_id": None},
+ {"report_id": "r-2", "project_id": 123},
+ ]
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="123")).run(
+ "brand_radar_web_pages",
+ [
+ ScriptedResponse(json={"reports": reports}),
+ ScriptedResponse(json={"pages": [{"url": "https://news.example/a"}]}),
+ ScriptedResponse(json={"pages": [{"url": "https://news.example/a"}, {"url": "https://blog.example/b"}]}),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ {"url": "https://news.example/a", "project_id": "123", "report_id": "r-1"},
+ {"url": "https://news.example/a", "project_id": "123", "report_id": "r-2"},
+ {"url": "https://blog.example/b", "project_id": "123", "report_id": "r-2"},
+ ]
+ reports_request, *page_requests = result.requests
+ assert reports_request.path == "/v3/management/brand-radar-reports"
+ assert [request.method for request in page_requests] == ["POST", "POST"]
+ assert [json.loads(request.body or b"")["report_id"] for request in page_requests] == ["r-1", "r-2"]
+
+
+ ("max_rank", "page_sizes", "expected_ranges"),
+ [
+ (5, [2, 2, 1], [("1", "2"), ("3", "4"), ("5", "5")]),
+ (10, [2, 1], [("1", "2"), ("3", "4")]),
+ (10, [2, 0], [("1", "2"), ("3", "4")]),
+ ],
+)
+def test_top_domains_walk_rank_ranges_to_terminal_page(
+ max_rank: int, page_sizes: list[int], expected_ranges: list[tuple[str, str]]
+) -> None:
+ ranks = iter(range(1, 100))
+ pages: list[list[dict[str, object]]] = [
+ [{"domain": f"d{rank}.example", "rank": rank} for rank in [next(ranks) for _ in range(size)]]
+ for size in page_sizes
+ ]
+ with patch(f"{SOURCE_MODULE}.TOP_DOMAINS_PAGE_ROWS", 2), patch(f"{SOURCE_MODULE}.TOP_DOMAINS_COUNT", max_rank):
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="123")).run(
+ "domain_rating_top_domains", [ScriptedResponse(json={"domains": page}) for page in pages]
+ )
+
+ assert result.raised is None
+ assert result.rows == [row for page in pages for row in page]
+ assert [(request.param("from"), request.param("to")) for request in result.requests] == expected_ranges
+ assert all(request.path == "/v3/public/domain-rating-top-domains" for request in result.requests)