repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
posthog
posthog/temporal/quota_limiting/__init__.py
.py
from posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingWorkflow, run_quota_limiting_all_orgs WORKFLOWS = [ RunQuotaLimitingWorkflow, ] ACTIVITIES = [ run_quota_limiting_all_orgs, ]
10
215
posthog
posthog/temporal/quota_limiting/run_quota_limiting.py
.py
import json import logging import dataclasses from datetime import timedelta import structlog from temporalio import activity, common, workflow from posthog.exceptions_capture import capture_exception from posthog.sync import database_sync_to_async from posthog.temporal.common.base import PostHogWorkflow from posthog...
88
2,798
posthog
posthog/temporal/tests/test_export_workflow.py
.py
from concurrent.futures import ThreadPoolExecutor import pytest from unittest.mock import MagicMock, patch from django.conf import settings from asgiref.sync import sync_to_async from temporalio.testing import WorkflowEnvironment from temporalio.worker import UnsandboxedWorkflowRunner, Worker from posthog.hogql.err...
206
7,362
posthog
posthog/temporal/tests/test_clickhouse.py
.py
import uuid import asyncio import datetime as dt import contextlib import pytest from unittest.mock import MagicMock, patch from posthog.clickhouse.query_tagging import QueryTags from posthog.temporal.common.clickhouse import ( ClickHouseAllReplicasAreStaleError, ClickHouseCheckQueryStatusError, ClickHous...
511
20,201
posthog
posthog/temporal/tests/test_encryption_codec.py
.py
import json import uuid import base64 import dataclasses import collections.abc import pytest from django.conf import settings import temporalio.converter from cryptography.fernet import InvalidToken from temporalio.api.enums.v1 import EventType from temporalio.client import Client from temporalio.worker import Unsa...
239
7,423
posthog
posthog/temporal/tests/test_codec_server.py
.py
import os from unittest.mock import patch from django.conf import settings from django.test import Client, TestCase from google.protobuf import json_format from temporalio.api.common.v1 import Payload, Payloads from posthog.temporal.common.codec import EncryptionCodec class CodecServerTestCase(TestCase): def ...
100
4,203
posthog
posthog/temporal/tests/test_oauth.py
.py
from uuid import uuid4 from django.test import SimpleTestCase, TestCase, override_settings from parameterized import parameterized from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE from posthog.temporal.oauth import ( ARRAY...
248
11,752
posthog
posthog/temporal/tests/test_export_activities.py
.py
import uuid from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from datetime import timedelta import pytest from unittest.mock import MagicMock, patch from django.conf import settings import temporalio.workflow from asgiref.sync import sync_to_async from playwright.sync_api ...
148
5,445
posthog
posthog/temporal/tests/test_schedule.py
.py
import pytest from unittest import mock from django.conf import settings from django.test import override_settings from temporalio.client import Schedule, ScheduleActionStartWorkflow from posthog.temporal.schedule import create_wa_digest_notification_schedule, create_wa_weekly_digest_schedule # Both WA digest sche...
39
1,789
posthog
posthog/temporal/tests/test_slo_interceptor.py
.py
import dataclasses from datetime import timedelta import pytest from unittest.mock import MagicMock, patch import temporalio.activity import temporalio.workflow from temporalio.exceptions import ApplicationError from temporalio.testing import WorkflowEnvironment from temporalio.worker import UnsandboxedWorkflowRunner...
270
9,500
posthog
posthog/temporal/tests/test_alerts_workflows.py
.py
import uuid from collections.abc import Callable from contextlib import nullcontext from datetime import UTC, datetime from typing import Any import pytest from unittest.mock import AsyncMock, MagicMock, patch from django.conf import settings import pytest_asyncio from asgiref.sync import sync_to_async from temporal...
422
15,774
posthog
posthog/temporal/tests/test_subscriptions_workflows.py
.py
import uuid import smtplib from collections.abc import Callable, Sequence from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta from typing import Any, cast from zoneinfo import ZoneInfo import pytest from freezegun import freeze_time from unittest.mock import AsyncMock, MagicMock,...
2,732
116,032
posthog
posthog/temporal/tests/test_alerts_investigation.py
.py
"""Tests for the investigation-agent trigger helpers in posthog/temporal/alerts/investigation.py. The decision logic — should we kick off an investigation, can we claim the cooldown slot — runs synchronously inside the `evaluate_alert` activity. These tests exercise the helpers directly so they're independent of Tempo...
151
5,923
posthog
posthog/temporal/tests/test_shutdown.py
.py
import uuid import asyncio from concurrent.futures import ThreadPoolExecutor import pytest import pytest_asyncio from temporalio.client import Client, WorkflowFailureError from temporalio.common import RetryPolicy from temporalio.exceptions import ActivityError, ApplicationError from temporalio.worker import Unsandbo...
173
6,626
posthog
posthog/temporal/tests/test_alerts_activities.py
.py
import uuid import contextlib from datetime import UTC, datetime import pytest from freezegun import freeze_time from unittest.mock import patch import pytest_asyncio from asgiref.sync import sync_to_async from temporalio.exceptions import ApplicationError from temporalio.testing import ActivityEnvironment from post...
933
40,660
posthog
posthog/temporal/tests/conftest.py
.py
import random import signal import asyncio import pytest from django.conf import settings import psycopg import pytest_asyncio import temporalio.worker from asgiref.sync import sync_to_async from psycopg import sql from temporalio.testing import ActivityEnvironment from posthog.models import Organization, Team from...
250
7,908
posthog
posthog/temporal/tests/sync_person_distinct_ids/test_activities.py
.py
"""Integration tests for sync_person_distinct_ids activities.""" import uuid import pytest from asgiref.sync import sync_to_async from posthog.temporal.sync_person_distinct_ids.activities import ( FindOrphanedPersonsInputs, FindOrphanedPersonsResult, LookupPgDistinctIdsInputs, LookupPgDistinctIdsRes...
505
20,226
posthog
posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py
.py
"""Integration tests for SyncPersonDistinctIdsWorkflow with real database operations.""" import uuid import pytest import temporalio.worker from asgiref.sync import sync_to_async from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog.persons_db import persons_db_connect...
298
12,742
posthog
posthog/temporal/tests/sync_person_distinct_ids/conftest.py
.py
"""Shared fixtures and utilities for sync_person_distinct_ids tests.""" import uuid from datetime import datetime import pytest from posthog.clickhouse.client.execute import sync_execute # ============================================================================ # ClickHouse Helper Functions # ==================...
139
4,952
posthog
posthog/temporal/tests/sync_events_retention/test_activities.py
.py
from contextlib import contextmanager import pytest from unittest.mock import patch from asgiref.sync import sync_to_async from temporalio.testing import ActivityEnvironment from posthog.models import Organization, Team from posthog.temporal.sync_events_retention.activities import sync_events_retention from posthog....
101
4,479
posthog
posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
.py
import json import pytest from unittest.mock import AsyncMock, MagicMock, patch from django.test import TestCase from temporalio.exceptions import ActivityError, ApplicationError from posthog.temporal.salesforce_enrichment.usage_workflow import ( EnrichPageResult, SalesforceUsageEnrichmentWorkflow, Usag...
499
20,453
posthog
posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py
.py
import json import datetime as dt from typing import Any import pytest from unittest.mock import AsyncMock, MagicMock, patch from django.test import SimpleTestCase from temporalio.exceptions import ActivityError, ApplicationError from posthog.temporal.salesforce_enrichment.conversations_slack_workflow import ( ...
399
17,020
posthog
posthog/temporal/tests/salesforce_enrichment/test_stripe_workflow.py
.py
import json import datetime as dt import pytest from unittest.mock import AsyncMock, MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.temporal.salesforce_enrichment.stripe_workflow import ( EnrichStripePageInputs, EnrichStripePageResult, Salesf...
573
23,925
posthog
posthog/temporal/tests/ai/test_sync_vectors.py
.py
import json import uuid from datetime import timedelta from itertools import cycle from typing import Annotated, Any import pytest from unittest.mock import patch from django.conf import settings from django.utils import timezone import pytest_asyncio from azure.ai.inference.aio import EmbeddingsClient from azure.ai...
1,121
41,530
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_signal.py
.py
from parameterized import parameterized from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport from posthog.temporal.ai.anomaly_investigation.workflow import ( _MAX_DESCRIPTION_CHARS, _build_signal_description, should_emit_investigation_signal, ) class TestBuildSignalDescription...
69
2,457
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
.py
"""Verifies that the workflow activity persists the agent's verdict onto the AlertCheck.""" import pytest from posthog.test.base import NonAtomicBaseTest from unittest.mock import patch from asgiref.sync import sync_to_async from posthog.schema import AlertState from posthog.temporal.ai.anomaly_investigation.report...
147
5,946
posthog
posthog/temporal/tests/ai/test_checkpoint_compaction_schedule.py
.py
from django.test import override_settings from parameterized import parameterized from posthog.temporal.ai.checkpoint_compaction.schedule import should_register_checkpoint_compaction_schedule class TestCheckpointCompactionSchedule: @parameterized.expand( [ ("US", "US", True), ("E...
25
792
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
.py
from posthog.test.base import BaseTest from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook from posthog.temporal.ai.anomaly_investigation.report import InvestigationHypothesis, InvestigationReport from products.alerts.backend.models.alert import AlertChec...
78
3,670
posthog
posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py
.py
from unittest.mock import patch from django.apps import apps from django.test import TestCase from posthog.models.integration import Integration from posthog.models.organization import Organization from posthog.models.team.team import Team from posthog.models.user import User from posthog.temporal.ai.slack_app import...
118
5,317
posthog
posthog/temporal/tests/ai/test_cascade_team_install.py
.py
from unittest.mock import MagicMock, patch from django.core.cache import cache from django.test import TestCase from parameterized import parameterized from posthog.models.integration import Integration from posthog.models.organization import Organization from posthog.models.team.team import Team from posthog.models...
83
3,168
posthog
posthog/temporal/tests/ai/test_module_integrity.py
.py
from posthog.temporal import ai from posthog.temporal.ai_observability import ( ACTIVITIES as LLM_ANALYTICS_ACTIVITIES, WORKFLOWS as LLM_ANALYTICS_WORKFLOWS, ) from products.signals.backend.temporal import ( ACTIVITIES as SIGNALS_PRODUCT_ACTIVITIES, WORKFLOWS as SIGNALS_PRODUCT_WORKFLOWS, ) class Tes...
251
12,093
posthog
posthog/temporal/tests/ai/test_posthog_code_slack_mention_workflow.py
.py
import pytest from unittest.mock import patch from posthog.temporal.ai.slack_app import posthog_code_slack_mention from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs @pytest.mark.asyncio @pytest.mark.parametrize( "text,patched,expect_classifier", [ # File-only repli...
61
2,310
posthog
posthog/temporal/tests/ai/test_research_agent_activity.py
.py
from uuid import uuid4 import pytest from unittest.mock import AsyncMock, MagicMock, Mock, patch from posthog.temporal.ai.research_agent import ResearchAgentWorkflowInputs, process_research_agent_activity from products.posthog_ai.backend.models.assistant import Conversation from ee.hogai.stream.redis_stream import ...
357
12,975
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_tools.py
.py
from typing import Any from unittest.mock import MagicMock, patch from posthog.schema import BaseMathType, ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery from posthog.caching.insight_result import InsightResult from posthog.temporal.ai.anomaly_investigation.tools import _run_detector_simulatio...
55
2,176
posthog
posthog/temporal/tests/ai/test_classify_task_needs_repo.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai.slack_app.activities.classifiers import classify_task_needs_repo class TestClassifyTaskNeedsRepo: @parameterized.expand( [ ( "product_debug_automation", ...
94
4,643
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_metric_definition.py
.py
from parameterized import parameterized from posthog.temporal.ai.anomaly_investigation.metric_definition import UNAVAILABLE, describe_metric_definition from posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context # A $pageview DAU series filtered to the app's error tracking pages — an insight w...
119
3,952
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
.py
import pytest from unittest.mock import MagicMock, patch from langchain_core.messages import AIMessage from parameterized import parameterized from posthog.temporal.ai.anomaly_investigation.report import salvage_report from posthog.temporal.ai.anomaly_investigation.runner import ( FINAL_REPORT_TOOL_NAME, MAX_...
383
13,504
posthog
posthog/temporal/tests/ai/test_chat_agent_activity.py
.py
import time from uuid import uuid4 import pytest from unittest.mock import AsyncMock, MagicMock, Mock, patch from posthog.schema import AgentMode from posthog.temporal.ai.chat_agent import ( ChatAgentWorkflowInputs, get_conversation_stream_key, process_chat_agent_activity, process_conversation_activi...
316
12,114
posthog
posthog/temporal/tests/ai/test_block_missing_user_github.py
.py
from unittest.mock import MagicMock, patch from django.test import TestCase from posthog.models.integration import Integration from posthog.models.organization import Organization from posthog.models.team.team import Team from posthog.models.user import User from posthog.models.user_integration import UserIntegration...
133
5,695
posthog
posthog/temporal/tests/ai/test_checkpoint_compaction_workflow.py
.py
import uuid import pytest import temporalio.worker from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog.temporal.ai.checkpoint_compaction.types import ( CompactBatchResult, CompactionBatch, CompactionProgress, CompactionS...
79
3,129
posthog
posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py
.py
from datetime import timedelta import pytest from unittest.mock import patch from django.utils import timezone from asgiref.sync import sync_to_async from posthog.temporal.ai.checkpoint_compaction.activities import ( compact_checkpoint_conversations, select_checkpoint_compaction_batch, ) from posthog.tempor...
93
3,609
posthog
posthog/temporal/tests/ai/test_anomaly_investigation_summary.py
.py
import pytest from posthog.temporal.ai.anomaly_investigation.workflow import MAX_SUMMARY_CHARS, _truncate_summary @pytest.mark.parametrize( "input,expected", [ (None, None), ("", None), (" ", None), ("Traffic doubled after a marketing campaign launch.", "Traffic doubled afte...
37
1,229
posthog
posthog/temporal/tests/ai/slack_app/test_attachments.py
.py
from unittest.mock import MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.temporal.ai.slack_app.attachments import build_slack_attachment_prompt_text, prepare_slack_file_artifacts _TYPE_SKIP_SUFFIX = ( "was skipped because only image, PDF, and plain-t...
131
5,835
posthog
posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
.py
import os import uuid import asyncio from datetime import timedelta from typing import Any, Literal import pytest from temporalio import activity from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy from temporalio.testing import WorkflowEnvironment from temporalio.worker import UnsandboxedWo...
498
21,088
posthog
posthog/temporal/tests/ai/slack_app/test_types.py
.py
import pytest from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs, coerce_mention_workflow_inputs def test_coerce_returns_dataclass_unchanged(): inputs = PostHogCodeSlackMentionWorkflowInputs(event={"ts": "1.2"}, integration_id=7, slack_team_id="T1") assert coerce_mention_wo...
46
1,791
posthog
posthog/temporal/tests/ai/slack_app/activities/test_classify_slack_app_model_override.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai.slack_app.activities.classifiers import classify_slack_app_model_override from posthog.temporal.ai.slack_app.posthog_code_slack_mention import POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS from products.slack_app...
160
7,720
posthog
posthog/temporal/tests/ai/slack_app/activities/test_task_creation.py
.py
"""Unit tests for the pure helpers in ``activities.task_creation``. The activity itself is exercised end-to-end in ``products/slack_app/backend/tests/test_followup_forwarding.py`` (it needs the Django DB, Slack mocks, and Temporal client). These tests stay narrow: they exercise ``_build_posthog_code_task_description``...
463
20,842
posthog
posthog/temporal/tests/ai/slack_app/activities/test_model_override_activity.py
.py
"""Gate tests for ``classify_slack_app_model_override_activity``. The classifier's own prompt/parse behaviour is covered in ``posthog/temporal/tests/ai/test_classify_slack_app_model_override.py``. What matters here is what guards it: the feature flag and an unreachable model catalogue, each of which must produce "no o...
84
3,519
posthog
posthog/temporal/tests/ai/slack_app/activities/test_classify_message_is_agent_directed.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.temporal.ai.slack_app.activities.classifiers import classify_message_is_agent_directed from posthog.temporal.ai.slack_app.posthog_code_slack_mention import POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS TASK_TITLE = "Fix the ...
117
6,066
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_client.py
.py
import uuid from collections.abc import Generator from datetime import UTC, datetime, timedelta import pytest from unittest.mock import MagicMock, patch from posthog.errors import InternalCHQueryError from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut from ...
282
11,370
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_activities.py
.py
import time import asyncio import pytest from unittest.mock import MagicMock, patch from posthog.temporal.ingestion_acceptance_test.config import Config from posthog.temporal.ingestion_acceptance_test.types import IngestionAcceptanceTestInput @pytest.fixture def config() -> Config: return Config( api_ho...
89
3,674
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_test_cases_discovery.py
.py
from posthog.temporal.ingestion_acceptance_test.test_cases_discovery import discover_tests def test_discovers_expected_tests() -> None: tests = discover_tests() discovered = {(t.test_class.__name__, t.method_name) for t in tests} # Basic capture tests assert ("TestBasicCapture", "test_capture_event"...
26
1,063
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_config.py
.py
from __future__ import annotations import os import pytest from posthog.temporal.ingestion_acceptance_test.config import DEFAULT_LANE, configured_lanes, load_config FLAT_ENV = { "INGESTION_ACCEPTANCE_TEST_API_HOST": "https://flat.example.com", "INGESTION_ACCEPTANCE_TEST_PROJECT_API_KEY": "phc_flat", "IN...
96
4,094
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_runner.py
.py
from concurrent.futures import ThreadPoolExecutor import pytest from unittest.mock import MagicMock, patch from posthog.temporal.ingestion_acceptance_test.config import Config from posthog.temporal.ingestion_acceptance_test.runner import ( AcceptanceTest, RunningTests, RunningTestSnapshot, TestContext...
233
8,639
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_schedule.py
.py
from __future__ import annotations from datetime import timedelta from django.conf import settings from temporalio.client import ScheduleActionStartWorkflow from posthog.temporal.ingestion_acceptance_test.schedule import WORKFLOW_NAME, _build_schedule, _lane_schedule_id from posthog.temporal.ingestion_acceptance_te...
50
2,053
posthog
posthog/temporal/tests/ingestion_acceptance_test/test_slack.py
.py
import pytest from unittest.mock import MagicMock, patch from posthog.temporal.ingestion_acceptance_test.config import Config from posthog.temporal.ingestion_acceptance_test.results import TestResult, TestSuiteResult from posthog.temporal.ingestion_acceptance_test.runner import RunningTestSnapshot from posthog.tempora...
280
10,514
posthog
posthog/temporal/tests/backfill_group_type_created_at/test_workflows.py
.py
import uuid import pytest import temporalio.worker from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog.temporal.backfill_group_type_created_at.types import ( ApplyBackfillInput, BackfillGroupTypeCreatedAtInput, PlanBackfillI...
159
5,797
posthog
posthog/temporal/tests/backfill_group_type_created_at/test_activities.py
.py
from datetime import UTC, datetime import pytest from posthog.test.base import _create_event, flush_persons_and_events from unittest.mock import patch from asgiref.sync import sync_to_async from posthog.models import Team from posthog.persons_db import persons_db_connection from posthog.temporal.backfill_group_type_...
357
13,684
posthog
posthog/temporal/tests/cleanup_property_definitions/test_workflows.py
.py
import uuid import pytest import temporalio.worker from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog.temporal.cleanup_property_definitions.types import ( CleanupPropertyDefinitionsInput, DeleteClickHousePropertyDefinitionsInpu...
345
13,101
posthog
posthog/temporal/tests/cleanup_property_definitions/test_activities.py
.py
"""Integration tests for cleanup_property_definitions activities.""" import pytest from asgiref.sync import sync_to_async from parameterized import parameterized_class from posthog.models import PropertyDefinition from posthog.temporal.cleanup_property_definitions.activities import ( delete_property_definitions_...
503
18,298
posthog
posthog/temporal/tests/cleanup_property_definitions/conftest.py
.py
"""Shared fixtures and utilities for cleanup_property_definitions tests.""" import uuid from datetime import datetime import pytest from posthog.clickhouse.client.execute import sync_execute def insert_property_definition_to_ch( team_id: int, name: str, property_type: int = 2, last_seen_at: datetim...
87
2,454
posthog
posthog/temporal/tests/usage_report/test_storage.py
.py
"""Tests for the usage report S3 helpers. Pure key-formatting tests don't touch storage. Roundtrip tests hit the real MinIO instance configured for the dev stack — the `minio_workflow_ctx` fixture cleans up its run prefix at teardown so the bucket stays tidy. Error-path tests (failed delete) stay mocked because MinIO ...
198
7,080
posthog
posthog/temporal/tests/usage_report/test_queries_registry.py
.py
"""Static validity checks for the QuerySpec registry. These run cheaply and catch the kind of refactoring mistakes that would otherwise only surface during an aggregation activity in production: duplicated names, multi specs without mappings, two specs writing to the same destination key, etc. """ import ast import i...
149
5,660
posthog
posthog/temporal/tests/usage_report/test_query_activity.py
.py
"""Tests for `run_query_to_s3` — the per-query gather activity. The dispatch path (period vs snapshot) and result persistence are verified end-to-end against real MinIO via the `minio_workflow_ctx` fixture; only the failure-propagation test mocks `object_storage.write` so we can assert it was *never* called. """ impo...
126
4,616
posthog
posthog/temporal/tests/usage_report/test_schedule.py
.py
"""Regression tests for the usage-report schedule builders. The previous version of this code passed `dataclasses.asdict(...)` on `RunUsageReportsInputs` *after* it was migrated to pydantic — that silently raised `TypeError` the first time the worker registered the schedule, and *no* test caught it because nothing in ...
134
5,877
posthog
posthog/temporal/tests/usage_report/test_aggregate_activity.py
.py
"""Tests for the `aggregate_and_chunk_org_reports` Temporal activity. These run end-to-end against real MinIO (via `minio_workflow_ctx`) and a real Postgres test DB (`@pytest.mark.django_db`). Only the "expensive" gather queries (the ClickHouse + ORM functions in `posthog.tasks.usage_report`) are mocked — by seeding c...
408
16,608
posthog
posthog/temporal/tests/usage_report/test_workflow.py
.py
"""End-to-end workflow tests using a Temporal `WorkflowEnvironment`. The activities are mocked at the `@activity.defn` boundary so the workflow's orchestration logic — query fan-out, aggregation, and SQS pointer dispatch — can be verified without standing up real ClickHouse / Postgres / S3. """ import uuid from datet...
184
7,765
posthog
posthog/temporal/tests/usage_report/test_pointer_activity.py
.py
"""Tests for `enqueue_pointer_message` — the activity that sends the single SQS pointer to billing. We mock the SQS producer so the test verifies (a) the queue name we route to, (b) the exact JSON body shape billing will read, and (c) the message attributes. """ import json from datetime import UTC, datetime from typ...
244
9,738
posthog
posthog/temporal/tests/usage_report/test_parity.py
.py
"""End-to-end parity between the legacy Celery `send_all_org_usage_reports` task and the new Temporal `aggregate-and-chunk-org-reports` activity. The same seeded `all_data` is fed into both flows against an in-memory S3 and SQS. The Celery path's per-org SQS payloads are decoded (base64 → gzip → JSON), the Temporal pa...
315
14,970
posthog
posthog/temporal/tests/usage_report/test_aggregator.py
.py
"""Pure-logic tests for the aggregator module. These cover the building blocks the aggregation activity composes: `load_all_data`, `iter_chunk_lines`, `batched`, `build_manifest`, `filter_org_reports`, `filter_orgs_with_usage`, `sort_org_reports`. No Django / Temporal / S3 required. """ import json import dataclasses...
310
11,364
posthog
posthog/temporal/tests/usage_report/conftest.py
.py
"""Shared fixtures for usage report tests. `minio_workflow_ctx` yields a `WorkflowContext` whose `run_id` and `date_str` are unique per test, then cleans up every S3 object written under that prefix. Tests that use it hit real MinIO via `posthog.storage.object_storage` instead of an in-memory fake — that catches conte...
57
1,811
posthog
posthog/temporal/tests/product_analytics/test_upgrade_queries_workflow.py
.py
import uuid from concurrent.futures import ThreadPoolExecutor import pytest from posthog.test.base import QueryMatchingTest, snapshot_postgres_queries_context from django.conf import settings from asgiref.sync import sync_to_async from temporalio.testing import WorkflowEnvironment from temporalio.worker import Unsan...
271
8,710
posthog
posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py
.py
import uuid as uuid_lib import pytest from asgiref.sync import sync_to_async from posthog.personhog_client.fake_client import fake_personhog_client from posthog.temporal.delete_persons.delete_persons_workflow import ( DeletePersonsActivityInputs, PrecleanCohortMembersActivityInputs, delete_persons_activi...
92
3,982
posthog
posthog/temporal/tests/dlq_replay/test_activities.py
.py
import ssl import uuid import asyncio import datetime as dt import pytest from django.conf import settings import aiokafka import pytest_asyncio from aiokafka import TopicPartition from aiokafka.admin import AIOKafkaAdminClient, NewTopic from temporalio.testing import ActivityEnvironment from posthog.temporal.dlq_r...
295
9,406
posthog
posthog/temporal/tests/dlq_replay/test_workflow.py
.py
import uuid from datetime import UTC, datetime, timedelta import pytest import temporalio.worker from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog.temporal.dlq_replay.activities import ( GetTopicPartitionsInputs, ReplayPartiti...
263
10,604
posthog
posthog/temporal/tests/data_modeling/test_run_workflow.py
.py
import os import re import uuid import asyncio import datetime as dt from typing import cast import pytest import unittest.mock from freezegun.api import freeze_time from django.conf import settings from django.test import override_settings import pyarrow as pa import deltalake import pytest_asyncio import temporali...
1,893
78,262
posthog
posthog/temporal/tests/data_modeling/test_preempt_dag_run.py
.py
import uuid import pytest import unittest.mock import pytest_asyncio from temporalio.client import WorkflowExecutionStatus from temporalio.service import RPCError, RPCStatusCode from temporalio.testing import ActivityEnvironment from posthog.sync import database_sync_to_async from posthog.temporal.data_modeling.acti...
222
9,685
posthog
posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
.py
import pytest from unittest.mock import AsyncMock, patch import temporalio.workflow from temporalio.exceptions import WorkflowAlreadyStartedError from posthog.temporal.data_modeling.activities import ( FailMaterializationInputs, SucceedMaterializationResult, fail_materialization_activity, ) from posthog.t...
125
5,684
posthog
posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
.py
"""Incremental materialization, exercised against real deltalite and real Delta tables. Mocked out here: only ``hogql_table`` (so a test controls exactly which rows a "run" returns) and the feature flags. The write path itself is real, because every load-bearing unknown lives in the Rust crate — key matching, duplicat...
434
19,608
posthog
posthog/temporal/tests/data_modeling/test_record_skipped_jobs.py
.py
import dataclasses import pytest import pytest_asyncio from temporalio.testing import ActivityEnvironment from posthog.sync import database_sync_to_async from posthog.temporal.data_modeling.activities.create_data_modeling_job import ( RecordSkippedDataModelingJobsInputs, SkippedDataModelingNode, record_s...
128
4,546
posthog
posthog/temporal/tests/data_modeling/test_incremental_write.py
.py
"""UniqueKeyTracker in isolation: pure pyarrow, no database, no delta table. The activity-level suite proves the tracker is wired into both write paths; these cover the detection logic itself, where the cheap edge cases live (composite keys, the byte cap, a key column missing from the output). """ import pytest impo...
73
2,524
posthog
posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
.py
import asyncio import contextlib from collections.abc import AsyncIterator, Collection, Iterable from io import BytesIO from typing import Any, cast from uuid import uuid4 import pytest import unittest.mock from django.conf import settings from django.test import override_settings import pyarrow as pa import deltala...
1,643
71,006
posthog
posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
.py
import uuid import datetime as dt import pytest import unittest.mock import pytest_asyncio import temporalio.worker import temporalio.exceptions from temporalio import ( activity as temporal_activity, workflow as temporal_workflow, ) from temporalio.testing import WorkflowEnvironment from posthog.sync import...
909
38,140
posthog
posthog/temporal/tests/data_modeling/test_notify_materialization_failure.py
.py
from types import SimpleNamespace from uuid import uuid4 import pytest import unittest.mock from posthog.models import User from posthog.sync import database_sync_to_async from posthog.temporal.data_modeling.activities import ( NotifyDAGMaterializationFailuresInputs, notify_dag_materialization_failures_activi...
289
13,449
posthog
posthog/temporal/tests/data_modeling/test_utils.py
.py
from parameterized import parameterized from posthog.temporal.data_modeling.activities.utils import strip_hostname_from_error class TestStripHostnameFromError: @parameterized.expand( [ # Pattern: "(from host:port)" ( "Code: 159. DB::Exception (from chi-posthog-01.s...
69
2,968
posthog
posthog/temporal/tests/data_modeling/test_log_routing.py
.py
import json import uuid import asyncio import dataclasses from collections.abc import Callable from typing import TYPE_CHECKING, cast import pytest from django.test import override_settings import pytest_asyncio import temporalio.testing from posthog.temporal.common.logger import BACKGROUND_LOGGER_TASKS, configure_...
190
6,459
posthog
posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py
.py
import uuid import datetime as dt import pytest import temporalio.worker from temporalio import ( activity as temporal_activity, workflow as temporal_workflow, ) from temporalio.testing import WorkflowEnvironment from posthog.temporal.data_modeling.activities import GetDAGStructureInputs from posthog.tempora...
128
4,910
posthog
posthog/temporal/tests/data_modeling/conftest.py
.py
import uuid import functools import pytest from django.conf import settings import aioboto3 import pytest_asyncio # The activity-log post_save signal lazily imports posthog.api.advanced_activity_logs # (-> posthog.tasks.usage_report) the first time an ActivityLog row is created. In these # temporal tests the worker...
92
2,931
posthog
posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_export.py
.py
# Golden vectors generated from the Node source of truth (nodejs/.../ml-mirror/pseudonymize.ts). import io from datetime import UTC, date, datetime import pytest import pyarrow.parquet as pq from parameterized import parameterized from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import (...
88
3,231
posthog
posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py
.py
import asyncio import pytest from unittest.mock import MagicMock, patch from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import ( export_scores_partition_activity, list_export_partitions_activity, ) from posthog.temporal.session_replay.surfacing_score_export_sweep.constants import ...
64
2,486
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_score_chunk_pipeline_clickhouse.py
.py
"""End-to-end check that fetch → validate → predict works against real ClickHouse. Booster comes from the `surfacing_booster_path` fixture (prod uses S3). Catches SQL/booster schema drift the static `test_sql_alignment.py` can't — specifically dtype-from-CH bugs. Prereqs that the local CH database needs: * `surfa...
228
10,783
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_activities.py
.py
from __future__ import annotations from datetime import datetime import pytest from unittest import mock import numpy as np import pandas as pd from temporalio.exceptions import ApplicationError from temporalio.testing import ActivityEnvironment from posthog.temporal.session_replay.surfacing_scoring_sweep.activitie...
252
11,037
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_metrics.py
.py
import pytest from unittest.mock import AsyncMock, MagicMock, patch from django.conf import settings from parameterized import parameterized from temporalio.worker import ExecuteActivityInput from posthog.temporal.common.worker import ALL_INTERCEPTOR_CLASSES from posthog.temporal.session_replay.surfacing_scoring_swe...
215
8,867
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_upload_surfacing_model.py
.py
from __future__ import annotations from pathlib import Path import pytest from unittest import mock from django.core.management.base import CommandError from posthog.management.commands.upload_surfacing_model import Command from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES ...
76
3,225
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_publish_scores.py
.py
"""Tests for the Kafka writeback path in `score_chunk_activity`. `_publish_scores` produces JSONEachRow messages onto `KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS` — the same topic ingestion uses. The existing `session_replay_events_mv` merges the partial row into the real session row via `max(surfacing_score)` on the Aggr...
195
9,547
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_features.py
.py
"""Unit tests for `surfacing_scoring_sweep.features.validate_features`. The function is the runtime gate between the CH SELECT and the XGBoost predict — every drift mode that could mis-score sessions in production is covered here. Tests are pure pandas, no CH or xgboost in the picture. `validate_features` and `featur...
238
10,508
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_scorer.py
.py
"""Integration tests for `surfacing_scoring_sweep.scorer`. Boosters come from the shared `surfacing_booster_path` fixture (binary:logistic on `FEATURE_RANGES.keys()`) or are trained inline via `train_synthetic_booster` when a test needs a custom shape (regression objective, custom feature set, etc). Singleton cleanup...
260
11,739
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_schedule.py
.py
from __future__ import annotations from django.conf import settings from temporalio.client import ScheduleActionStartWorkflow from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import ( SCHEDULE_INTERVAL, WORKFLOW_EXECUTION_TIMEOUT, WORKFLOW_NAME, ) from posthog.temporal.session_repla...
50
2,034
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_alignment.py
.py
"""CI guard: fetch_features_sql(), FEATURE_RANGES, and a synthetic booster stay aligned. Prod model lives in S3; `assert_serving_schema_parity` re-runs at worker boot. """ from __future__ import annotations from pathlib import Path import pytest import xgboost as xgb from posthog.temporal.session_replay.surfacing...
96
4,275
posthog
posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py
.py
from __future__ import annotations import uuid import pytest from unittest import mock import temporalio.worker from temporalio import activity from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import WORKFL...
215
8,340