: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement testrail import source (#69391)
Tom Owersb1a0f9ee0409
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f24441049698..95db6dae8a39 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -331,6 +331,7 @@ the row lists both.| teamtailor | HTTP | requests | ✅ || teamwork | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |+| testrail | HTTP | requests | ✅ || thinkific | HTTP | requests | ✅ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || tmdb | HTTP | requests | ✅ |@@ -693,7 +694,6 @@ doesn't conflict with concurrent PRs.- tawk_to- teachable- tempo-- testrail- thinkific_courses- thrive_learning- ticketmasterdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 7bbb719feecf..ca4e08b8d104 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3289,7 +3289,9 @@ class TemporalIOSourceConfig(config.Config):@config.configclass TestrailSourceConfig(config.Config):- pass+ subdomain: str+ username: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/canonical_descriptions.pynew file mode 100644index 000000000000..9fe354261bc6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/canonical_descriptions.py@@ -0,0 +1,219 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the TestRail API docs (https://support.testrail.com/hc/en-us/sections/7077185274644-API-reference).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A project in TestRail — the top-level container for test suites, runs, plans, and milestones.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077792415124-Projects",+ "columns": {+ "id": "The unique ID of the project.",+ "name": "The name of the project.",+ "announcement": "The description or announcement of the project.",+ "show_announcement": "Whether the announcement is shown on the project's overview page.",+ "is_completed": "Whether the project is marked as completed (archived).",+ "completed_on": "When the project was marked as completed (UNIX timestamp).",+ "suite_mode": "The suite mode of the project: 1 = single suite, 2 = single suite with baselines, 3 = multiple suites.",+ "url": "The web address to the project in TestRail.",+ },+ },+ "users": {+ "description": "A user account on the TestRail instance.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077978310292-Users",+ "columns": {+ "id": "The unique ID of the user.",+ "name": "The full name of the user.",+ "email": "The email address of the user.",+ "is_active": "Whether the user account is active.",+ "role_id": "The ID of the user's role.",+ "role": "The name of the user's role.",+ },+ },+ "suites": {+ "description": "A test suite — a collection of test cases within a project.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077936624276-Suites",+ "columns": {+ "id": "The unique ID of the test suite.",+ "project_id": "The ID of the project the suite belongs to.",+ "name": "The name of the test suite.",+ "description": "The description of the test suite.",+ "is_master": "Whether the suite is the default (master) suite of a single-suite project.",+ "is_baseline": "Whether the suite is a baseline of another suite.",+ "is_completed": "Whether the suite is marked as completed (archived).",+ "completed_on": "When the suite was marked as completed (UNIX timestamp).",+ "url": "The web address to the suite in TestRail.",+ },+ },+ "sections": {+ "description": "A section grouping test cases within a suite, optionally nested under a parent section.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077918603412-Sections",+ "columns": {+ "id": "The unique ID of the section.",+ "suite_id": "The ID of the test suite the section belongs to.",+ "parent_id": "The ID of the parent section, or null for top-level sections.",+ "name": "The name of the section.",+ "description": "The description of the section.",+ "display_order": "The order of the section relative to its siblings.",+ "depth": "The nesting depth of the section (0 for top-level).",+ },+ },+ "cases": {+ "description": "A test case — the reusable definition of a test, organized into sections and suites.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077292642580-Cases",+ "columns": {+ "id": "The unique ID of the test case.",+ "title": "The title of the test case.",+ "section_id": "The ID of the section the case belongs to.",+ "suite_id": "The ID of the test suite the case belongs to.",+ "template_id": "The ID of the template (field layout) used by the case.",+ "type_id": "The ID of the case type (see the case_types table).",+ "priority_id": "The ID of the case priority (see the priorities table).",+ "milestone_id": "The ID of the milestone the case is linked to.",+ "refs": "A comma-separated list of external references or requirements.",+ "created_by": "The ID of the user who created the case.",+ "created_on": "When the case was created (UNIX timestamp).",+ "updated_by": "The ID of the user who last updated the case.",+ "updated_on": "When the case was last updated (UNIX timestamp).",+ "estimate": "The estimate of the case, e.g. '30s' or '1m 45s'.",+ "is_deleted": "Whether the case has been marked as deleted.",+ },+ },+ "milestones": {+ "description": "A milestone within a project, used to group test runs and plans toward a release or date.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077723976084-Milestones",+ "columns": {+ "id": "The unique ID of the milestone.",+ "project_id": "The ID of the project the milestone belongs to.",+ "parent_id": "The ID of the parent milestone, or null for top-level milestones.",+ "name": "The name of the milestone.",+ "description": "The description of the milestone.",+ "start_on": "The scheduled start date of the milestone (UNIX timestamp).",+ "started_on": "When the milestone was started (UNIX timestamp).",+ "due_on": "The due date of the milestone (UNIX timestamp).",+ "is_started": "Whether the milestone has been started.",+ "is_completed": "Whether the milestone has been completed.",+ "completed_on": "When the milestone was completed (UNIX timestamp).",+ "refs": "A comma-separated list of external references.",+ "url": "The web address to the milestone in TestRail.",+ },+ },+ "runs": {+ "description": "A test run — an execution of a set of test cases. Includes standalone runs and runs that belong to a test plan (plan_id is set).",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077874763156-Runs",+ "columns": {+ "id": "The unique ID of the test run.",+ "project_id": "The ID of the project the run belongs to.",+ "suite_id": "The ID of the test suite the run is derived from.",+ "plan_id": "The ID of the test plan the run belongs to, or null for standalone runs.",+ "entry_id": "The ID of the plan entry the run belongs to (plan runs only).",+ "milestone_id": "The ID of the milestone the run is linked to.",+ "name": "The name of the test run.",+ "description": "The description of the test run.",+ "config": "The configuration combination of the run (plan runs only), e.g. 'Firefox, Windows'.",+ "config_ids": "The IDs of the configurations of the run (plan runs only).",+ "include_all": "Whether the run includes all test cases of the suite or a selection.",+ "is_completed": "Whether the run has been closed (completed).",+ "completed_on": "When the run was closed (UNIX timestamp).",+ "assignedto_id": "The ID of the user the run is assigned to.",+ "passed_count": "The number of tests in the run with a passed status.",+ "blocked_count": "The number of tests in the run with a blocked status.",+ "untested_count": "The number of untested tests in the run.",+ "retest_count": "The number of tests in the run with a retest status.",+ "failed_count": "The number of tests in the run with a failed status.",+ "created_by": "The ID of the user who created the run.",+ "created_on": "When the run was created (UNIX timestamp).",+ "refs": "A comma-separated list of external references.",+ "url": "The web address to the run in TestRail.",+ },+ },+ "plans": {+ "description": "A test plan — a group of test runs, often spanning multiple suites and configurations.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077711537684-Plans",+ "columns": {+ "id": "The unique ID of the test plan.",+ "project_id": "The ID of the project the plan belongs to.",+ "milestone_id": "The ID of the milestone the plan is linked to.",+ "name": "The name of the test plan.",+ "description": "The description of the test plan.",+ "is_completed": "Whether the plan has been closed (completed).",+ "completed_on": "When the plan was closed (UNIX timestamp).",+ "assignedto_id": "The ID of the user the plan is assigned to.",+ "passed_count": "The number of tests across the plan with a passed status.",+ "blocked_count": "The number of tests across the plan with a blocked status.",+ "untested_count": "The number of untested tests across the plan.",+ "retest_count": "The number of tests across the plan with a retest status.",+ "failed_count": "The number of tests across the plan with a failed status.",+ "created_by": "The ID of the user who created the plan.",+ "created_on": "When the plan was created (UNIX timestamp).",+ "refs": "A comma-separated list of external references.",+ "url": "The web address to the plan in TestRail.",+ },+ },+ "tests": {+ "description": "A test — the instance of a test case inside a specific test run, carrying its current status.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077990441108-Tests",+ "columns": {+ "id": "The unique ID of the test.",+ "case_id": "The ID of the test case the test is derived from.",+ "run_id": "The ID of the test run the test belongs to.",+ "status_id": "The ID of the current status of the test (see the statuses table).",+ "assignedto_id": "The ID of the user the test is assigned to.",+ "title": "The title of the related test case.",+ "type_id": "The ID of the case type of the related test case.",+ "priority_id": "The ID of the priority of the related test case.",+ "milestone_id": "The ID of the milestone of the related test case.",+ "estimate": "The estimate of the related test case.",+ "refs": "A comma-separated list of external references of the related test case.",+ },+ },+ "results": {+ "description": "A test result — one status change or outcome recorded against a test. Results are append-only.",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077819312404-Results",+ "columns": {+ "id": "The unique ID of the test result.",+ "test_id": "The ID of the test the result belongs to.",+ "status_id": "The ID of the status recorded by the result (see the statuses table).",+ "comment": "The comment or error message of the result.",+ "version": "The version or build the test was executed against.",+ "elapsed": "The amount of time it took to execute the test, e.g. '30s' or '1m 45s'.",+ "defects": "A comma-separated list of defects linked to the result.",+ "assignedto_id": "The ID of the user the test is assigned to.",+ "created_by": "The ID of the user who added the result.",+ "created_on": "When the result was added (UNIX timestamp).",+ },+ },+ "statuses": {+ "description": "A test status available on the instance (passed, blocked, retest, failed, plus custom statuses).",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077935129364-Statuses",+ "columns": {+ "id": "The unique ID of the status.",+ "name": "The system name of the status.",+ "label": "The display label of the status.",+ "is_system": "Whether the status is one of TestRail's built-in statuses.",+ "is_untested": "Whether the status is the untested status.",+ "is_final": "Whether the status is a final status.",+ },+ },+ "priorities": {+ "description": "A test case priority available on the instance (e.g. Low, Medium, High, Critical).",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077746564244-Priorities",+ "columns": {+ "id": "The unique ID of the priority.",+ "name": "The full name of the priority.",+ "short_name": "The abbreviated name of the priority.",+ "priority": "The numeric order of the priority.",+ "is_default": "Whether the priority is the default for new test cases.",+ },+ },+ "case_types": {+ "description": "A test case type available on the instance (e.g. Functional, Regression, Automated).",+ "docs_url": "https://support.testrail.com/hc/en-us/articles/7077295487252-Case-Types",+ "columns": {+ "id": "The unique ID of the case type.",+ "name": "The name of the case type.",+ "is_default": "Whether the case type is the default for new test cases.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/settings.pynew file mode 100644index 000000000000..b75169bfe204--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/settings.py@@ -0,0 +1,168 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Paginated bulk endpoints accept a `limit` of up to 250; the largest page minimises round trips.+PAGE_SIZE = 250++# Where the endpoint sits in TestRail's resource hierarchy, which drives fan-out:+# instance-level endpoints are a single listing, project/suite/run endpoints iterate parents.+TestrailScope = Literal["instance", "project", "suite", "run"]+++def _epoch_incremental_field(name: str) -> list[IncrementalField]:+ # TestRail timestamps (`created_on` / `updated_on`) are UNIX epoch integers, and its+ # `*_after` filters take the same epoch format, so the advertised cursor is an Integer.+ return [+ {+ "label": name,+ "type": IncrementalFieldType.Integer,+ "field": name,+ "field_type": IncrementalFieldType.Integer,+ },+ ]+++@dataclass+class TestrailEndpointConfig:+ name: str+ # API method segment, e.g. "get_cases" in index.php?/api/v2/get_cases/{project_id}.+ method: str+ scope: TestrailScope+ # Key of the record list inside the bulk pagination envelope+ # ({"offset": ..., "limit": ..., "size": ..., "_links": ..., "<key>": [...]}). Endpoints+ # documented as returning a plain JSON array still declare it so the transport tolerates+ # either shape.+ response_key: str+ # Whether the endpoint documents limit/offset pagination (TestRail 6.7+ bulk endpoints).+ paginated: bool+ # Server-side UNIX-timestamp filter param (e.g. "updated_after"); None = full refresh only.+ incremental_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # TestRail record IDs are instance-global (case C123 / run R45 identifiers are unique across+ # projects), so `id` is a safe table-wide primary key even for fan-out endpoints.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++TESTRAIL_ENDPOINTS: dict[str, TestrailEndpointConfig] = {+ "projects": TestrailEndpointConfig(+ name="projects",+ method="get_projects",+ scope="instance",+ response_key="projects",+ # get_projects only filters by is_completed — no server-side timestamp, so full refresh.+ paginated=True,+ ),+ "users": TestrailEndpointConfig(+ name="users",+ method="get_users",+ scope="project",+ response_key="users",+ # Documented as a plain array; instance-wide listing needs an administrator account, so+ # the transport falls back to per-project listing (see _users_rows).+ paginated=False,+ ),+ "suites": TestrailEndpointConfig(+ name="suites",+ method="get_suites",+ scope="project",+ response_key="suites",+ paginated=False,+ ),+ "sections": TestrailEndpointConfig(+ name="sections",+ method="get_sections",+ scope="suite",+ response_key="sections",+ # get_sections exposes no timestamp filter, so full refresh only.+ paginated=True,+ ),+ "cases": TestrailEndpointConfig(+ name="cases",+ method="get_cases",+ scope="suite",+ response_key="cases",+ paginated=True,+ # get_cases filters server-side on updated_after (UNIX timestamp against updated_on).+ incremental_param="updated_after",+ incremental_fields=_epoch_incremental_field("updated_on"),+ ),+ "milestones": TestrailEndpointConfig(+ name="milestones",+ method="get_milestones",+ scope="project",+ response_key="milestones",+ # Only is_completed / is_started filters are documented — no timestamp, full refresh.+ paginated=True,+ ),+ "runs": TestrailEndpointConfig(+ name="runs",+ method="get_runs",+ scope="project",+ response_key="runs",+ paginated=True,+ # get_runs / get_plans filter on created_after only (runs have no updated_after filter),+ # so incremental catches new runs but not later edits — completion state on already+ # synced rows only refreshes on a full refresh. Plan-entry runs ride the plan's+ # created_after, so runs added to a pre-watermark plan are also full-refresh-only+ # (see _runs_rows).+ incremental_param="created_after",+ incremental_fields=_epoch_incremental_field("created_on"),+ ),+ "plans": TestrailEndpointConfig(+ name="plans",+ method="get_plans",+ scope="project",+ response_key="plans",+ paginated=True,+ incremental_param="created_after",+ incremental_fields=_epoch_incremental_field("created_on"),+ ),+ "tests": TestrailEndpointConfig(+ name="tests",+ method="get_tests",+ scope="run",+ response_key="tests",+ # get_tests only filters by status_id and tests carry no timestamps, so full refresh.+ paginated=True,+ ),+ "results": TestrailEndpointConfig(+ name="results",+ method="get_results_for_run",+ scope="run",+ response_key="results",+ paginated=True,+ # get_results_for_run documents a created_after filter; results are append-only in+ # TestRail, so a created_on cursor is a genuine incremental sync.+ incremental_param="created_after",+ incremental_fields=_epoch_incremental_field("created_on"),+ ),+ "statuses": TestrailEndpointConfig(+ name="statuses",+ method="get_statuses",+ scope="instance",+ response_key="statuses",+ paginated=False,+ ),+ "priorities": TestrailEndpointConfig(+ name="priorities",+ method="get_priorities",+ scope="instance",+ response_key="priorities",+ paginated=False,+ ),+ "case_types": TestrailEndpointConfig(+ name="case_types",+ method="get_case_types",+ scope="instance",+ response_key="case_types",+ paginated=False,+ ),+}++ENDPOINTS = tuple(TESTRAIL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TESTRAIL_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/source.pyindex c8c138487a50..be8e6a83b022 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/source.py@@ -1,30 +1,162 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TestrailSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ TESTRAIL_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.testrail import (+ TestrailResumeConfig,+ testrail_source,+ validate_credentials as validate_testrail_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TestrailSource(SimpleSource[TestrailSourceConfig]):+class TestrailSource(ResumableSource[TestrailSourceConfig, TestrailResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TESTRAIL+ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to `<subdomain>.testrail.io`, so changing the subdomain must+ # re-require the key.+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TESTRAIL,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Testrail",+ label="TestRail",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your TestRail Cloud address, email, and API key to pull your test management data into the PostHog Data warehouse.++Generate an API key under **My Settings → API keys** in TestRail, and make sure the API is enabled for your instance under **Administration → Site Settings → API**. Self-hosted TestRail Server instances on custom domains are not supported yet.""",iconPath="/static/services/testrail.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/testrail",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="TestRail address",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Email",+ type=SourceFieldInputConfigType.EMAIL,+ required=True,+ placeholder="[email protected]",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync.+ "401 Client Error: Unauthorized": "Your TestRail email or API key is invalid or has been revoked. Generate a new key under My Settings → API keys, then reconnect.",+ "403 Client Error: Forbidden": "TestRail rejected the request. Check that the API is enabled (Administration → Site Settings → API) and that your account can read this data, then reconnect.",+ }++ def get_schemas(+ self,+ config: TestrailSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.incremental_param is not None,+ supports_append=endpoint_config.incremental_param is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint, endpoint_config in TESTRAIL_ENDPOINTS.items()+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: TestrailSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # TestRail access is account-wide (project permissions surface per request at sync+ # time), so a single get_projects probe validates the credentials for every schema.+ return validate_testrail_credentials(config.subdomain, config.username, config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TestrailResumeConfig]:+ return ResumableSourceManager[TestrailResumeConfig](inputs, TestrailResumeConfig)++ def source_for_pipeline(+ self,+ config: TestrailSourceConfig,+ resumable_source_manager: ResumableSourceManager[TestrailResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in ENDPOINTS:+ raise ValueError(f"Unknown TestRail schema '{inputs.schema_name}'")++ return testrail_source(+ subdomain=config.subdomain,+ username=config.username,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/testrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/testrail.pynew file mode 100644index 000000000000..7ae834380741--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/testrail.py@@ -0,0 +1,570 @@+import re+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.settings import (+ PAGE_SIZE,+ TESTRAIL_ENDPOINTS,+)++REQUEST_TIMEOUT_SECONDS = 60+# Cheap probe confirming the credentials are genuine and the instance's API toggle is enabled.+DEFAULT_PROBE_METHOD = "get_projects"++# A single DNS label: letters, digits, hyphens. Rejects anything that could retarget the host+# (slashes, `@`, dots) so the stored API key is only ever sent to `<subdomain>.testrail.io`.+_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")+++class TestrailRetryableError(Exception):+ pass+++class TestrailResumeConfig:+ # Position of the NEXT page to fetch within the deterministic parent walk. `parent_path`+ # identifies the fan-out parent: [] for instance-level endpoints, [project_id],+ # [project_id, suite_id] or [run_id] for scoped ones. `phase` separates the two passes of+ # the `runs` endpoint (0 = standalone runs via get_runs, 1 = plan-entry runs via+ # get_plans/get_plan). Parents are walked in ascending id order, so a resume skips every+ # position before the saved one; merge on `id` dedupes any boundary page re-fetched.+ parent_path: list[int] = dataclasses.field(default_factory=list)+ phase: int = 0+ offset: int = 0+++class _ResumeCursor:+ """Maps a saved crash position onto the deterministic parent walk.++ Positions are ``(parent_path, phase)`` tuples visited in strictly ascending order, so a+ parent that compares below the saved position was fully synced before the crash and is+ skipped; the saved parent itself restarts at the saved offset; everything after syncs+ from offset 0.+ """++ def __init__(self, resume: TestrailResumeConfig | None) -> None:+ self._position = (tuple(resume.parent_path), resume.phase) if resume is not None else None+ self._offset = resume.offset if resume is not None else 0++ def start_offset(self, parent_path: tuple[int, ...], phase: int = 0) -> int | None:+ """Offset to start this parent at, or ``None`` to skip it entirely."""+ if self._position is None:+ return 0+ current = (parent_path, phase)+ if current < self._position:+ return None+ if current == self._position:+ return self._offset+ return 0+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce user input to a bare, validated TestRail Cloud subdomain label.++ Accepts either the full host (``yourcompany.testrail.io``) or the bare subdomain+ (``yourcompany``). Raises ``ValueError`` on anything that isn't a single DNS label so the+ API key can never be retargeted away from ``<subdomain>.testrail.io``.+ """+ cleaned = subdomain.strip().removeprefix("https://").removeprefix("http://")+ cleaned = cleaned.strip("/")+ cleaned = cleaned.removesuffix(".testrail.io").removesuffix(".testrail.com")+ if not _SUBDOMAIN_RE.match(cleaned):+ raise ValueError(+ f"Invalid TestRail address: {subdomain!r}. Enter just your subdomain, e.g. 'yourcompany' "+ "for yourcompany.testrail.io."+ )+ return cleaned+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.testrail.io/index.php?"+++def _build_url(+ base_url: str, method: str, path_id: Optional[int] = None, params: Optional[dict[str, Any]] = None+) -> str:+ # TestRail's router keeps the whole API path inside the query string+ # (index.php?/api/v2/get_cases/1&suite_id=2&limit=250), so extra params are appended+ # with `&`, never a second `?`.+ url = f"{base_url}/api/v2/{method}"+ if path_id is not None:+ url = f"{url}/{path_id}"+ if params:+ url = f"{url}&{urlencode(params)}"+ return url+++def _make_session(username: str, api_key: str) -> requests.Session:+ session = make_tracked_session(+ headers={"Accept": "application/json", "Content-Type": "application/json"},+ redact_values=(api_key,),+ )+ # TestRail auth is HTTP Basic with the account email plus an API key (or password).+ session.auth = (username, api_key)+ return session+++def _to_epoch(value: Any) -> int:+ """Coerce an incremental cursor into the UNIX timestamp TestRail's `*_after` filters expect."""+ if isinstance(value, bool):+ raise ValueError(f"Cannot use {value!r} as a TestRail timestamp cursor")+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return int(aware.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ return int(str(value))+++@retry(+ retry=retry_if_exception_type((TestrailRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Any:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # TestRail Cloud rate-limits (~180-300 req/min depending on plan) and answers 429 with a+ # Retry-After; exponential backoff with jitter stays under the window. Transient 5xx retry too.+ if response.status_code == 429 or response.status_code >= 500:+ raise TestrailRetryableError(f"TestRail API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"TestRail API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _extract_items(data: Any, response_key: str) -> tuple[list[dict[str, Any]], bool]:+ """Normalise both TestRail response shapes into ``(items, has_more)``.++ Bulk endpoints (6.7+) wrap records in {"offset", "limit", "size", "_links", "<key>": [...]};+ dictionary endpoints (suites, statuses, ...) return a plain JSON array. `has_more` comes+ exclusively from `_links.next` — a full page is never treated as "more" on its own, so an+ endpoint that ignores limit/offset can't loop forever.+ """+ if isinstance(data, list):+ return data, False+ if isinstance(data, dict) and isinstance(data.get(response_key), list):+ links = data.get("_links")+ has_more = isinstance(links, dict) and bool(links.get("next"))+ return data[response_key], has_more+ raise TestrailRetryableError(f"TestRail returned an unexpected payload shape: {type(data).__name__}")+++def _fetch_list(+ session: requests.Session,+ base_url: str,+ method: str,+ path_id: Optional[int],+ params: dict[str, Any],+ response_key: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ data = _fetch(session, _build_url(base_url, method, path_id, params), logger)+ items, _ = _extract_items(data, response_key)+ return items+++def _paginate(+ session: requests.Session,+ base_url: str,+ method: str,+ path_id: Optional[int],+ extra_params: dict[str, Any],+ response_key: str,+ logger: FilteringBoundLogger,+ start_offset: int = 0,+ save_state: Optional[Callable[[int], None]] = None,+) -> Iterator[list[dict[str, Any]]]:+ """Walk one parent's limit/offset pages, yielding each page's records.++ ``save_state`` (when set) is called with the NEXT page's offset after the consumer has+ fully processed the yielded page — save AFTER yielding, so a crash re-fetches the last+ page and merge dedupes it on the primary key rather than skipping it.+ """+ offset = start_offset+ while True:+ params: dict[str, Any] = {**extra_params, "limit": PAGE_SIZE, "offset": offset}+ data = _fetch(session, _build_url(base_url, method, path_id, params), logger)+ items, has_more = _extract_items(data, response_key)+ if items:+ yield items+ if save_state is not None:+ save_state(offset + PAGE_SIZE)+ if not has_more:+ break+ offset += PAGE_SIZE+++def _make_checkpoint(+ resumable_source_manager: ResumableSourceManager[TestrailResumeConfig],+ parent_path: tuple[int, ...],+ phase: int = 0,+) -> Callable[[int], None]:+ def save(next_offset: int) -> None:+ resumable_source_manager.save_state(+ TestrailResumeConfig(parent_path=list(parent_path), phase=phase, offset=next_offset)+ )++ return save+++def _list_project_ids(session: requests.Session, base_url: str, logger: FilteringBoundLogger) -> list[int]:+ project_ids: list[int] = []+ for page in _paginate(session, base_url, "get_projects", None, {}, "projects", logger):+ project_ids.extend(project["id"] for project in page)+ return sorted(project_ids)+++def _list_suite_units(+ session: requests.Session, base_url: str, project_ids: list[int], logger: FilteringBoundLogger+) -> list[tuple[int, int]]:+ """Every (project_id, suite_id) pair, ascending. get_suites also returns the default suite+ of single-suite-mode projects, so the same walk covers every suite mode."""+ units: list[tuple[int, int]] = []+ for project_id in project_ids:+ suites = _fetch_list(session, base_url, "get_suites", project_id, {}, "suites", logger)+ units.extend((project_id, suite["id"]) for suite in suites)+ return sorted(units)+++def _plan_entry_runs(+ session: requests.Session, base_url: str, plan_id: int, logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ """Runs embedded in a plan's entries (same record shape as get_runs rows, with plan_id set).+ get_plans omits `entries`, so each plan needs one get_plan detail request."""+ plan = _fetch(session, _build_url(base_url, "get_plan", plan_id), logger)+ if not isinstance(plan, dict):+ raise TestrailRetryableError(f"TestRail returned an unexpected get_plan payload: {type(plan).__name__}")+ runs: list[dict[str, Any]] = []+ for entry in plan.get("entries") or []:+ runs.extend(entry.get("runs") or [])+ return runs+++def _list_run_ids(+ session: requests.Session, base_url: str, project_ids: list[int], logger: FilteringBoundLogger+) -> list[int]:+ """Every run id, ascending: standalone runs (get_runs excludes runs inside plans) plus+ plan-entry runs, so tests/results cover plan-driven QA workflows too."""+ run_ids: set[int] = set()+ for project_id in project_ids:+ for page in _paginate(session, base_url, "get_runs", project_id, {}, "runs", logger):+ run_ids.update(run["id"] for run in page)+ for page in _paginate(session, base_url, "get_plans", project_id, {}, "plans", logger):+ for plan in page:+ run_ids.update(run["id"] for run in _plan_entry_runs(session, base_url, plan["id"], logger))+ logger.debug(f"TestRail: enumerated {len(run_ids)} runs across {len(project_ids)} projects")+ return sorted(run_ids)+++def _users_rows(+ session: requests.Session, base_url: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ """Instance-wide get_users needs an administrator account; everyone else must pass a+ project id. Try the admin listing first (it also includes users with only global access),+ then fall back to per-project listing with client-side dedupe. The walk is one cheap+ request per project, so it restarts from scratch instead of checkpointing — a resumed+ seen-set would otherwise re-emit duplicate rows into a full-refresh table.+ """+ try:+ users = _fetch_list(session, base_url, "get_users", None, {}, "users", logger)+ if users:+ yield users+ return+ except requests.HTTPError as e:+ if e.response is None or e.response.status_code != 403:+ raise+ logger.debug("TestRail: instance-wide get_users forbidden, falling back to per-project listing")++ seen: set[Any] = set()+ for project_id in _list_project_ids(session, base_url, logger):+ users = _fetch_list(session, base_url, "get_users", project_id, {}, "users", logger)+ # Direct access on the user's id (its primary key): a user without one is a broken+ # response that should fail loudly, not get silently deduplicated against None.+ fresh = [user for user in users if user["id"] not in seen]+ seen.update(user["id"] for user in fresh)+ if fresh:+ yield fresh+++def _runs_rows(+ session: requests.Session,+ base_url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TestrailResumeConfig],+ cursor: _ResumeCursor,+ cutoff: int | None,+) -> Iterator[list[dict[str, Any]]]:+ """The runs table combines, per project, standalone runs (phase 0: get_runs, which+ excludes runs inside plans) and plan-entry runs (phase 1: get_plans -> get_plan ->+ entries[].runs[]). On incremental syncs created_after bounds get_runs directly and bounds+ plan-entry runs via their PLAN's creation time — runs added later to a pre-watermark plan+ only appear on a full refresh (documented in the source docs).+ """+ extra_params: dict[str, Any] = {"created_after": cutoff} if cutoff is not None else {}+ project_ids = _list_project_ids(session, base_url, logger)++ for project_id in project_ids:+ offset = cursor.start_offset((project_id,), phase=0)+ if offset is not None:+ yield from _paginate(+ session,+ base_url,+ "get_runs",+ project_id,+ extra_params,+ "runs",+ logger,+ start_offset=offset,+ save_state=_make_checkpoint(resumable_source_manager, (project_id,), phase=0),+ )++ offset = cursor.start_offset((project_id,), phase=1)+ if offset is None:+ continue+ for plan_page in _paginate(+ session,+ base_url,+ "get_plans",+ project_id,+ extra_params,+ "plans",+ logger,+ start_offset=offset,+ save_state=_make_checkpoint(resumable_source_manager, (project_id,), phase=1),+ ):+ runs: list[dict[str, Any]] = []+ for plan in plan_page:+ runs.extend(_plan_entry_runs(session, base_url, plan["id"], logger))+ if runs:+ yield runs+++def get_rows(+ subdomain: str,+ username: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TestrailResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = TESTRAIL_ENDPOINTS[endpoint]+ base_url = _base_url(subdomain)+ session = _make_session(username, api_key)++ cutoff: int | None = None+ if config.incremental_param is not None and should_use_incremental_field and db_incremental_field_last_value:+ cutoff = _to_epoch(db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = _ResumeCursor(resume)+ if resume is not None:+ logger.debug(+ f"TestRail: resuming {endpoint} from parent={resume.parent_path} phase={resume.phase} "+ f"offset={resume.offset}"+ )++ if endpoint == "runs":+ yield from _runs_rows(session, base_url, logger, resumable_source_manager, cursor, cutoff)+ return++ if endpoint == "users":+ yield from _users_rows(session, base_url, logger)+ return++ extra_params: dict[str, Any] = {}+ if cutoff is not None and config.incremental_param is not None:+ extra_params[config.incremental_param] = cutoff++ if config.scope == "instance":+ if not config.paginated:+ items = _fetch_list(session, base_url, config.method, None, {}, config.response_key, logger)+ if items:+ yield items+ return+ offset = cursor.start_offset(())+ if offset is None:+ return+ yield from _paginate(+ session,+ base_url,+ config.method,+ None,+ extra_params,+ config.response_key,+ logger,+ start_offset=offset,+ save_state=_make_checkpoint(resumable_source_manager, ()),+ )+ return++ project_ids = _list_project_ids(session, base_url, logger)++ if config.scope == "project":+ if not config.paginated:+ # One cheap request per project (e.g. suites) — no checkpointing needed.+ for project_id in project_ids:+ items = _fetch_list(session, base_url, config.method, project_id, {}, config.response_key, logger)+ if items:+ yield items+ return+ for project_id in project_ids:+ offset = cursor.start_offset((project_id,))+ if offset is None:+ continue+ yield from _paginate(+ session,+ base_url,+ config.method,+ project_id,+ extra_params,+ config.response_key,+ logger,+ start_offset=offset,+ save_state=_make_checkpoint(resumable_source_manager, (project_id,)),+ )+ return++ if config.scope == "suite":+ for project_id, suite_id in _list_suite_units(session, base_url, project_ids, logger):+ offset = cursor.start_offset((project_id, suite_id))+ if offset is None:+ continue+ yield from _paginate(+ session,+ base_url,+ config.method,+ project_id,+ {**extra_params, "suite_id": suite_id},+ config.response_key,+ logger,+ start_offset=offset,+ save_state=_make_checkpoint(resumable_source_manager, (project_id, suite_id)),+ )+ return++ # scope == "run": tests and results fan out over every run (standalone + plan-entry).+ for run_id in _list_run_ids(session, base_url, project_ids, logger):+ offset = cursor.start_offset((run_id,))+ if offset is None:+ continue+ yield from _paginate(+ session,+ base_url,+ config.method,+ run_id,+ extra_params,+ config.response_key,+ logger,+ start_offset=offset,+ save_state=_make_checkpoint(resumable_source_manager, (run_id,)),+ )+++def testrail_source(+ subdomain: str,+ username: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TestrailResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = TESTRAIL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ username=username,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ # Fan-out across projects/suites/runs means rows never arrive globally time-ordered, so+ # incremental endpoints declare "desc": the watermark commits only once the whole sync+ # completes instead of checkpointing after every batch.+ sort_mode="desc" if config.incremental_param is not None else "asc",+ )+++def _error_message(response: requests.Response) -> Optional[str]:+ # TestRail error bodies are {"error": "..."} with a user-actionable message (bad credentials+ # vs the API toggle being disabled), so surface it verbatim when present.+ try:+ body = response.json()+ except Exception:+ return None+ if isinstance(body, dict) and isinstance(body.get("error"), str):+ return body["error"]+ return None+++def check_access(subdomain: str, username: str, api_key: str) -> tuple[int, Optional[str]]:+ """Probe get_projects to validate the credentials and the instance's API toggle.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth or API-disabled+ failure (message carries TestRail's own explanation when available), ``0`` for a+ connection problem, other HTTP status otherwise. Raises ``ValueError`` on a malformed+ subdomain so the caller can surface a precise message.+ """+ session = _make_session(username, api_key)+ url = _build_url(_base_url(subdomain), DEFAULT_PROBE_METHOD, None, {"limit": 1})+ try:+ response = session.get(url, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to TestRail: {e}"++ if response.status_code in (401, 403):+ return response.status_code, _error_message(response)++ if not response.ok:+ return response.status_code, f"TestRail returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(subdomain: str, username: str, api_key: str) -> tuple[bool, str | None]:+ try:+ status, message = check_access(subdomain, username, api_key)+ except ValueError as e:+ return False, str(e)++ if status == 200:+ return True, None+ if status == 401:+ return False, message or "Invalid TestRail email or API key"+ if status == 403:+ return False, (+ message+ or "TestRail rejected the request. Check that the API is enabled under "+ "Administration > Site Settings > API."+ )+ return False, message or "Could not validate TestRail credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/tests/test_testrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/tests/test_testrail.pynew file mode 100644index 000000000000..e89eeb3b03c5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/tests/test_testrail.py@@ -0,0 +1,431 @@+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import parse_qsl++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.testrail import testrail+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.settings import (+ ENDPOINTS,+ PAGE_SIZE,+ TESTRAIL_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.testrail import (+ TestrailResumeConfig,+ TestrailRetryableError,+ _build_url,+ _extract_items,+ _to_epoch,+ check_access,+ get_rows,+ normalize_subdomain,+ testrail_source as make_testrail_source, # aliased so pytest doesn't collect it as a test+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_unwrapped = testrail._fetch.__wrapped__ # type: ignore[attr-defined]++BASE_URL = "https://acme.testrail.io/index.php?"+++class _FakeResumableManager:+ def __init__(self, state: TestrailResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[TestrailResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> TestrailResumeConfig | None:+ return self._state++ def save_state(self, data: TestrailResumeConfig) -> None:+ self.saved.append(data)+++def _parse_api_url(url: str) -> tuple[str, Optional[int], dict[str, str]]:+ """Split a TestRail URL into (method, path_id, params) for request assertions."""+ query = url.split("index.php?", 1)[1]+ path, _, param_string = query.partition("&")+ segments = path.removeprefix("/api/v2/").split("/")+ method = segments[0]+ path_id = int(segments[1]) if len(segments) > 1 else None+ return method, path_id, dict(parse_qsl(param_string))+++def _bulk(key: str, items: list[dict], has_more: bool = False) -> dict:+ return {+ "offset": 0,+ "limit": PAGE_SIZE,+ "size": len(items),+ "_links": {"next": f"/api/v2/next&offset={PAGE_SIZE}" if has_more else None, "prev": None},+ key: items,+ }+++class _FakeApi:+ """Routes _fetch calls to canned responses keyed on (method, path_id); records every request."""++ def __init__(self, responses: dict[tuple[str, Optional[int]], Any]) -> None:+ self._responses = responses+ self.requests: list[tuple[str, Optional[int], dict[str, str]]] = []++ def __call__(self, session: Any, url: str, logger: Any) -> Any:+ method, path_id, params = _parse_api_url(url)+ self.requests.append((method, path_id, params))+ response = self._responses[(method, path_id)]+ if isinstance(response, Exception):+ raise response+ if callable(response):+ return response(params)+ return response++ def params_for(self, method: str) -> list[dict[str, str]]:+ return [params for m, _, params in self.requests if m == method]+++def _http_error(status: int) -> requests.HTTPError:+ response = MagicMock()+ response.status_code = status+ return requests.HTTPError(f"{status} error", response=response)+++def _collect(+ api: _FakeApi,+ endpoint: str,+ monkeypatch: Any,+ manager: _FakeResumableManager | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[dict]:+ monkeypatch.setattr(testrail, "_fetch", api)+ monkeypatch.setattr(testrail, "_make_session", lambda username, api_key: MagicMock())+ rows: list[dict] = []+ for batch in get_rows(+ subdomain="acme",+ username="[email protected]",+ api_key="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager or _FakeResumableManager(), # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows+++class TestUrlBuilding:+ def test_params_are_appended_with_ampersand_not_second_question_mark(self) -> None:+ # TestRail's whole API path lives inside the query string; a second `?` would break routing.+ url = _build_url(BASE_URL, "get_cases", 12, {"suite_id": 3, "limit": 250, "offset": 0})+ assert url == "https://acme.testrail.io/index.php?/api/v2/get_cases/12&suite_id=3&limit=250&offset=0"++ def test_method_without_id_or_params(self) -> None:+ assert _build_url(BASE_URL, "get_statuses") == "https://acme.testrail.io/index.php?/api/v2/get_statuses"++ @parameterized.expand(+ [+ ("bare", "acme", "acme"),+ ("full_host", "acme.testrail.io", "acme"),+ ("scheme_and_slash", "https://acme.testrail.io/", "acme"),+ ("whitespace", " acme ", "acme"),+ ]+ )+ def test_normalize_subdomain_accepts(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_subdomain(raw) == expected++ @parameterized.expand(+ [+ ("path_injection", "evil.com/index.php"),+ ("at_sign", "[email protected]"),+ ("dotted_host", "acme.evil.com"),+ ("empty", ""),+ ]+ )+ def test_normalize_subdomain_rejects_retargeting(self, _name: str, raw: str) -> None:+ with pytest.raises(ValueError):+ normalize_subdomain(raw)+++class TestToEpoch:+ @parameterized.expand(+ [+ ("int_passthrough", 1700000000, 1700000000),+ ("numeric_string", "1700000000", 1700000000),+ ("datetime_utc", datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),+ ("naive_datetime_treated_as_utc", datetime(2023, 11, 14, 22, 13, 20), 1700000000),+ ("date_midnight_utc", date(2023, 11, 14), 1699920000),+ ]+ )+ def test_coercions(self, _name: str, value: Any, expected: int) -> None:+ assert _to_epoch(value) == expected+++class TestExtractItems:+ def test_plain_array_is_a_single_page(self) -> None:+ items, has_more = _extract_items([{"id": 1}], "suites")+ assert items == [{"id": 1}]+ assert has_more is False++ def test_bulk_envelope_reads_items_and_next_link(self) -> None:+ items, has_more = _extract_items(_bulk("cases", [{"id": 2}], has_more=True), "cases")+ assert items == [{"id": 2}]+ assert has_more is True++ def test_null_next_link_terminates(self) -> None:+ _, has_more = _extract_items(_bulk("cases", [{"id": 2}] * PAGE_SIZE, has_more=False), "cases")+ # A full page with a null `_links.next` must NOT be treated as "more" — an endpoint that+ # ignores limit/offset would otherwise loop on the same page forever.+ assert has_more is False++ @parameterized.expand([("string", "nope"), ("wrong_key", {"other": []}), ("null", None)])+ def test_unexpected_payload_is_retryable(self, _name: str, payload: Any) -> None:+ with pytest.raises(TestrailRetryableError):+ _extract_items(payload, "cases")+++class TestFetch:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else []+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ with pytest.raises(TestrailRetryableError):+ _fetch_unwrapped(+ self._session_returning(status), "https://acme.testrail.io/index.php?/api/v2/x", MagicMock()+ )++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ with pytest.raises(requests.HTTPError):+ _fetch_unwrapped(+ self._session_returning(status), "https://acme.testrail.io/index.php?/api/v2/x", MagicMock()+ )+++class TestPagination:+ def test_follows_next_link_and_checkpoints_after_each_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()++ def projects(params: dict[str, str]) -> dict:+ if params["offset"] == "0":+ return _bulk("projects", [{"id": 1}], has_more=True)+ return _bulk("projects", [{"id": 2}], has_more=False)++ api = _FakeApi({("get_projects", None): projects})+ rows = _collect(api, "projects", monkeypatch, manager=manager)++ assert [row["id"] for row in rows] == [1, 2]+ offsets = [params["offset"] for params in api.params_for("get_projects")]+ assert offsets == ["0", str(PAGE_SIZE)]+ # State is saved AFTER each yielded page, pointing at the next page's offset.+ assert [(s.parent_path, s.offset) for s in manager.saved] == [([], PAGE_SIZE), ([], PAGE_SIZE * 2)]+++class TestSuiteScopedFanOut:+ def _api(self) -> _FakeApi:+ return _FakeApi(+ {+ ("get_projects", None): _bulk("projects", [{"id": 1}]),+ ("get_suites", 1): [{"id": 10}, {"id": 11}],+ ("get_cases", 1): lambda params: _bulk(+ "cases", [{"id": int(params["suite_id"]) * 100, "suite_id": int(params["suite_id"])}]+ ),+ }+ )++ def test_cases_fan_out_over_every_suite(self, monkeypatch: Any) -> None:+ rows = _collect(self._api(), "cases", monkeypatch)+ assert [row["id"] for row in rows] == [1000, 1100]++ def test_incremental_sends_updated_after_to_every_case_request(self, monkeypatch: Any) -> None:+ api = self._api()+ _collect(+ api, "cases", monkeypatch, should_use_incremental_field=True, db_incremental_field_last_value=1700000000+ )+ case_params = api.params_for("get_cases")+ assert len(case_params) == 2+ assert all(params["updated_after"] == "1700000000" for params in case_params)++ def test_full_refresh_sends_no_timestamp_filter(self, monkeypatch: Any) -> None:+ api = self._api()+ _collect(api, "cases", monkeypatch)+ assert all("updated_after" not in params for params in api.params_for("get_cases"))++ def test_resume_skips_completed_suites_and_restarts_at_saved_offset(self, monkeypatch: Any) -> None:+ api = self._api()+ manager = _FakeResumableManager(TestrailResumeConfig(parent_path=[1, 11], offset=PAGE_SIZE))+ rows = _collect(api, "cases", monkeypatch, manager=manager)+ # Suite 10 compares below the saved position, so it was fully synced before the crash.+ assert [row["id"] for row in rows] == [1100]+ case_params = api.params_for("get_cases")+ assert [params["suite_id"] for params in case_params] == ["11"]+ assert case_params[0]["offset"] == str(PAGE_SIZE)+++class TestRunsEndpoint:+ def _api(self) -> _FakeApi:+ return _FakeApi(+ {+ ("get_projects", None): _bulk("projects", [{"id": 1}]),+ ("get_runs", 1): _bulk("runs", [{"id": 100, "plan_id": None}]),+ ("get_plans", 1): _bulk("plans", [{"id": 200}]),+ ("get_plan", 200): {"id": 200, "entries": [{"runs": [{"id": 201, "plan_id": 200}]}]},+ }+ )++ def test_combines_standalone_and_plan_entry_runs(self, monkeypatch: Any) -> None:+ rows = _collect(self._api(), "runs", monkeypatch)+ assert [row["id"] for row in rows] == [100, 201]++ def test_incremental_bounds_both_get_runs_and_get_plans(self, monkeypatch: Any) -> None:+ api = self._api()+ _collect(+ api, "runs", monkeypatch, should_use_incremental_field=True, db_incremental_field_last_value=1700000000+ )+ assert api.params_for("get_runs")[0]["created_after"] == "1700000000"+ assert api.params_for("get_plans")[0]["created_after"] == "1700000000"+++class TestRunScopedFanOut:+ def _api(self) -> _FakeApi:+ return _FakeApi(+ {+ ("get_projects", None): _bulk("projects", [{"id": 1}]),+ ("get_runs", 1): _bulk("runs", [{"id": 100}]),+ ("get_plans", 1): _bulk("plans", [{"id": 200}]),+ ("get_plan", 200): {"id": 200, "entries": [{"runs": [{"id": 201}]}]},+ ("get_results_for_run", 100): _bulk("results", [{"id": 9000, "test_id": 1}]),+ ("get_results_for_run", 201): _bulk("results", [{"id": 9001, "test_id": 2}]),+ }+ )++ def test_results_cover_plan_entry_runs(self, monkeypatch: Any) -> None:+ rows = _collect(self._api(), "results", monkeypatch)+ assert [row["id"] for row in rows] == [9000, 9001]++ def test_incremental_filters_results_but_not_run_enumeration(self, monkeypatch: Any) -> None:+ # The run walk must stay unfiltered so results added to OLD runs after the watermark are+ # still found; only the per-run results request carries created_after.+ api = self._api()+ _collect(+ api, "results", monkeypatch, should_use_incremental_field=True, db_incremental_field_last_value=1700000000+ )+ assert all("created_after" not in params for params in api.params_for("get_runs"))+ assert all("created_after" not in params for params in api.params_for("get_plans"))+ assert all(params["created_after"] == "1700000000" for params in api.params_for("get_results_for_run"))+++class TestUsersEndpoint:+ def test_admin_listing_is_used_when_permitted(self, monkeypatch: Any) -> None:+ api = _FakeApi({("get_users", None): [{"id": 1}, {"id": 2}]})+ rows = _collect(api, "users", monkeypatch)+ assert [row["id"] for row in rows] == [1, 2]+ # No per-project fallback means get_projects is never called.+ assert api.params_for("get_projects") == []++ def test_forbidden_admin_listing_falls_back_to_per_project_with_dedupe(self, monkeypatch: Any) -> None:+ api = _FakeApi(+ {+ ("get_users", None): _http_error(403),+ ("get_projects", None): _bulk("projects", [{"id": 1}, {"id": 2}]),+ ("get_users", 1): [{"id": 7}, {"id": 8}],+ ("get_users", 2): [{"id": 8}, {"id": 9}],+ }+ )+ rows = _collect(api, "users", monkeypatch)+ assert [row["id"] for row in rows] == [7, 8, 9]++ def test_non_403_admin_error_propagates(self, monkeypatch: Any) -> None:+ api = _FakeApi({("get_users", None): _http_error(500)})+ with pytest.raises(requests.HTTPError):+ _collect(api, "users", monkeypatch)+++class TestInstanceDictionaries:+ def test_statuses_yield_from_a_single_plain_array_request(self, monkeypatch: Any) -> None:+ api = _FakeApi({("get_statuses", None): [{"id": 1, "name": "passed"}]})+ rows = _collect(api, "statuses", monkeypatch)+ assert rows == [{"id": 1, "name": "passed"}]+ assert len(api.requests) == 1+ # Dictionary endpoints are documented as plain arrays — no pagination params sent.+ assert api.params_for("get_statuses") == [{}]+++class TestTestrailSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = make_testrail_source(+ subdomain="acme",+ username="[email protected]",+ api_key="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Fan-out rows never arrive globally time-ordered, so incremental endpoints must commit+ # their watermark only at end of sync (desc); asc would corrupt it on mid-sync restarts.+ expected_sort = "desc" if TESTRAIL_ENDPOINTS[endpoint].incremental_param else "asc"+ assert response.sort_mode == expected_sort+++class TestCheckAccess:+ def _response(self, status: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ if body is None:+ response.json.side_effect = ValueError("no body")+ else:+ response.json.return_value = body+ return response++ @patch(f"{testrail.__name__}._make_session")+ def test_surfaces_testrail_error_message_on_forbidden(self, mock_session: MagicMock) -> None:+ api_disabled = "The API is disabled for your installation."+ mock_session.return_value.get.return_value = self._response(403, {"error": api_disabled})+ assert check_access("acme", "[email protected]", "key") == (403, api_disabled)++ @patch(f"{testrail.__name__}._make_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ status, message = check_access("acme", "[email protected]", "key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid TestRail email or API key"),+ ("server_error", 500, False, "TestRail returned HTTP 500"),+ ]+ )+ @patch(f"{testrail.__name__}._make_session")+ def test_validate_credentials_status_mapping(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None, mock_session: MagicMock+ ) -> None:+ mock_session.return_value.get.return_value = self._response(status)+ assert validate_credentials("acme", "[email protected]", "key") == (expected_valid, expected_message)++ def test_malformed_subdomain_returns_precise_message(self) -> None:+ valid, message = validate_credentials("evil.com/@x", "[email protected]", "key")+ assert valid is False+ assert message is not None and "Invalid TestRail address" in messagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/tests/test_testrail_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/tests/test_testrail_source.pynew file mode 100644index 000000000000..e21d7811bac8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/testrail/tests/test_testrail_source.py@@ -0,0 +1,155 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TestrailSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.settings import (+ ENDPOINTS,+ TESTRAIL_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.source import TestrailSource+from products.warehouse_sources.backend.temporal.data_imports.sources.testrail.testrail import TestrailResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"cases", "runs", "plans", "results"}+++class TestTestrailSource:+ def setup_method(self) -> None:+ self.source = TestrailSource()+ self.team_id = 123+ self.config = TestrailSourceConfig(subdomain="acme", username="[email protected]", api_key="testrail-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TESTRAIL++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Testrail"+ assert config.label == "TestRail"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/testrail"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["subdomain", "username", "api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_subdomain_is_a_connection_host_field(self) -> None:+ # The stored API key is sent to `<subdomain>.testrail.io`; without this, an editor could+ # retarget the subdomain and exfiltrate the preserved key.+ assert self.source.connection_host_fields == ["subdomain"]++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_with_correct_incremental_flags(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)+ assert {name for name, s in schemas.items() if s.supports_incremental} == INCREMENTAL_ENDPOINTS+ assert schemas["cases"].incremental_fields[0]["field"] == "updated_on"+ for name in INCREMENTAL_ENDPOINTS - {"cases"}:+ assert schemas[name].incremental_fields[0]["field"] == "created_on"+ for name in set(ENDPOINTS) - INCREMENTAL_ENDPOINTS:+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["cases", "nope"])+ assert [s.name for s in schemas] == ["cases"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert "Incremental" in tables["cases"]["sync_methods"]+ assert tables["suites"]["sync_methods"] == ["Full refresh"]++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://acme.testrail.io/index.php?/api/v2/get_projects&limit=250&offset=0",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://acme.testrail.io/index.php?/api/v2/get_cases/1&suite_id=2",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://acme.testrail.io/index.php?"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://acme.testrail.io/index.php?"),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.testrail.source.validate_testrail_credentials"+ )+ def test_validate_credentials_delegates_full_connection_details(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid TestRail email or API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("acme", "[email protected]", "testrail-key")+ assert result == (False, "Invalid TestRail email or API key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TestrailResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.testrail.source.testrail_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "cases"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["subdomain"] == "acme"+ assert kwargs["username"] == "[email protected]"+ assert kwargs["api_key"] == "testrail-key"+ assert kwargs["endpoint"] == "cases"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.testrail.source.testrail_source")+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark left on the schema must not leak into a full-refresh sync.+ inputs = mock.MagicMock()+ inputs.schema_name = "cases"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = 1700000000++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown TestRail schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ # TestRail record IDs are instance-global; a non-unique key would multi-match on merge.+ assert all(config.primary_keys == ["id"] for config in TESTRAIL_ENDPOINTS.values())+ assert set(TESTRAIL_ENDPOINTS) == set(ENDPOINTS)