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(warehouse_sources): add AdRoll adgroup, segment, report and org tables (#97624)

Tom Owers21271777a27f
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 a4df51dcb5c0..c3be7feb1697 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
@@ -64,16 +64,16 @@ ActiveCampaign adds a collection route.
Note: deal_groups/deal_stages already cover the pipelines and stages lookups. The reference sidebar also exposes campaign messages, campaign link stats, scores, bounce logs, custom object records, conversations, SMS broadcast metrics and the separate e-commerce GraphQL API — all plausible but lower value than the 12 above.
-## AdRoll — **thin**
+## AdRoll — gaps
-Today (3): `ads`, `advertisables`, `campaigns`
+Today (10): `accounts`, `ad_reports`, `adgroups`, `ads`, `advertisable_reports`, `advertisables`, `campaign_reports`, `campaigns`, `organization`, `segments`
Diffed against: <https://apidocs.nextroll.com/crud-api/reference.html>
-- [ ] `adgroups (GET /api/v1/advertisable/get_adgroups, /api/v1/campaign/get_adgroups)` — the missing middle level of the campaign -> adgroup -> ad hierarchy we already half-sync (high)
-- [ ] `report/campaign, report/adgroup, report/ad, report/advertisable` — delivery and attribution metrics - impressions, clicks, spend, conversions; the whole point of an ads connector (high)
-- [ ] `segments (GET /api/v1/advertisable/get_segments, /api/v1/segment/get)` — audience segments targeted by adgroups, with sizes (high)
-- [ ] `organization (GET /api/v1/organization/get, get_advertisables, get_accounts)` — lookup resolving the org/account EIDs that advertisables hang off (medium)
+- [x] `adgroups (GET /api/v1/advertisable/get_adgroups, /api/v1/campaign/get_adgroups)` — the missing middle level of the campaign -> adgroup -> ad hierarchy we already half-sync (high)
+- [x] `report/campaign, report/ad, report/advertisable` — delivery metrics - impressions, clicks, spend; the whole point of an ads connector (high). `report/adgroup` does not exist on the CRUD API.
+- [x] `segments (GET /api/v1/advertisable/get_segments)` — audience segments targeted by adgroups (high). `segment/get` is a single-segment lookup, covered by the list endpoint's `get` representation.
+- [x] `organization (GET /api/v1/organization/get, get_accounts)` — lookup resolving the org/account EIDs that advertisables hang off (medium). `get_advertisables` already backs the `advertisables` table.
- [ ] `pixel (GET /api/v1/advertisable/get_pixel, /api/v1/pixel/get)` — conversion tracking pixel per advertisable (medium)
- [ ] `rules (GET /api/v1/pixel/get_rules, /api/v1/rule/get)` — conversion and retargeting rule definitions that decode segment membership (medium)
- [ ] `invoice (GET /api/v1/invoice/get)` — billed spend reconciliation against reported campaign spend (medium)
@@ -83,7 +83,7 @@ Diffed against: <https://apidocs.nextroll.com/crud-api/reference.html>
- [ ] `contextual_categories` — lookup decoding contextual targeting categories on adgroups (low)
- [ ] `dynamic_template/get_all_for_advertisable` — creative template lookup for dynamic ads (low)
-Note: NextRoll splits reporting into a separate GraphQL Reporting API (https://apidocs.nextroll.com/graphql-reporting-api/index.html) that supersedes the legacy CRUD /api/v1/report/\* endpoints - delivery and attribution metrics by advertisable, campaign, adgroup, ad, plus granular conversions. The developers.nextroll.com URL in the payload is an Angular shell with no content; the real reference is apidocs.nextroll.com.
+Note: NextRoll splits reporting into a separate GraphQL Reporting API (https://apidocs.nextroll.com/graphql-reporting-api/index.html) that supersedes the legacy CRUD /api/v1/report/\* endpoints - delivery and attribution metrics by advertisable, campaign, adgroup, ad, plus granular conversions. The synced report tables use the CRUD API's `entity` data format, the only shape that reference documents: one row per entity with its delivery metrics. Per-day breakdowns and attribution remain a GraphQL Reporting API follow-up. The developers.nextroll.com URL in the payload is an Angular shell with no content; the real reference is apidocs.nextroll.com.
## AgileCRM — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/adroll.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/adroll.py
index 78d103010b38..91a148a137db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/adroll.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/adroll.py
@@ -1,7 +1,8 @@
-import dataclasses
from typing import Any, Optional
from urllib.parse import urlencode
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.adroll.settings import ADROLL_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
@@ -27,10 +28,10 @@ MAX_RETRY_ATTEMPTS = 3
_ADVERTISABLE_PARENT = "advertisable"
+@frozen
class AdRollResumeConfig:
# Framework fan-out checkpoint ({"completed": [...], "current": ..., "child_state": ...}).
- # The plain advertisables list is a single request, so only fan-out endpoints checkpoint.
+ # The unscoped endpoints are one request each, so only fan-out endpoints checkpoint.
fanout_state: Optional[dict[str, Any]] = None
@@ -70,8 +71,8 @@ def adroll_source(
"name": endpoint,
"endpoint": {
"path": config.path,
- "params": {"apikey": client_id},
- "data_selector": "results",
+ "params": {"apikey": client_id, **config.extra_params},
+ "data_selector": config.data_selector,
},
}
],
@@ -97,24 +98,25 @@ def adroll_source(
"endpoint": {
"path": ADROLL_ENDPOINTS["advertisables"].path,
"params": {"apikey": client_id},
- "data_selector": "results",
+ "data_selector": ADROLL_ENDPOINTS["advertisables"].data_selector,
},
},
{
"name": endpoint,
"endpoint": {
- # AdRoll scopes campaign/ad lists with an `advertisable` query param,
- # not a path segment; bind the resolve param inside the query string.
- "path": f"{config.path}?advertisable={{advertisable}}",
+ # AdRoll scopes the per-advertisable lists with a query param, not a path
+ # segment; bind the resolve param inside the query string.
+ "path": f"{config.path}?{config.resolve_param}={{{config.resolve_param}}}",
"params": {
- "advertisable": {
+ config.resolve_param: {
"type": "resolve",
"resource": _ADVERTISABLE_PARENT,
"field": "eid",
},
"apikey": client_id,
+ **config.extra_params,
},
- "data_selector": "results",
+ "data_selector": config.data_selector,
},
"include_from_parent": ["eid"],
},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/canonical_descriptions.py
index 6f7046dab166..e2b43c6a3195 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/canonical_descriptions.py
@@ -1,18 +1,39 @@
"""Canonical, documentation-sourced descriptions for AdRoll (NextRoll) endpoints and columns.
-Sourced from the official NextRoll/AdRoll API reference (https://developers.nextroll.com/).
-Keyed by the endpoint names in `settings.py` `ADROLL_ENDPOINTS`, which match the
-`ExternalDataSchema.name` of a synced AdRoll table. Columns absent here fall back to LLM enrichment.
+Sourced from the official NextRoll/AdRoll CRUD API reference
+(https://apidocs.nextroll.com/crud-api/reference.html). Keyed by the endpoint names in
+`settings.py` `ADROLL_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced AdRoll
+table. Columns absent here fall back to LLM enrichment.
"""
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+_DOCS_URL = "https://apidocs.nextroll.com/crud-api/reference.html"
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organization": {
+ "description": "The AdRoll organization the credentials belong to — the top of the organization, account, advertisable hierarchy.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "Unique encoded identifier (EID) for the organization.",
+ "name": "Display name of the organization.",
+ "created_date": "Date the organization was created.",
+ },
+ },
+ "accounts": {
+ "description": "An account under your AdRoll organization, grouping the advertisables that are billed together.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "Unique encoded identifier (EID) for the account.",
+ "name": "Display name of the account.",
+ "status": "Current status of the account.",
+ },
+ },
"advertisables": {
"description": "An advertisable entity (a brand or product) under your AdRoll organization that campaigns run against.",
- "docs_url": "https://developers.nextroll.com/api-reference/index.html",
+ "docs_url": _DOCS_URL,
"columns": {
"eid": "Unique encoded identifier (EID) for the advertisable.",
"name": "Display name of the advertisable.",
@@ -26,7 +47,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"campaigns": {
"description": "An advertising campaign belonging to an advertisable, grouping ads toward a goal and budget.",
- "docs_url": "https://developers.nextroll.com/api-reference/index.html",
+ "docs_url": _DOCS_URL,
"columns": {
"eid": "Unique encoded identifier (EID) for the campaign.",
"_advertisable_eid": "EID of the parent advertisable the campaign belongs to (added during sync).",
@@ -41,9 +62,29 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"type": "Type of the campaign (e.g. retargeting, prospecting).",
},
},
+ "adgroups": {
+ "description": "An ad group within a campaign, pairing a set of ads with the segments and placements they target.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "Unique encoded identifier (EID) for the ad group.",
+ "_advertisable_eid": "EID of the parent advertisable the ad group belongs to (added during sync).",
+ "name": "Display name of the ad group.",
+ "campaign": "EID of the campaign the ad group belongs to.",
+ "status": "Current status of the ad group.",
+ "created_date": "Date the ad group was created.",
+ "updated_date": "Date the ad group was last updated.",
+ "ad_optimization": "Strategy used to pick between ads that fit a single ad space.",
+ "ads": "Ads attached to the ad group, each with the ad's EID (`id`) and its status in this ad group.",
+ "segments": "Segments targeted by the ad group, each with the segment's EID (`id`) and an `is_negative` flag marking exclusions.",
+ "site_exclusions": "Domains excluded from the ad group, with ad format information where set.",
+ "placement_targets": "Placements the ad group targets (all, newsfeed, or rightcolumn).",
+ "flight_timezone": "Time zone applied to all flights of the ad group.",
+ "allowed_targeting": "Targeting classification allowed by the campaign's objective.",
+ },
+ },
"ads": {
"description": "An individual ad creative belonging to an advertisable, served within campaigns.",
- "docs_url": "https://developers.nextroll.com/api-reference/index.html",
+ "docs_url": _DOCS_URL,
"columns": {
"eid": "Unique encoded identifier (EID) for the ad.",
"_advertisable_eid": "EID of the parent advertisable the ad belongs to (added during sync).",
@@ -58,4 +99,83 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"clickthrough_url": "Destination URL the ad links to when clicked.",
},
},
+ "segments": {
+ "description": "An audience segment on an advertisable's active pixel, used to target or exclude visitors in ad groups.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "Unique encoded identifier (EID) for the segment.",
+ "_advertisable_eid": "EID of the parent advertisable the segment belongs to (added during sync).",
+ "name": "Name of the segment, used internally and for JavaScript segment matching.",
+ "display_name": "Name of the segment shown in the AdRoll UI.",
+ "type": "Type of the segment, one of s (segment), u (single product), c (conversion), p (low-intent), b (shopping cart), e (email), g (prospecting), x (external), l (product list), q (coop).",
+ "match_method": "Match method used to decide segment membership.",
+ "pattern": "URL pattern used to match visitors into the segment.",
+ "threshold": "Threshold applied by match methods that take a numerical limit.",
+ "duration": "How long a visitor stays in the segment, in days.",
+ "conversion_value": "Value of a conversion from this segment, in USD.",
+ "group": "Group the segment belongs to.",
+ "product": "Product the segment belongs to.",
+ "mobile": "Mobile extension data for the segment.",
+ },
+ },
+ "advertisable_reports": {
+ "description": "Lifetime delivery metrics per advertisable, as returned by the CRUD reporting API in its entity format.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "EID of the advertisable the metrics belong to.",
+ "_advertisable_eid": "EID of the advertisable the report was requested for (added during sync).",
+ "advertisable": "Display name of the advertisable.",
+ "status": "Status of the advertisable at the time of the report.",
+ "created_date": "Date the advertisable was created.",
+ "impressions": "Number of times the advertisable's ads were shown.",
+ "clicks": "Number of clicks on the advertisable's ads.",
+ "cost": "Amount spent, in the report's currency.",
+ "cpc": "Average cost per click.",
+ "cpm": "Average cost per thousand impressions.",
+ "ctr": "Click-through rate, as clicks divided by impressions.",
+ "prospects": "Number of prospects reached.",
+ },
+ },
+ "campaign_reports": {
+ "description": "Lifetime delivery metrics per campaign, as returned by the CRUD reporting API in its entity format. Prospecting and new-style Facebook campaigns are not covered by this endpoint.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "EID of the campaign the metrics belong to.",
+ "_advertisable_eid": "EID of the advertisable the report was requested for (added during sync).",
+ "campaign": "Display name of the campaign.",
+ "advertiser": "Display name of the advertisable the campaign belongs to.",
+ "type": "Type of the campaign (e.g. Retargeting).",
+ "status": "Status of the campaign at the time of the report.",
+ "created_date": "Date the campaign was created.",
+ "start_date": "Date the campaign starts running.",
+ "end_date": "Date the campaign stops running.",
+ "budget": "Budget allocated to the campaign.",
+ "impressions": "Number of times the campaign's ads were shown.",
+ "clicks": "Number of clicks on the campaign's ads.",
+ "cost": "Amount spent, in the report's currency.",
+ "cpc": "Average cost per click.",
+ "cpm": "Average cost per thousand impressions.",
+ "ctr": "Click-through rate, as clicks divided by impressions.",
+ "prospects": "Number of prospects reached.",
+ },
+ },
+ "ad_reports": {
+ "description": "Lifetime delivery metrics per ad, as returned by the CRUD reporting API in its entity format.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "eid": "EID of the ad the metrics belong to.",
+ "_advertisable_eid": "EID of the advertisable the report was requested for (added during sync).",
+ "ad": "Display name of the ad.",
+ "ad_size": "Size of the ad creative, as width by height in pixels.",
+ "status": "Status of the ad at the time of the report.",
+ "created_date": "Date the ad was created.",
+ "impressions": "Number of times the ad was shown.",
+ "clicks": "Number of clicks on the ad.",
+ "cost": "Amount spent, in the report's currency.",
+ "cpc": "Average cost per click.",
+ "cpm": "Average cost per thousand impressions.",
+ "ctr": "Click-through rate, as clicks divided by impressions.",
+ "prospects": "Number of prospects reached.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/settings.py
index b6a762c4539d..e1274de39036 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/settings.py
@@ -1,10 +1,12 @@
-from dataclasses import dataclass
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+@frozen
class AdRollEndpointConfig:
name: str
# Path under https://services.adroll.com.
@@ -13,17 +15,33 @@ class AdRollEndpointConfig:
# Fan-out parent (campaigns/ads are fetched per advertisable EID).
advertisable_scoped: bool = False
parent_key: Optional[str] = None
+ # Query param the parent advertisable EID binds to. The reporting endpoints filter on a list
+ # of advertisables (`advertisables`); the entity endpoints scope to one (`advertisable`).
+ resolve_param: str = "advertisable"
+ # Static query params the endpoint requires beyond `apikey`.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # `organization/get` returns the object itself; every other endpoint wraps rows in `results`.
+ data_selector: str = "results"
def __post_init__(self) -> None:
if self.advertisable_scoped and self.parent_key is None:
raise ValueError(f"advertisable_scoped endpoint '{self.name}' must define parent_key")
-# AdRoll's default quota is only 100 API requests per day, so v1 ships the
-# small entity hierarchy (1 + 2×advertisables requests per sync). Entity
-# endpoints have no updated_at filter — full refresh. Performance metrics are
-# GraphQL-only (POST /reporting/api/v1/query) and a follow-up.
+# AdRoll's default quota is only 100 API requests per day, so every endpoint is either a single
+# request or one request per advertisable. Adgroups come from `advertisable/get_adgroups` rather
+# than `campaign/get_adgroups` for that reason — the latter costs a request per campaign.
+# No endpoint accepts an updated_at filter, so every endpoint is full refresh.
ADROLL_ENDPOINTS: dict[str, AdRollEndpointConfig] = {
+ "organization": AdRollEndpointConfig(
+ name="organization",
+ path="/api/v1/organization/get",
+ data_selector="$",
+ ),
+ "accounts": AdRollEndpointConfig(
+ name="accounts",
+ path="/api/v1/organization/get_accounts",
+ ),
"advertisables": AdRollEndpointConfig(
name="advertisables",
path="/api/v1/organization/get_advertisables",
@@ -34,15 +52,57 @@ ADROLL_ENDPOINTS: dict[str, AdRollEndpointConfig] = {
advertisable_scoped=True,
parent_key="_advertisable_eid",
),
+ # Returns adgroups of active campaigns whose status is one of AdRoll's documented defaults
+ # (approved, admin_review, paused, admin_paused) — the endpoint offers no way to ask for all.
+ "adgroups": AdRollEndpointConfig(
+ name="adgroups",
+ path="/api/v1/advertisable/get_adgroups",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ ),
"ads": AdRollEndpointConfig(
name="ads",
path="/api/v1/ad/get_all",
advertisable_scoped=True,
parent_key="_advertisable_eid",
),
+ # Segments of the advertisable's active pixel. Omitting `per_page` opts out of pagination,
+ # so the response carries every segment.
+ "segments": AdRollEndpointConfig(
+ name="segments",
+ path="/api/v1/advertisable/get_segments",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ ),
+ # `data_format=entity` is the only response shape the CRUD API documents: one row per entity
+ # carrying its delivery metrics. Per-day breakdowns need the GraphQL Reporting API.
+ "advertisable_reports": AdRollEndpointConfig(
+ name="advertisable_reports",
+ path="/api/v1/report/advertisable",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ resolve_param="advertisables",
+ extra_params={"data_format": "entity"},
+ ),
+ "campaign_reports": AdRollEndpointConfig(
+ name="campaign_reports",
+ path="/api/v1/report/campaign",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ resolve_param="advertisables",
+ extra_params={"data_format": "entity"},
+ ),
+ "ad_reports": AdRollEndpointConfig(
+ name="ad_reports",
+ path="/api/v1/report/ad",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ resolve_param="advertisables",
+ extra_params={"data_format": "entity"},
+ ),
}
ENDPOINTS = tuple(ADROLL_ENDPOINTS.keys())
-# Entity endpoints have no updated_at filter — every endpoint is full refresh.
+# No AdRoll endpoint accepts an updated_at filter — every endpoint is full refresh.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ADROLL_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/source.py
index 225a8a76679a..4a6cd8730d84 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/source.py
@@ -58,7 +58,7 @@ class AdRollSource(ResumableSource[AdRollSourceConfig, AdRollResumeConfig]):
category=DataWarehouseSourceCategory.ADVERTISING,
keywords=["nextroll"],
label="AdRoll",
- caption="""Enter your AdRoll (NextRoll) API credentials to pull your advertising entity data into the PostHog Data warehouse.
+ caption="""Enter your AdRoll (NextRoll) API credentials to pull your advertising entities and delivery metrics into the PostHog Data warehouse.
Create a personal access token and an app in the [NextRoll developer console](https://developers.nextroll.com/) — the app's Client ID is sent as the `apikey` on every request. Note that NextRoll's default quota is 100 API requests per day; contact NextRoll support to raise it for larger accounts.""",
iconPath="/static/services/adroll.png",
@@ -103,8 +103,7 @@ Create a personal access token and an app in the [NextRoll developer console](ht
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Entity endpoints have no updated_at filter — full refresh. Metrics
- # are GraphQL-only and a follow-up.
+ # No endpoint accepts an updated_at filter — full refresh.
return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
def validate_credentials(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
index 004d950b0f8b..47f76fc3d091 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
@@ -39,6 +39,14 @@ def _response(results: list[dict[str, Any]] | None, *, drop_results: bool = Fals
return resp
+def _object_response(body: dict[str, Any]) -> Response:
+ """A bare object body — `organization/get` returns the row itself, not a `results` list."""
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _error_response(status_code: int) -> Response:
resp = Response()
resp.status_code = status_code
@@ -144,8 +152,9 @@ class TestRows:
auth(prepared)
assert prepared.headers["Authorization"] == "Token pat"
+ @pytest.mark.parametrize("endpoint", ["campaigns", "ads", "adgroups", "segments"])
@mock.patch(CLIENT_SESSION_PATCH)
- def test_campaigns_fan_out_over_advertisables(self, MockSession):
+ def test_scoped_endpoints_fan_out_over_advertisables(self, MockSession, endpoint):
session = MockSession.return_value
snapshots = _wire(
session,
@@ -156,16 +165,46 @@ class TestRows:
],
)
- rows = _rows(_source("campaigns"))
+ rows = _rows(_source(endpoint))
assert [(c["eid"], c["_advertisable_eid"]) for c in rows] == [("C1", "ADV1"), ("C2", "ADV2")]
child_queries = [parse_qs(urlparse(s["url"]).query) for s in snapshots[1:]]
assert child_queries[0]["advertisable"] == ["ADV1"]
assert child_queries[1]["advertisable"] == ["ADV2"]
- assert all(urlparse(s["url"]).path == CAMPAIGNS_PATH for s in snapshots[1:])
+ assert all(urlparse(s["url"]).path == ADROLL_ENDPOINTS[endpoint].path for s in snapshots[1:])
# The apikey param rides along on every request, parent and children alike.
assert all(s["params"]["apikey"] == "cid" for s in snapshots)
+ @pytest.mark.parametrize("endpoint", ["advertisable_reports", "campaign_reports", "ad_reports"])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_report_endpoints_filter_by_advertisables_in_entity_format(self, MockSession, endpoint):
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"eid": "ADV1"}]),
+ _response([{"eid": "C1", "impressions": 5}]),
+ ],
+ )
+
+ rows = _rows(_source(endpoint))
+
+ assert rows == [{"eid": "C1", "impressions": 5, "_advertisable_eid": "ADV1"}]
+ assert urlparse(snapshots[1]["url"]).path == ADROLL_ENDPOINTS[endpoint].path
+ # The reporting endpoints take a list of advertisables, not a single one.
+ assert parse_qs(urlparse(snapshots[1]["url"]).query)["advertisables"] == ["ADV1"]
+ assert snapshots[1]["params"]["data_format"] == "entity"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_organization_yields_the_bare_response_object(self, MockSession):
+ session = MockSession.return_value
+ snapshots = _wire(session, [_object_response({"eid": "ORG1", "name": "Acme"})])
+
+ rows = _rows(_source("organization"))
+
+ assert rows == [{"eid": "ORG1", "name": "Acme"}]
+ assert urlparse(snapshots[0]["url"]).path == "/api/v1/organization/get"
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_advertisables_without_eid_are_skipped(self, MockSession):
session = MockSession.return_value