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 genesys cloud teams, groups, contacts, status tables (#122038)

Tom Owersb1b06b84d622
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 e68085aeffea..08506093820c 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
@@ -5188,11 +5188,11 @@ Diffed against: <https://api.mypurecloud.com/api/v2/docs/swagger>
- [x] `Get list of wrapup codes (GET /api/v2/routing/wrapupcodes)` — resolve wrapUpCode values into conversation outcome labels (high)
- [x] `Get the list of routing skills (GET /api/v2/routing/skills)` — resolve requestedRoutingSkillIds and activeSkillIds on conversation sessions (high)
- [x] `Retrieve all divisions (GET /api/v2/authorization/divisions)` — resolve divisionIds on conversations and group performance by business unit (high)
-- [ ] `Get Team listing (GET /api/v2/teams)` — resolve participant teamId values for agent team reporting (high)
-- [ ] `Get a group list (GET /api/v2/groups)` — resolve groupId and agentGroups references in conversation routing data (high)
-- [ ] `Get external contacts (GET /api/v2/externalcontacts/contacts)` — resolve externalContactId on participants into customer identities (high)
+- [x] `Get Team listing (GET /api/v2/teams)` — resolve participant teamId values for agent team reporting (high)
+- [x] `Get a group list (GET /api/v2/groups)` — resolve groupId and agentGroups references in conversation routing data (high)
+- [x] `Get external contacts (GET /api/v2/externalcontacts/contacts)` — resolve externalContactId on participants into customer identities (high)
- [x] `Get external organizations (GET /api/v2/externalcontacts/organizations)` — resolve externalOrganizationId on participants into customer organizations (high)
-- [ ] `Query for user details (POST /api/v2/analytics/users/details/query)` — measure agent presence and routing-state history, including time available and offline (high)
+- [x] `Query for user details (POST /api/v2/analytics/users/details/query)` — measure agent presence and routing-state history, including time available and offline (high)
- [ ] `Queries Evaluations (GET /api/v2/quality/evaluations/query)` — analyze detailed quality evaluations beyond evaluation summaries embedded in conversations (medium)
- [ ] `Get the members of this queue (GET /api/v2/routing/queues/{queueId}/members)` — connect agents to queues and report queue staffing and membership (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.py
index 4c56ccbd0b1a..5a99895fe954 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/canonical_descriptions.py
@@ -141,4 +141,70 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"externalIds": "Identifiers for this external organization in external systems.",
},
},
+ "external_contacts": {
+ "description": "External contacts (customer identities) stored in Genesys Cloud external contacts.",
+ "docs_url": "https://developer.genesys.cloud/commdigital/externalcontacts/",
+ "columns": {
+ "id": "The globally unique identifier for the external contact. Matches externalContactId on participants.",
+ "division": "The division to which this external contact belongs.",
+ "firstName": "The first name of the contact.",
+ "middleName": "The middle name of the contact.",
+ "lastName": "The last name of the contact.",
+ "title": "The title of the contact.",
+ "workEmail": "The work email of the contact.",
+ "personalEmail": "The personal email of the contact.",
+ "workPhone": "The work phone number of the contact.",
+ "cellPhone": "The cell phone number of the contact.",
+ "externalOrganization": "The external organization this contact belongs to.",
+ "externalIds": "Identifiers for this contact in external systems.",
+ "customFields": "Custom fields defined in the schema attached to this external contact.",
+ "type": "The type of contact.",
+ "createDate": "Date the external contact was created.",
+ "modifyDate": "Date the external contact was last modified.",
+ },
+ },
+ "teams": {
+ "description": "Teams of users in the Genesys Cloud organization.",
+ "docs_url": "https://developer.genesys.cloud/useragentman/groups/",
+ "columns": {
+ "id": "The globally unique identifier for the team. Matches teamId on conversation participants.",
+ "name": "The team name.",
+ "division": "The division to which this team belongs.",
+ "description": "Team information.",
+ "dateCreated": "Date the team was created.",
+ "dateModified": "Date the team was last modified.",
+ "memberCount": "Number of members in the team.",
+ },
+ },
+ "groups": {
+ "description": "Groups of users in the Genesys Cloud organization.",
+ "docs_url": "https://developer.genesys.cloud/useragentman/groups/",
+ "columns": {
+ "id": "The globally unique identifier for the group. Matches groupId and agentGroups on conversation data.",
+ "name": "The group name.",
+ "description": "The group description.",
+ "dateModified": "Date the group was last modified.",
+ "memberCount": "Number of members.",
+ "state": "Active, inactive, or deleted state.",
+ "type": "Type of group.",
+ "visibility": "Who can view this group.",
+ "rolesEnabled": "Whether roles can be assigned to this group.",
+ "callsEnabled": "Whether calls can be placed to this group.",
+ "email": "Email address for the group.",
+ "owners": "Owners of the group.",
+ },
+ },
+ "user_status_history": {
+ "description": "Presence and ACD routing status history for users, one row per status record, from the user details query.",
+ "docs_url": "https://developer.genesys.cloud/analyticsdatamanagement/analytics/detail/user-query",
+ "columns": {
+ "userId": "The identifier for the user. Matches id on users.",
+ "recordType": "presence for a primary presence record, routing_status for an ACD routing status record.",
+ "startTime": "The start time of the record.",
+ "endTime": "The end time of the record. Empty while the record is still open.",
+ "systemPresence": "The user's system presence, for presence records.",
+ "organizationPresenceId": "The identifier for the user's organization presence, for presence records.",
+ "routingStatus": "The user's ACD routing status, for routing status records.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.py
index 21e422cda48a..fa5801d1fbbd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/genesys_cloud.py
@@ -1,6 +1,7 @@
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
import requests
import structlog
@@ -16,7 +17,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.genesys_cloud.settings import (
ANALYTICS_PAGE_SIZE,
- CONVERSATION_DETAILS_PATH,
GENESYS_CLOUD_ENDPOINTS,
LISTING_PAGE_SIZE,
REGIONS,
@@ -123,6 +123,54 @@ def _to_rows(conversations: list[dict[str, Any]], flatten_participants: bool) ->
return rows
+def _status_rows(
+ user_detail: dict[str, Any], start: datetime, end: datetime, include_earlier: bool
+) -> list[dict[str, Any]]:
+ user_id = user_detail.get("userId")
+ rows: list[dict[str, Any]] = []
+ for record_type, key in (("presence", "primaryPresence"), ("routing_status", "routingStatus")):
+ for record in user_detail.get(key) or []:
+ raw = record.get("startTime")
+ if not raw:
+ continue
+ record_start = _to_utc(raw)
+ # A record overlaps every window it spans, so emit it once per run: in the window it starts in, or in
+ # the first window when it started earlier. The first window refreshes the end time of long records.
+ if record_start >= end or (record_start < start and not include_earlier):
+ continue
+ rows.append({**record, "userId": user_id, "recordType": record_type})
+ return rows
+
+
+def _query_user_window(
+ session: requests.Session,
+ url: str,
+ start: datetime,
+ end: datetime,
+ include_earlier: bool,
+) -> Iterator[tuple[list[dict[str, Any]], Optional[datetime]]]:
+ """Yield `(rows, window_end)` per page. `window_end` is set on the last page of a window."""
+ page_number = 1
+ while True:
+ body = {
+ "interval": _interval(start, end),
+ "order": "asc",
+ "paging": {"pageSize": ANALYTICS_PAGE_SIZE, "pageNumber": page_number},
+ }
+ response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ data = response.json() or {}
+ total_hits = int(data.get("totalHits") or 0)
+ user_details = data.get("userDetails") or []
+ rows = [row for detail in user_details for row in _status_rows(detail, start, end, include_earlier)]
+ # Genesys Cloud can return short pages before the last one, so only totalHits ends the window.
+ is_last_page = not user_details or page_number * ANALYTICS_PAGE_SIZE >= total_hits
+ yield rows, (end if is_last_page else None)
+ if is_last_page:
+ return
+ page_number += 1
+
+
def _query_window(
session: requests.Session,
url: str,
@@ -183,11 +231,18 @@ def _iter_analytics_rows(
else:
start = now - INITIAL_HISTORY
- url = f"{base_url}{CONVERSATION_DETAILS_PATH}"
+ url = f"{base_url}{config.path}"
+ # A resumed run already emitted the records that started before its checkpoint.
+ first_window = resume is None or not resume.window_start
while start < now:
window_end = min(start + ANALYTICS_WINDOW, now)
- for conversations, finished_window_end in _query_window(session, url, config, start, window_end):
- rows = _to_rows(conversations, config.flatten_participants)
+ pages = (
+ _query_user_window(session, url, start, window_end, include_earlier=first_window)
+ if config.kind == "user_analytics"
+ else _query_window(session, url, config, start, window_end)
+ )
+ for records, finished_window_end in pages:
+ rows = _to_rows(records, config.flatten_participants)
if finished_window_end is not None:
# Stage the cursor before the yield that covers it, so a resume starts after this window.
resumable_source_manager.save_state(
@@ -198,6 +253,7 @@ def _iter_analytics_rows(
if rows:
yield rows
start = window_end
+ first_window = False
# A later sync must derive a fresh start from its watermark instead of reusing this run's cursor.
resumable_source_manager.clear_state()
@@ -235,6 +291,18 @@ def _iter_listing_rows(
page_number += 1
+def _next_cursor(data: dict[str, Any], cursor_param: str) -> Optional[str]:
+ cursor = (data.get("cursors") or {}).get("after")
+ if cursor:
+ return cursor
+ # The teams listing returns its next cursor only inside nextUri.
+ next_uri = data.get("nextUri")
+ if not next_uri:
+ return None
+ values = parse_qs(urlparse(next_uri).query).get(cursor_param)
+ return values[0] if values else None
+
+
def _iter_scan_rows(
session: requests.Session,
base_url: str,
@@ -247,9 +315,9 @@ def _iter_scan_rows(
url = f"{base_url}{config.path}"
while True:
- params: dict[str, Any] = {**config.params, "limit": LISTING_PAGE_SIZE}
+ params: dict[str, Any] = {**config.params, config.page_size_param: LISTING_PAGE_SIZE}
if cursor:
- params["cursor"] = cursor
+ params[config.cursor_param] = cursor
response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
if sends_resumed_cursor and response.status_code in (400, 422):
# The saved cursor expired. Restarting here would append rows this run already loaded, so drop the
@@ -259,7 +327,7 @@ def _iter_scan_rows(
response.raise_for_status()
data = response.json() or {}
entities = data.get("entities") or []
- next_cursor = (data.get("cursors") or {}).get("after")
+ next_cursor = _next_cursor(data, config.cursor_param)
has_next_page = bool(entities) and bool(next_cursor)
if has_next_page:
resumable_source_manager.save_state(GenesysCloudResumeConfig(cursor=next_cursor))
@@ -284,7 +352,7 @@ def genesys_cloud_source(
def items() -> Iterator[list[dict[str, Any]]]:
session = _make_session(region, client_id, client_secret)
- if config.kind == "analytics":
+ if config.kind in ("analytics", "user_analytics"):
yield from _iter_analytics_rows(
session, base_url, config, resumable_source_manager, db_incremental_field_last_value
)
@@ -300,7 +368,8 @@ def genesys_cloud_source(
partition_mode="datetime" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
partition_format="month" if config.partition_key else None,
- sort_mode="asc",
+ # User status records arrive grouped by user, not ordered by startTime.
+ sort_mode=None if config.kind == "user_analytics" else "asc",
)
@@ -316,10 +385,10 @@ def validate_credentials(
try:
if config is None:
response = session.get(f"{base_url}/api/v2/organizations/me", timeout=VALIDATION_TIMEOUT_SECONDS)
- elif config.kind == "analytics":
+ elif config.kind in ("analytics", "user_analytics"):
now = datetime.now(UTC)
response = session.post(
- f"{base_url}{CONVERSATION_DETAILS_PATH}",
+ f"{base_url}{config.path}",
json={"interval": _interval(now - timedelta(hours=1), now), "paging": {"pageSize": 1, "pageNumber": 1}},
timeout=VALIDATION_TIMEOUT_SECONDS,
)
@@ -327,7 +396,7 @@ def validate_credentials(
response = session.get(
f"{base_url}{config.path}",
# The scan listings reject a limit below 10.
- params={"limit": 10} if config.kind == "scan" else {"pageSize": 1, "pageNumber": 1},
+ params={config.page_size_param: 10} if config.kind == "scan" else {"pageSize": 1, "pageNumber": 1},
timeout=VALIDATION_TIMEOUT_SECONDS,
)
except OAuth2AuthRequestError as e:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.py
index d127a061cf93..921518921e07 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/settings.py
@@ -26,6 +26,7 @@ REGIONS: dict[str, str] = {
DEFAULT_REGION = "mypurecloud.com"
CONVERSATION_DETAILS_PATH = "/api/v2/analytics/conversations/details/query"
+USER_DETAILS_PATH = "/api/v2/analytics/users/details/query"
# The details query caps pageSize at 100.
ANALYTICS_PAGE_SIZE = 100
@@ -40,15 +41,25 @@ _CONVERSATION_START_INCREMENTAL_FIELDS: list[IncrementalField] = [
},
]
+_STATUS_START_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "startTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "startTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
@dataclass(frozen=True)
class GenesysCloudEndpointConfig:
name: str
primary_keys: list[str]
# "analytics" endpoints read the conversation details query in time windows;
+ # "user_analytics" endpoints read the user details query in time windows;
# "listing" endpoints page through a plain GET entity listing by page number;
# "scan" endpoints page through a GET listing by cursor.
- kind: Literal["analytics", "listing", "scan"]
+ kind: Literal["analytics", "user_analytics", "listing", "scan"]
path: str
# Permission a Genesys Cloud role must grant for the OAuth client to read this endpoint.
permission: str | None = None
@@ -57,6 +68,9 @@ class GenesysCloudEndpointConfig:
query_body: dict[str, Any] = field(default_factory=dict)
# Emit one row per participant instead of one row per conversation.
flatten_participants: bool = False
+ # Scan endpoints: query params that carry the page size and the cursor.
+ page_size_param: str = "limit"
+ cursor_param: str = "cursor"
partition_key: str | None = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
@@ -147,6 +161,40 @@ GENESYS_CLOUD_ENDPOINTS: dict[str, GenesysCloudEndpointConfig] = {
path="/api/v2/externalcontacts/scan/organizations",
permission="externalContacts:externalOrganization:view",
),
+ # Like organizations, the plain /externalcontacts/contacts listing stops at the first 1,000 records.
+ "external_contacts": GenesysCloudEndpointConfig(
+ name="external_contacts",
+ primary_keys=["id"],
+ kind="scan",
+ path="/api/v2/externalcontacts/scan/contacts",
+ permission="externalContacts:contact:view",
+ ),
+ "teams": GenesysCloudEndpointConfig(
+ name="teams",
+ primary_keys=["id"],
+ kind="scan",
+ path="/api/v2/teams",
+ permission="groups:team:view",
+ page_size_param="pageSize",
+ cursor_param="after",
+ ),
+ "groups": GenesysCloudEndpointConfig(
+ name="groups",
+ primary_keys=["id"],
+ kind="listing",
+ path="/api/v2/groups",
+ params={"sortOrder": "ascending"},
+ ),
+ # One row per presence or routing status record, so a user's history is queryable without unnesting.
+ "user_status_history": GenesysCloudEndpointConfig(
+ name="user_status_history",
+ primary_keys=["userId", "recordType", "startTime"],
+ kind="user_analytics",
+ path=USER_DETAILS_PATH,
+ permission="analytics:userDetail:view",
+ partition_key="startTime",
+ incremental_fields=list(_STATUS_START_INCREMENTAL_FIELDS),
+ ),
}
ENDPOINTS = tuple(GENESYS_CLOUD_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py
index 233c7ccb6b37..bb4383646716 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/source.py
@@ -98,14 +98,17 @@ class GenesysCloudSource(ResumableSource[GenesysCloudSourceConfig, GenesysCloudR
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
keywords=["genesys", "purecloud", "contact center"],
label="Genesys Cloud",
- caption="""Connect your Genesys Cloud organization to import calls, conversations, participants, users, queues, wrap-up codes, skills, divisions, and external organizations.
+ caption="""Connect your Genesys Cloud organization to import calls, conversations, participants, users, user status history, queues, wrap-up codes, skills, divisions, teams, groups, external contacts, and external organizations.
In Genesys Cloud, go to **Admin > Integrations > OAuth** and add a client with the **Client Credentials** grant type. Assign it a role with these permissions:
- `analytics:conversationDetail:view` for calls, conversations, and participants
+- `analytics:userDetail:view` for user status history
- `routing:queue:view` for queues
- `routing:wrapupCode:view` for wrap-up codes
- `routing:skill:view` for skills
+- `groups:team:view` for teams
+- `externalContacts:contact:view` for external contacts
- `externalContacts:externalOrganization:view` for external organizations
Then select the region your organization is hosted in.""",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud.py
index 2891b2e45bcf..a8804a164989 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/genesys_cloud/tests/test_genesys_cloud.py
@@ -165,6 +165,62 @@ class TestAnalyticsEndpoints:
]
assert all(row["conversationStart"] == "2026-03-10T11:00:00.000Z" for row in result.rows)
+ @pytest.mark.parametrize("resumed", [False, True])
+ def test_user_status_records_are_emitted_once_per_run(self, resumed):
+ watermark = NOW - timedelta(hours=1)
+ start = watermark - genesys_cloud.INCREMENTAL_LOOKBACK
+ second_window = start + genesys_cloud.ANALYTICS_WINDOW
+
+ def record(at: datetime, **fields: Any) -> dict[str, Any]:
+ return {"startTime": at.strftime("%Y-%m-%dT%H:%M:%S.000Z"), **fields}
+
+ def page(total_hits: int, *details: dict[str, Any]) -> ScriptedResponse:
+ return ScriptedResponse(json={"totalHits": total_hits, "userDetails": list(details)})
+
+ spans_windows = record(second_window - timedelta(hours=1), routingStatus="IDLE")
+ first_window_users = {
+ "userId": "u1",
+ "primaryPresence": [
+ record(start - timedelta(days=3), systemPresence="OFFLINE"),
+ record(start + timedelta(hours=1), systemPresence="AVAILABLE"),
+ ],
+ "routingStatus": [spans_windows, record(second_window + timedelta(hours=1), routingStatus="IDLE")],
+ }
+ second_window_users = {
+ "userId": "u1",
+ "primaryPresence": [record(second_window + timedelta(hours=2), systemPresence="BUSY")],
+ "routingStatus": [spans_windows, {"routingStatus": "OFF_QUEUE"}],
+ }
+
+ result = _driver().run(
+ "user_status_history",
+ [
+ TOKEN,
+ page(101, first_window_users),
+ page(
+ 101, {"userId": "u2", "routingStatus": [record(start + timedelta(hours=2), routingStatus="IDLE")]}
+ ),
+ page(1, second_window_users),
+ page(0),
+ ],
+ resume_state=GenesysCloudResumeConfig(window_start=start.isoformat()) if resumed else None,
+ incremental_field="startTime",
+ db_incremental_field_last_value=watermark,
+ )
+
+ assert result.raised is None
+ assert result.response is not None and result.response.sort_mode is None
+ assert [request.path for request in result.requests[1:]] == ["/api/v2/analytics/users/details/query"] * 4
+ assert [request.json()["paging"]["pageNumber"] for request in result.requests[1:]] == [1, 2, 1, 1]
+ carried_over = [] if resumed else [("u1", "presence", "2026-03-05T11:00:00.000Z")]
+ assert [(row["userId"], row["recordType"], row["startTime"]) for row in result.rows] == [
+ *carried_over,
+ ("u1", "presence", "2026-03-08T12:00:00.000Z"),
+ ("u1", "routing_status", "2026-03-09T10:00:00.000Z"),
+ ("u2", "routing_status", "2026-03-08T13:00:00.000Z"),
+ ("u1", "presence", "2026-03-09T13:00:00.000Z"),
+ ]
+
class TestListingEndpoints:
@pytest.mark.parametrize(
@@ -194,27 +250,34 @@ class TestListingEndpoints:
assert result.final_state is None
@pytest.mark.parametrize(
- "resume,expected_cursors",
+ "endpoint,cursor_param,first_page,resume,expected_cursors",
[
- (None, [None, "after-1"]),
- (GenesysCloudResumeConfig(cursor="after-1"), ["after-1"]),
+ ("external_organizations", "cursor", {"cursors": {"after": "after-1"}}, None, [None, "after-1"]),
+ (
+ "external_organizations",
+ "cursor",
+ {"cursors": {"after": "after-1"}},
+ GenesysCloudResumeConfig(cursor="after-1"),
+ ["after-1"],
+ ),
+ ("teams", "after", {"nextUri": "/api/v2/teams?pageSize=100&after=after-1"}, None, [None, "after-1"]),
],
)
- def test_scan_pages_until_cursor_runs_out(self, resume, expected_cursors):
+ def test_scan_pages_until_cursor_runs_out(self, endpoint, cursor_param, first_page, resume, expected_cursors):
pages = {
- None: ScriptedResponse(json={"entities": [{"id": "o1"}], "cursors": {"after": "after-1"}}),
+ None: ScriptedResponse(json={"entities": [{"id": "o1"}], **first_page}),
"after-1": ScriptedResponse(json={"entities": [{"id": "o2"}], "cursors": {}}),
}
def respond(request: RecordedRequest) -> ScriptedResponse:
if request.path == "/oauth/token":
return TOKEN
- return pages[request.param("cursor")]
+ return pages[request.param(cursor_param)]
- result = _driver().run("external_organizations", respond, resume_state=resume)
+ result = _driver().run(endpoint, respond, resume_state=resume)
assert result.raised is None
- assert result.params("cursor")[1:] == expected_cursors
+ assert result.params(cursor_param)[1:] == expected_cursors
assert [row["id"] for row in result.rows] == ["o1", "o2"][-len(expected_cursors) :]
assert result.saved_states == ([GenesysCloudResumeConfig(cursor="after-1")] if resume is None else [])
assert result.final_state is None
@@ -237,6 +300,12 @@ class TestValidateCredentials:
[
(None, 200, True, None),
("external_organizations", 200, True, None),
+ (
+ "user_status_history",
+ 403,
+ False,
+ "The OAuth client's role is missing the `analytics:userDetail:view` permission, which the user_status_history table needs.",
+ ),
],
)
def test_maps_probe_status(self, endpoint, status_code, expected_valid, expected_message):
@@ -258,6 +327,7 @@ class TestValidateCredentials:
"users": "/api/v2/users",
"queues": "/api/v2/routing/queues",
"external_organizations": "/api/v2/externalcontacts/scan/organizations",
+ "user_status_history": "/api/v2/analytics/users/details/query",
}[endpoint]
)