Skip to content

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

chore(tests): retire completed migration tests (#84239)

Paul D'Ambrade7e4ba5ad96
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.md
index bea91313d43c..7a9f33e3a9bd 100644
--- a/.agents/skills/django-migrations/SKILL.md
+++ b/.agents/skills/django-migrations/SKILL.md
@@ -28,6 +28,14 @@ To retire a model/table:
Full guide: `safe-django-migrations.md` (`## Dropping Tables`, `### Removing a whole product or app`). Deleting a migration your branch added but never merged to master is allowed (regenerating).
+## Retire dedicated migration tests
+
+A data migration test protects the rollout, not the permanent behavior of the product. Remove the dedicated test after all supported environments have applied the migration, the rollback window has closed, and no supported upgrade still relies on the old data state.
+
+Delete an expired test instead of marking it skipped. Keep the migration file. Fresh-schema CI still checks that the complete migration chain applies.
+
+Do not apply this rule to migration tooling, migration safety checks, reusable backfill systems, or backfills that people can still run.
+
## Workflow
1. **Classify** the change as additive (new nullable column, new table) or risky (drop/rename, `NOT NULL`, indexes, constraints, large data updates, model moves). A change is also risky if it touches a [hot table](#hot-table-hazard), regardless of how additive it looks. See also the [cross-language `NOT NULL` hazard](#cross-language-not-null-hazard) below.
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index 93fd06f04ac1..7b2e5db958ea 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -91,6 +91,7 @@ Escalating to the next rung is the last resort, not the default.
- testing `transaction.on_commit` side effects → use `TestCase` + `self.captureOnCommitCallbacks(execute=True)`.
- needing a connection visible across a real separate thread (`thread_sensitive`) → `async_to_sync(...)`, not `asyncio.run(...)`.
Use `TransactionTestCase` only when the regression genuinely requires committed transaction boundaries that `TestCase` hides.
+- **Dedicated data migration tests are temporary.** Remove a dedicated test after every supported environment has applied the migration, the rollback window has closed, and no supported upgrade relies on the old data state. Delete the expired test instead of marking it skipped. Keep the migration file and tests for migration tooling, safety checks, reusable backfill systems, and backfills people can still run. Use `/django-migrations` for the migration safety workflow.
- **DRF input-validation belongs in a `SimpleTestCase`, not an `APIBaseTest` round-trip.**
A test that posts a malformed body to an endpoint and asserts a 400 pays for `APIBaseTest` to build an Organization + Team + User in Postgres and wrap the test in a transaction — just to exercise validation that runs entirely in memory.
DRF field validators (`required`, type coercion, `choices`, `min/max`, regex) and `validate_<field>` methods run inside `Serializer(data=...).is_valid()` with no database and no request: field-level validation happens in `to_internal_value`, _before_ the object-level `validate()` that typically needs `self.context`. So an invalid-field case never reaches the DB-touching code.
diff --git a/docs/published/handbook/engineering/conventions/backend-coding.md b/docs/published/handbook/engineering/conventions/backend-coding.md
index 94358cb838b0..3eb9087c6315 100644
--- a/docs/published/handbook/engineering/conventions/backend-coding.md
+++ b/docs/published/handbook/engineering/conventions/backend-coding.md
@@ -133,6 +133,14 @@ A good test should:
- They give greater confidence (because you avoid the mistake of just testing a mock) but they're slower
- They are generally less brittle in response to changes because they test at a higher level than developer tests (e.g. they test a Django API not a class used inside it)
+#### Temporary migration tests
+
+A dedicated data migration test protects the rollout. Remove the test after the migration has run in every supported environment, the rollback window has closed, and no supported upgrade still relies on the old data state.
+
+Delete an expired migration test instead of marking it skipped. Keep the migration file. Fresh-schema CI continues to check that the migration chain applies.
+
+Keep tests for migration tooling, migration safety checks, reusable backfill systems, and backfills that people can still run.
+
### Dataclasses
Prefer a small dataclass over a tuple when returning or passing multiple values: always when two or more elements share a type (callers can silently swap them, e.g. `(start, end)` timestamps or `(username, password)` credentials), and when there are roughly 3+ elements, where positional access hurts readability.
diff --git a/ee/migrations/test/test_migration_0051.py b/ee/migrations/test/test_migration_0051.py
deleted file mode 100644
index 66d25e5a8454..000000000000
--- a/ee/migrations/test/test_migration_0051.py
+++ /dev/null
@@ -1,112 +0,0 @@
-import importlib
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-
-from parameterized import parameterized
-
-from ee.models.rbac.access_control import AccessControl
-from ee.models.rbac.role import Role
-
-migration_module = importlib.import_module("ee.migrations.0051_backfill_ai_observability_clusters_access_control")
-backfill_ai_observability_clusters_access_control = migration_module.backfill_ai_observability_clusters_access_control
-
-
-class TestBackfillAIObservabilityClustersAccessControl(BaseTest):
- @parameterized.expand(
- [
- ("member_scoped",),
- ("role_scoped",),
- ("org_default",),
- ]
- )
- def test_backfills_resource_wide_row(self, case):
- role = (
- Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None
- )
- scope_kwargs = {
- "organization_member": self.organization_membership if case == "member_scoped" else None,
- "role": role,
- }
-
- AccessControl.objects.create(
- team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs
- )
-
- backfill_ai_observability_clusters_access_control(apps, None)
-
- backfilled = AccessControl.objects.filter(
- resource="ai_observability_clusters", team=self.team, **scope_kwargs
- ).first()
- assert backfilled is not None
- assert backfilled.access_level == "viewer"
-
- def test_does_not_touch_other_resources(self):
- AccessControl.objects.create(
- team=self.team,
- resource="dataset",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_ai_observability_clusters_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="ai_observability_clusters").exists()
-
- def test_ignores_object_scoped_llm_analytics_rows(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id="123",
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_ai_observability_clusters_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="ai_observability_clusters").exists()
-
- def test_does_not_overwrite_existing_row(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
- AccessControl.objects.create(
- team=self.team,
- resource="ai_observability_clusters",
- resource_id=None,
- access_level="none",
- organization_member=self.organization_membership,
- )
-
- backfill_ai_observability_clusters_access_control(apps, None)
-
- rows = AccessControl.objects.filter(
- resource="ai_observability_clusters", organization_member=self.organization_membership
- )
- assert rows.count() == 1
- row = rows.first()
- assert row is not None
- assert row.access_level == "none"
-
- def test_idempotent_on_repeat_run(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id=None,
- access_level="viewer",
- organization_member=self.organization_membership,
- )
-
- backfill_ai_observability_clusters_access_control(apps, None)
- backfill_ai_observability_clusters_access_control(apps, None)
-
- rows = AccessControl.objects.filter(
- resource="ai_observability_clusters", organization_member=self.organization_membership
- )
- assert rows.count() == 1
diff --git a/ee/migrations/test/test_migration_0052.py b/ee/migrations/test/test_migration_0052.py
deleted file mode 100644
index 36a8a3f74da5..000000000000
--- a/ee/migrations/test/test_migration_0052.py
+++ /dev/null
@@ -1,109 +0,0 @@
-import importlib
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-
-from parameterized import parameterized
-
-from ee.models.rbac.access_control import AccessControl
-from ee.models.rbac.role import Role
-
-migration_module = importlib.import_module("ee.migrations.0052_backfill_llm_skill_access_control")
-backfill_llm_skill_access_control = migration_module.backfill_llm_skill_access_control
-
-
-class TestBackfillLlmSkillAccessControl(BaseTest):
- @parameterized.expand(
- [
- ("member_scoped",),
- ("role_scoped",),
- ("org_default",),
- ]
- )
- def test_backfills_resource_wide_row(self, case):
- role = (
- Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None
- )
- scope_kwargs = {
- "organization_member": self.organization_membership if case == "member_scoped" else None,
- "role": role,
- }
-
- AccessControl.objects.create(
- team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs
- )
-
- backfill_llm_skill_access_control(apps, None)
-
- backfilled = AccessControl.objects.filter(resource="llm_skill", team=self.team, **scope_kwargs).first()
- assert backfilled is not None
- assert backfilled.access_level == "viewer"
-
- def test_ignores_object_scoped_llm_analytics_rows(self):
- # A resource_id-scoped llm_analytics row is a per-object grant on one of its OTHER children
- # (dataset/evaluation/tagger/...) - those are always looked up under their own resource
- # string, never through llm_analytics, so this row has nothing to do with llm_skill.
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id="123",
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_skill_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="llm_skill").exists()
-
- def test_does_not_touch_other_resources(self):
- AccessControl.objects.create(
- team=self.team,
- resource="dataset",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_skill_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="llm_skill").exists()
-
- def test_does_not_overwrite_existing_row(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
- AccessControl.objects.create(
- team=self.team,
- resource="llm_skill",
- resource_id=None,
- access_level="none",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_skill_access_control(apps, None)
-
- rows = AccessControl.objects.filter(resource="llm_skill", organization_member=self.organization_membership)
- assert rows.count() == 1
- row = rows.first()
- assert row is not None
- assert row.access_level == "none"
-
- def test_idempotent_on_repeat_run(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id=None,
- access_level="viewer",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_skill_access_control(apps, None)
- backfill_llm_skill_access_control(apps, None)
-
- rows = AccessControl.objects.filter(resource="llm_skill", organization_member=self.organization_membership)
- assert rows.count() == 1
diff --git a/ee/migrations/test/test_migration_0053.py b/ee/migrations/test/test_migration_0053.py
deleted file mode 100644
index 69de0beac2c9..000000000000
--- a/ee/migrations/test/test_migration_0053.py
+++ /dev/null
@@ -1,118 +0,0 @@
-import importlib
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-
-from parameterized import parameterized
-
-from ee.models.rbac.access_control import AccessControl
-from ee.models.rbac.role import Role
-
-migration_module = importlib.import_module("ee.migrations.0053_backfill_tagger_access_control")
-backfill_tagger_access_control = migration_module.backfill_tagger_access_control
-
-
-class TestBackfillTaggerAccessControl(BaseTest):
- def _scope_kwargs(self, case):
- role = (
- Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None
- )
- return {
- "organization_member": self.organization_membership if case == "member_scoped" else None,
- "role": role,
- }
-
- @parameterized.expand(
- [
- ("member_scoped",),
- ("role_scoped",),
- ("org_default",),
- ]
- )
- def test_backfills_resource_wide_row(self, case):
- scope_kwargs = self._scope_kwargs(case)
-
- AccessControl.objects.create(
- team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs
- )
-
- backfill_tagger_access_control(apps, None)
-
- backfilled = AccessControl.objects.filter(resource="tagger", team=self.team, **scope_kwargs).first()
- assert backfilled is not None
- assert backfilled.access_level == "viewer"
-
- def test_does_not_touch_other_resources(self):
- AccessControl.objects.create(
- team=self.team,
- resource="dataset",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_tagger_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="tagger").exists()
-
- def test_ignores_object_scoped_llm_analytics_rows(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id="123",
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_tagger_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="tagger").exists()
-
- def test_does_not_overwrite_existing_row(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
- AccessControl.objects.create(
- team=self.team,
- resource="tagger",
- resource_id=None,
- access_level="none",
- organization_member=self.organization_membership,
- )
-
- backfill_tagger_access_control(apps, None)
-
- rows = AccessControl.objects.filter(resource="tagger", organization_member=self.organization_membership)
-
- assert rows.count() == 1
- row = rows.first()
- assert row is not None
- assert row.access_level == "none"
-
- @parameterized.expand(
- [
- ("member_scoped",),
- ("role_scoped",),
- ("org_default",),
- ]
- )
- def test_idempotent_on_repeat_run(self, case):
- # organization_member/role are nullable, and Postgres unique constraints treat NULLs as
- # distinct, so the org_default (both-None) case would silently duplicate on a second run
- # if the migration ever stopped looking up the existing row before creating one.
- scope_kwargs = self._scope_kwargs(case)
-
- AccessControl.objects.create(
- team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs
- )
-
- backfill_tagger_access_control(apps, None)
- backfill_tagger_access_control(apps, None)
-
- rows = AccessControl.objects.filter(resource="tagger", team=self.team, **scope_kwargs)
- assert rows.count() == 1
diff --git a/ee/migrations/test/test_migration_0054.py b/ee/migrations/test/test_migration_0054.py
deleted file mode 100644
index a9db854e1f9d..000000000000
--- a/ee/migrations/test/test_migration_0054.py
+++ /dev/null
@@ -1,118 +0,0 @@
-import importlib
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-
-from parameterized import parameterized
-
-from ee.models.rbac.access_control import AccessControl
-from ee.models.rbac.role import Role
-
-migration_module = importlib.import_module("ee.migrations.0054_backfill_llm_playground_access_control")
-backfill_llm_playground_access_control = migration_module.backfill_llm_playground_access_control
-
-
-class TestBackfillLlmPlaygroundAccessControl(BaseTest):
- def _scope_kwargs(self, case):
- role = (
- Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None
- )
- return {
- "organization_member": self.organization_membership if case == "member_scoped" else None,
- "role": role,
- }
-
- @parameterized.expand(
- [
- ("member_scoped",),
- ("role_scoped",),
- ("org_default",),
- ]
- )
- def test_backfills_resource_wide_row(self, case):
- scope_kwargs = self._scope_kwargs(case)
-
- AccessControl.objects.create(
- team=self.team, resource="llm_analytics", resource_id=None, access_level="none", **scope_kwargs
- )
-
- backfill_llm_playground_access_control(apps, None)
-
- backfilled = AccessControl.objects.filter(resource="llm_playground", team=self.team, **scope_kwargs).first()
- assert backfilled is not None
- assert backfilled.access_level == "none"
-
- def test_does_not_touch_other_resources(self):
- AccessControl.objects.create(
- team=self.team,
- resource="dataset",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_playground_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="llm_playground").exists()
-
- def test_ignores_object_scoped_llm_analytics_rows(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id="123",
- access_level="editor",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_playground_access_control(apps, None)
-
- assert not AccessControl.objects.filter(resource="llm_playground").exists()
-
- def test_does_not_overwrite_existing_row(self):
- AccessControl.objects.create(
- team=self.team,
- resource="llm_analytics",
- resource_id=None,
- access_level="editor",
- organization_member=self.organization_membership,
- )
- AccessControl.objects.create(
- team=self.team,
- resource="llm_playground",
- resource_id=None,
- access_level="none",
- organization_member=self.organization_membership,
- )
-
- backfill_llm_playground_access_control(apps, None)
-
- rows = AccessControl.objects.filter(resource="llm_playground", organization_member=self.organization_membership)
-
- assert rows.count() == 1
- row = rows.first()
- assert row is not None
- assert row.access_level == "none"
-
- @parameterized.expand(
- [
- ("member_scoped",),
- ("role_scoped",),
- ("org_default",),
- ]
- )
- def test_idempotent_on_repeat_run(self, case):
- # organization_member/role are nullable, and Postgres unique constraints treat NULLs as
- # distinct, so the org_default (both-None) case would silently duplicate on a second run
- # if the migration ever stopped looking up the existing row before creating one.
- scope_kwargs = self._scope_kwargs(case)
-
- AccessControl.objects.create(
- team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs
- )
-
- backfill_llm_playground_access_control(apps, None)
- backfill_llm_playground_access_control(apps, None)
-
- rows = AccessControl.objects.filter(resource="llm_playground", team=self.team, **scope_kwargs)
- assert rows.count() == 1
diff --git a/ee/migrations/test/test_migration_0058.py b/ee/migrations/test/test_migration_0058.py
deleted file mode 100644
index e68c05216f8a..000000000000
--- a/ee/migrations/test/test_migration_0058.py
+++ /dev/null
@@ -1,70 +0,0 @@
-import importlib
-from types import SimpleNamespace
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-from django.db import connection
-
-from posthog.models.identity_provider_config import IdentityProviderConfig
-from posthog.models.organization_domain import OrganizationDomain
-from posthog.models.user import User
-
-from ee.models.scim_provisioned_user import SCIMProvisionedUser
-
-migration_module = importlib.import_module("ee.migrations.0058_backfill_scim_provisioned_user_config")
-backfill_scim_provisioned_user_config = migration_module.backfill_scim_provisioned_user_config
-
-SCHEMA_EDITOR = SimpleNamespace(connection=connection)
-
-
-class TestBackfillSCIMProvisionedUserConfig(BaseTest):
- def setUp(self):
- super().setUp()
- self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)
- self.domain = OrganizationDomain.objects.create(
- organization=self.organization,
- domain="example.com",
- verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
- )
- self.provisioned_user = User.objects.create_user(
- email="[email protected]", password=None, first_name="Provisioned"
- )
-
- def _create_record(self, user: User, domain: OrganizationDomain) -> SCIMProvisionedUser:
- return SCIMProvisionedUser.objects.create(
- user=user,
- organization_domain=domain,
- identity_provider=SCIMProvisionedUser.IdentityProvider.OKTA,
- username=user.email,
- )
-
- def test_backfills_the_config_linked_to_the_record_domain(self):
- record = self._create_record(self.provisioned_user, self.domain)
-
- backfill_scim_provisioned_user_config(apps, SCHEMA_EDITOR)
-
- record.refresh_from_db()
- assert record.identity_provider_config_id == self.config.id
-
- def test_leaves_a_second_record_for_the_same_config_on_its_domain_key(self):
- # Two domains sharing a config used to serve SCIM separately, so one user can hold a record
- # per domain. Claiming both for the config would break the unique constraint added in 0059.
- second_domain = OrganizationDomain.objects.create(
- organization=self.organization,
- domain="partner.example.com",
- verified_at="2024-01-01T00:00:00Z",
- identity_provider_config=self.config,
- )
- first_record = self._create_record(self.provisioned_user, self.domain)
- second_record = self._create_record(self.provisioned_user, second_domain)
-
- backfill_scim_provisioned_user_config(apps, SCHEMA_EDITOR)
-
- first_record.refresh_from_db()
- second_record.refresh_from_db()
- assert [first_record.identity_provider_config_id, second_record.identity_provider_config_id] == [
- self.config.id,
- None,
- ]
diff --git a/posthog/test/test_migration_0218.py b/posthog/test/test_migration_0218.py
deleted file mode 100644
index 1b7e705e66eb..000000000000
--- a/posthog/test/test_migration_0218.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-from django.db import IntegrityError
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class TaggedItemsUniquenessTest(NonAtomicTestMigrations):
- migrate_from = "0217_team_primary_dashboard"
- migrate_to = "0218_uniqueness_constraint_tagged_items"
-
- def setUpBeforeMigration(self, apps):
- Dashboard = apps.get_model("posthog", "Dashboard")
- Insight = apps.get_model("posthog", "Insight")
- Tag = apps.get_model("posthog", "Tag")
- TaggedItem = apps.get_model("posthog", "TaggedItem")
-
- # Setup
- self.tag = Tag.objects.create(name="tag", team_id=self.team.id)
- self.dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")
- self.insight = Insight.objects.create(team_id=self.team.id, name="XYZ", dashboard=self.dashboard)
-
- # Before migration you can create duplicate tagged items
- taggeditem_1 = TaggedItem.objects.create(dashboard_id=self.dashboard.id, tag_id=self.tag.id)
- taggeditem_2 = TaggedItem.objects.create(dashboard_id=self.dashboard.id, tag_id=self.tag.id)
- self.assertNotEqual(taggeditem_1.id, taggeditem_2.id)
-
- # More duplicate tagged items to ensure deduping works properly
- TaggedItem.objects.create(insight_id=self.insight.id, tag_id=self.tag.id)
- TaggedItem.objects.create(insight_id=self.insight.id, tag_id=self.tag.id)
-
- def test_taggeditems_uniqueness(self):
- TaggedItem = self.apps.get_model("posthog", "TaggedItem") # type: ignore
-
- self.assertEqual(TaggedItem.objects.all().count(), 2)
-
- with self.assertRaises(IntegrityError):
- TaggedItem.objects.create(dashboard_id=self.dashboard.id, tag_id=self.tag.id)
-
- def tearDown(self):
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Dashboard.objects.filter(id=self.dashboard.id).delete()
- super().tearDown()
diff --git a/posthog/test/test_migration_0219.py b/posthog/test/test_migration_0219.py
deleted file mode 100644
index 504f7a430e02..000000000000
--- a/posthog/test/test_migration_0219.py
+++ /dev/null
@@ -1,122 +0,0 @@
-import pytest
-from posthog.test.base import TestMigrations
-
-from django.db.models import Q
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class TagsTestCase(TestMigrations):
- migrate_from = "0218_uniqueness_constraint_tagged_items"
- migrate_to = "0219_migrate_tags_v2"
- assert_snapshots = True
-
- def setUpBeforeMigration(self, apps):
- Dashboard = apps.get_model("posthog", "Dashboard")
- Insight = apps.get_model("posthog", "Insight")
- Tag = apps.get_model("posthog", "Tag")
- TaggedItem = apps.get_model("posthog", "TaggedItem")
- Team = apps.get_model("posthog", "Team")
- Organization = apps.get_model("posthog", "Organization")
-
- # Setup
- tag = Tag.objects.create(name="existing tag", team_id=self.team.id)
- self.dashboard = Dashboard.objects.create(
- team_id=self.team.id,
- name="private dashboard",
- deprecated_tags=["a", "b", "c", "a", "b", "existing tag", "", " ", None],
- )
- filter_dict = {
- "events": [{"id": "$pageview"}],
- "properties": [{"key": "$browser", "value": "Mac OS X"}],
- }
- self.insight_with_tags = Insight.objects.create(
- dashboard=self.dashboard,
- filters=filter_dict,
- team_id=self.team.id,
- deprecated_tags=["c", "d", "d", "existing tag"],
- )
- self.insight_without_tags = Insight.objects.create(
- dashboard=self.dashboard, filters=filter_dict, team_id=self.team.id
- )
- TaggedItem.objects.create(tag=tag, insight_id=self.insight_with_tags.id)
-
- # Setup for batched tags
- self.org2 = Organization.objects.create(name="o1")
- self.team2 = Team.objects.create(
- organization=self.org2,
- api_token="token12345",
- test_account_filters=[
- {
- "key": "email",
- "value": "@posthog.com",
- "operator": "not_icontains",
- "type": "person",
- }
- ],
- )
- self.team2_total_insights = 1_001
- tag2 = Tag.objects.create(name="existing tag", team_id=self.team2.id)
- self.dashboard2 = Dashboard.objects.create(team_id=self.team2.id, name="dashboard")
- Insight.objects.bulk_create(
- [
- Insight(
- dashboard=self.dashboard2,
- filters=filter_dict,
- team_id=self.team2.id,
- deprecated_tags=[_tag, "existing tag"],
- )
- for _tag in range(self.team2_total_insights)
- ],
- ignore_conflicts=True,
- batch_size=1000,
- )
- TaggedItem.objects.create(
- tag=tag2,
- insight_id=Insight.objects.filter(team_id=self.team2.id).first().id,
- )
-
- def test_tags_migrated(self):
- Tag = self.apps.get_model("posthog", "Tag") # type: ignore
- TaggedItem = self.apps.get_model("posthog", "TaggedItem") # type: ignore
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Insight = self.apps.get_model("posthog", "Insight") # type: ignore
-
- dashboard = Dashboard.objects.get(id=self.dashboard.id)
- self.assertEqual(
- list(dashboard.tagged_items.order_by("tag__name").values_list("tag__name", flat=True)),
- ["a", "b", "c", "existing tag"],
- )
-
- insight_with_tags = Insight.objects.get(id=self.insight_with_tags.id)
- self.assertEqual(
- list(insight_with_tags.tagged_items.order_by("tag__name").values_list("tag__name", flat=True)),
- ["c", "d", "existing tag"],
- )
-
- insight_without_tags = Insight.objects.get(id=self.insight_without_tags.id)
- self.assertEqual(insight_without_tags.tagged_items.count(), 0)
-
- self.assertEqual(
- sorted(Tag.objects.filter(team_id=self.team.id).all().values_list("name", flat=True)),
- ["a", "b", "c", "d", "existing tag"],
- )
-
- # By the end of the migration, the total count for team 2 should be
- # Tags = team2_total_insights + 2 + team1_tags
- # TaggedItems = team2_total_insights * 3 + team1_taggeditems
- self.assertEqual(Tag.objects.all().count(), self.team2_total_insights + 1 + 5)
- self.assertEqual(TaggedItem.objects.all().count(), self.team2_total_insights * 2 + 7)
-
- def tearDown(self):
- Insight = self.apps.get_model("posthog", "Insight") # type: ignore
- Insight.objects.filter(
- Q(id__in=[self.insight_with_tags.id, self.insight_without_tags.id]) | Q(dashboard_id=self.dashboard2.id)
- ).delete()
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Dashboard.objects.filter(id=self.dashboard.id).delete()
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- Team.objects.get(id=self.team2.id).delete()
- Organization = self.apps.get_model("posthog", "Organization") # type: ignore
- Organization.objects.get(id=self.org2.id).delete()
- super().tearDown()
diff --git a/posthog/test/test_migration_0220.py b/posthog/test/test_migration_0220.py
deleted file mode 100644
index c1454c2b9d83..000000000000
--- a/posthog/test/test_migration_0220.py
+++ /dev/null
@@ -1,96 +0,0 @@
-import pytest
-from posthog.test.base import TestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class TagsTestCase(TestMigrations):
- migrate_from = "0219_migrate_tags_v2"
- migrate_to = "0220_backfill_primary_dashboards"
- assert_snapshots = True
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- Dashboard = apps.get_model("posthog", "Dashboard")
- Team = apps.get_model("posthog", "Team")
-
- org = Organization.objects.create(name="o1")
-
- # CASE 1:
- # Team with an existing primary dashboard, and non primary dashboards
- # Expect: t1.primary_dashboard = d2 (even though d1 is created first)
- team_1 = Team.objects.create(name="t1", organization=org)
- Dashboard.objects.create(name="d1", team=team_1)
- dashboard_2 = Dashboard.objects.create(name="d2", team=team_1)
- team_1.primary_dashboard = dashboard_2
- team_1.save()
-
- # CASE 2:
- # Team with no dashboards
- # Expect: t2.primary_dashboard = None
- Team.objects.create(name="t2", organization=org)
-
- # CASE 3:
- # Team with multiple pinned and non pinned dashboards, and no primary set
- # Expect: t3.primary_dashboard = d4 (even though d3 is created first)
- team_3 = Team.objects.create(name="t3", organization=org)
- Dashboard.objects.create(name="d3", team=team_3, pinned=False)
- Dashboard.objects.create(name="d4", team=team_3, pinned=True)
- Dashboard.objects.create(name="d5", team=team_3, pinned=True)
-
- # CASE 4:
- # Team with multiple non-pinned dashboards, and no primary set
- # Expect: t4.primary_dashboard = d6
- team_4 = Team.objects.create(name="t4", organization=org)
- Dashboard.objects.create(name="d6", team=team_4)
- Dashboard.objects.create(name="d7", team=team_4)
-
- # BATCH CASE
- teams = Team.objects.bulk_create(
- [Team(name=f"batch_team-{team_number + 10}", organization=org) for team_number in range(501)]
- )
- Dashboard.objects.bulk_create(
- [
- Dashboard(name=f"batch_dashboard-{dashboard_number + 10}", team=team)
- for dashboard_number, team in enumerate(teams)
- ]
- )
-
- def test_backfill_primary_dashboard(self):
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Team = self.apps.get_model("posthog", "Team") # type: ignore
-
- # CASE 1:
- self.assertEqual(
- Team.objects.get(name="t1").primary_dashboard.id,
- Dashboard.objects.get(name="d2").id,
- )
-
- # CASE 2:
- self.assertEqual(Team.objects.get(name="t2").primary_dashboard, None)
-
- # CASE 3:
- self.assertEqual(
- Team.objects.get(name="t3").primary_dashboard.id,
- Dashboard.objects.get(name="d4").id,
- )
-
- # CASE 4:
- self.assertEqual(
- Team.objects.get(name="t4").primary_dashboard.id,
- Dashboard.objects.get(name="d6").id,
- )
-
- # BATCH CASE
- teams = Team.objects.filter(name__startswith="batch_team-")
- self.assertEqual(teams.count(), 501)
- for team in teams:
- team_number = team.name.split("-")[1]
- self.assertEqual(team.primary_dashboard.name.split("-")[1], team_number)
-
- def tearDown(self):
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Dashboard.objects.all().delete()
- Team.objects.all().delete()
- super().tearDown()
diff --git a/posthog/test/test_migration_0222.py b/posthog/test/test_migration_0222.py
deleted file mode 100644
index 1d418b27f498..000000000000
--- a/posthog/test/test_migration_0222.py
+++ /dev/null
@@ -1,97 +0,0 @@
-import pytest
-from posthog.test.base import TestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class DeletedPrimaryDashboardTestCase(TestMigrations):
- migrate_from = "0221_add_activity_log_model"
- migrate_to = "0222_fix_deleted_primary_dashboards"
- assert_snapshots = True
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- Dashboard = apps.get_model("posthog", "Dashboard")
- Team = apps.get_model("posthog", "Team")
-
- org = Organization.objects.create(name="o1")
-
- # CASE 1:
- # Team with an existing primary dashboard that's not deleted isn't affected
- # Expect: t1.primary_dashboard = d1
- team_1 = Team.objects.create(name="t1", organization=org)
- dashboard_1 = Dashboard.objects.create(name="d1", team=team_1)
- team_1.primary_dashboard = dashboard_1
- team_1.save()
-
- # CASE 2:
- # Team with a deleted primary dashboard and no other dashboards is set to None
- # Expect: t2.primary_dashboard = None
- team_2 = Team.objects.create(name="t2", organization=org)
- dashboard_2 = Dashboard.objects.create(name="d2", team=team_2, deleted=True)
- team_2.primary_dashboard = dashboard_2
- team_2.save()
-
- # CASE 3:
- # Team with a deleted primary dashboard and other dashboards is set to the first dashboard
- # Expect: t3.primary_dashboard = d4
- team_3 = Team.objects.create(name="t3", organization=org)
- dashboard_3 = Dashboard.objects.create(name="d3", team=team_3, deleted=True)
- team_3.primary_dashboard = dashboard_3
- team_3.save()
- Dashboard.objects.create(name="d4", team=team_3)
-
- # CASE 4:
- # Team with no primary dashboards is set to the first non deleted dashboard
- # Expect: t4.primary_dashboard = d6 (even though d5 is created first)
- team_4 = Team.objects.create(name="t4", organization=org)
- Dashboard.objects.create(name="d5", team=team_4, deleted=True)
- Dashboard.objects.create(name="d6", team=team_4)
-
- # CASE 5:
- # Team with a deleted primary dashboard is set to the first non-deleted dashboard
- # Expect: t5.primary_dashboard = d9
- team_5 = Team.objects.create(name="t5", organization=org)
- dashboard_7 = Dashboard.objects.create(name="d7", team=team_5, deleted=True)
- team_5.primary_dashboard = dashboard_7
- team_5.save()
- Dashboard.objects.create(name="d8", team=team_5, deleted=True)
- Dashboard.objects.create(name="d9", team=team_5)
-
- def test_backfill_primary_dashboard(self):
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Team = self.apps.get_model("posthog", "Team") # type: ignore
-
- # CASE 1:
- self.assertEqual(
- Team.objects.get(name="t1").primary_dashboard.id,
- Dashboard.objects.get(name="d1").id,
- )
-
- # CASE 2:
- self.assertEqual(Team.objects.get(name="t2").primary_dashboard, None)
-
- # CASE 3:
- self.assertEqual(
- Team.objects.get(name="t3").primary_dashboard.id,
- Dashboard.objects.get(name="d4").id,
- )
-
- # CASE 4:
- self.assertEqual(
- Team.objects.get(name="t4").primary_dashboard.id,
- Dashboard.objects.get(name="d6").id,
- )
-
- # CASE 5:
- self.assertEqual(
- Team.objects.get(name="t5").primary_dashboard.id,
- Dashboard.objects.get(name="d9").id,
- )
-
- def tearDown(self):
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Dashboard.objects.all().delete()
- Team.objects.all().delete()
- super().tearDown()
diff --git a/posthog/test/test_migration_0227.py b/posthog/test/test_migration_0227.py
deleted file mode 100644
index a218a3d27c5b..000000000000
--- a/posthog/test/test_migration_0227.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import pytest
-from posthog.test.base import TestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class CreatingDashboardTilesTestCase(TestMigrations):
- migrate_from = "0226_longer_action_slack_message_format"
- migrate_to = "0227_add_dashboard_tiles"
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- Dashboard = apps.get_model("posthog", "Dashboard")
- Insight = apps.get_model("posthog", "Insight")
- Team = apps.get_model("posthog", "Team")
-
- org = Organization.objects.create(name="o1")
- team = Team.objects.create(name="t1", organization=org)
-
- # CASE 1:
- # dashboard with no insights
- # Expect: no tiles for this dashboard
- Dashboard.objects.create(name="d1", team=team)
-
- # CASE 2:
- # dashboard no filters with 2 tiles
- # Expect: 2 tiles with layout and color
- dashboard_2 = Dashboard.objects.create(name="d2", team=team)
- Insight.objects.create(
- team=team,
- filters={"insight": "TRENDS", "date_from": "-7d"},
- dashboard=dashboard_2,
- layouts={"some": "content"},
- color="blue",
- name="blue",
- )
- Insight.objects.create(
- team=team,
- filters={"insight": "TRENDS", "date_from": "-14d"},
- dashboard=dashboard_2,
- layouts={"some": "different content"},
- color="red",
- name="red",
- )
-
- # CASE 3:
- # soft deleted insight with dashboard
- # Expect: no tiles
- dashboard_3 = Dashboard.objects.create(name="d3", team=team, deleted=False)
- Insight.objects.create(
- team=team,
- filters={"insight": "TRENDS", "date_from": "-7d"},
- dashboard=dashboard_3,
- deleted=True,
- )
-
- def test_migrate_to_create_tiles(self):
- DashboardTile = self.apps.get_model("posthog", "DashboardTile") # type: ignore
-
- # CASE 1:
- self.assertEqual(DashboardTile.objects.filter(dashboard__name="d1").count(), 0)
-
- # CASE 2:
- self.assertEqual(DashboardTile.objects.filter(dashboard__name="d2").count(), 2)
- blue_tile = DashboardTile.objects.get(dashboard__name="d2", insight__name="blue")
- self.assertEqual(blue_tile.color, "blue")
- self.assertEqual(blue_tile.layouts, {"some": "content"})
-
- red_tile = DashboardTile.objects.get(dashboard__name="d2", insight__name="red")
- self.assertEqual(red_tile.color, "red")
- self.assertEqual(red_tile.layouts, {"some": "different content"})
-
- # CASE 3:
- self.assertEqual(DashboardTile.objects.filter(dashboard__name="d3").count(), 0)
-
- def tearDown(self):
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
-
- Dashboard.objects.all().delete()
- Team.objects.all().delete()
diff --git a/posthog/test/test_migration_0228.py b/posthog/test/test_migration_0228.py
deleted file mode 100644
index ee814b0cfcfb..000000000000
--- a/posthog/test/test_migration_0228.py
+++ /dev/null
@@ -1,82 +0,0 @@
-import json
-
-import pytest
-from posthog.test.base import TestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class FixingDashboardTilesTestCase(TestMigrations):
- migrate_from = "0227_add_dashboard_tiles"
- migrate_to = "0228_fix_tile_layouts"
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- Dashboard = apps.get_model("posthog", "Dashboard")
- Insight = apps.get_model("posthog", "Insight")
- Team = apps.get_model("posthog", "Team")
- DashboardTile = apps.get_model("posthog", "DashboardTile")
-
- org = Organization.objects.create(name="o1")
- team = Team.objects.create(name="t1", organization=org)
-
- dashboard = Dashboard.objects.create(name="d1", team=team)
- # CASE 1:
- # dashboard tile with valid layouts
- # Expect: no conversion for this tile
- insight_for_case_1 = Insight.objects.create(
- team=team,
- filters={"insight": "TRENDS", "date_from": "-7d"},
- name="has valid layouts on tile",
- )
- DashboardTile.objects.create(dashboard=dashboard, insight=insight_for_case_1, layouts={"a": "dict"})
-
- # CASE 2:
- # dashboard with layout that has been stringified once
- # Expect: conversion for this tile
- insight_for_case_2 = Insight.objects.create(
- team=team,
- filters={"insight": "TRENDS", "date_from": "-7d"},
- name="has invalid layouts on tile",
- )
- DashboardTile.objects.create(
- dashboard=dashboard,
- insight=insight_for_case_2,
- layouts=json.dumps({"a": "dict"}),
- )
-
- def test_migrate_to_create_tiles(self):
- """
- Migration 0227 loaded layouts via SQL query from insights and then saved them to dashboard tiles
- That assumed that when loaded they were dicts.
- However, when a Django model saves a JSONField it runs `jsons.dumps(field)` so it is saving a string
- 0227 loaded that string, passed it into a model, and saved it
- So it had effectively had `json.dumps(json.dumps(field)` run on it
-
- In the meantime if anyone has edited a dashboard the layout will have been saved correctly
- (as a singly string stringified dict)
-
- A migration to fix that needs to cope with both singly and doubly stringified dicts)
- """
- DashboardTile = self.apps.get_model("posthog", "DashboardTile") # type: ignore
-
- # CASE 1:
- self.assertIsInstance(
- DashboardTile.objects.get(dashboard__name="d1", insight__name="has valid layouts on tile").layouts,
- dict,
- )
-
- # CASE 2:
- self.assertIsInstance(
- DashboardTile.objects.get(dashboard__name="d1", insight__name="has invalid layouts on tile").layouts,
- dict,
- )
-
- def tearDown(self):
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- Dashboard = self.apps.get_model("posthog", "Dashboard") # type: ignore
- Insight = self.apps.get_model("posthog", "Dashboard") # type: ignore
-
- Insight.objects.all().delete()
- Dashboard.objects.all().delete()
- Team.objects.all().delete()
diff --git a/posthog/test/test_migration_0259.py b/posthog/test/test_migration_0259.py
deleted file mode 100644
index bf17582bc4f1..000000000000
--- a/posthog/test/test_migration_0259.py
+++ /dev/null
@@ -1,90 +0,0 @@
-import pytest
-from posthog.test.base import TestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class RecordingDomainMigrationTestCase(TestMigrations):
- migrate_from = "0258_team_recording_domains"
- migrate_to = "0259_backfill_team_recording_domains"
- assert_snapshots = True
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- Team = apps.get_model("posthog", "Team")
-
- org = Organization.objects.create(name="o1")
-
- # CASE 1:
- # Team with empty app_urls
- Team.objects.create(name="t1", organization=org, app_urls=[])
-
- # CASE 2:
- # Team with normal app_urls
- Team.objects.create(
- name="t2",
- organization=org,
- app_urls=[
- "https://example.com",
- "https://www.example2.com/test/test",
- "https://www.example2.com/test",
- "http://localhost:8000",
- "http://localhost:9000/test/test",
- ],
- )
-
- # CASE 3:
- # Team with wildcarded app_urls
- Team.objects.create(
- name="t3",
- organization=org,
- app_urls=["https://*.example.com", "https://*.app.example.com/test/test"],
- )
-
- # CASE 4:
- # Team with invalid urls in app_urls
- Team.objects.create(
- name="t4",
- organization=org,
- app_urls=[
- "jamaican me crazy",
- "test.com",
- "http://",
- "",
- "https://test.example.com",
- ],
- )
-
- def test_backfill_recording_domain(self):
- Team = self.apps.get_model("posthog", "Team") # type: ignore
-
- # CASE 1:
- self.assertEqual(set(Team.objects.get(name="t1").recording_domains), set())
-
- # CASE 2:
- self.assertEqual(
- set(Team.objects.get(name="t2").recording_domains),
- {
- "https://example.com",
- "https://www.example2.com",
- "http://localhost:8000",
- "http://localhost:9000",
- },
- )
-
- # CASE 3:
- self.assertEqual(
- set(Team.objects.get(name="t3").recording_domains),
- {"https://*.example.com", "https://*.app.example.com"},
- )
-
- # CASE 4:
- self.assertEqual(
- set(Team.objects.get(name="t4").recording_domains),
- {"https://test.example.com"},
- )
-
- def tearDown(self):
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- Team.objects.all().delete()
- super().tearDown()
diff --git a/posthog/test/test_migration_0273.py b/posthog/test/test_migration_0273.py
deleted file mode 100644
index 7c40904e3bd8..000000000000
--- a/posthog/test/test_migration_0273.py
+++ /dev/null
@@ -1,197 +0,0 @@
-import json
-import importlib
-from datetime import timedelta
-from typing import Any, cast
-
-import pytest
-from freezegun.api import freeze_time
-
-from django.db import connection
-from django.db.migrations.executor import MigrationExecutor
-from django.test import TestCase
-from django.utils import timezone
-
-from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.organization import Organization
-from posthog.models.team.team import Team
-
-from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginStorage
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-@freeze_time("2021-08-25T13:00:00Z")
-class MarkInactiveExportsAsFinished(TestCase):
- """
- Test that the migration 0273_mark_inactive_exports_as_finished.py works as
- expected. It should update th activity log entries for exports such that any
- failed exports are highlighted as such.
-
- NOTE: this test used to explicitly test the migration by first migrating to
- migration 0272 and then migrating to 0273. However, this is not possible
- with the addition of a squashed migration from posthog 0001 to 0284, as the
- migration in question is not elided. Instead, we explicitly test the
- migration forwards code. This isn't ideal as we're not testing with the same
- model state as the migration would be run on, but it's better than nothing.
- """
-
- def test_migration(self):
- # First we go back to the previous migration, and setup the database
- # state with exports in various states.
-
- self.organization = Organization.objects.create()
- self.team = Team.objects.create(organization=self.organization, app_urls=[])
- self.plugins = [Plugin.objects.create(organization_id=self.organization.pk) for _ in range(6)]
- self.plugin_configs = [
- PluginConfig.objects.create(plugin=plugin, team=self.team, enabled=True, order=i)
- for i, plugin in enumerate(self.plugins)
- ]
-
- # Case 1: Old non-finished export
- self.create_entry(
- self.plugin_configs[0].pk,
- created_at=timezone.now() - timedelta(days=1),
- activity="job_triggered",
- detail={
- "trigger": {
- "job_id": "1",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
-
- # Case 2: Finished export
- self.create_entry(
- self.plugin_configs[1].pk,
- created_at=timezone.now() - timedelta(days=1),
- activity="job_triggered",
- detail={
- "trigger": {
- "job_id": "2",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
- self.create_entry(
- self.plugin_configs[1].pk,
- created_at=timezone.now() - timedelta(days=1),
- activity="export_success",
- detail={
- "trigger": {
- "job_id": "2",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
-
- # Case 3: Failed export
- self.create_entry(
- self.plugin_configs[2].pk,
- created_at=timezone.now() - timedelta(days=1),
- activity="job_triggered",
- detail={
- "trigger": {
- "job_id": "3",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
- self.create_entry(
- self.plugin_configs[2].pk,
- created_at=timezone.now() - timedelta(days=1),
- activity="export_fail",
- detail={
- "trigger": {
- "job_id": "3",
- "job_type": "Export historical events V2",
- "payload": {},
- "failure_reason": "Some reason",
- }
- },
- )
-
- # Case 4: Recently started export
- self.create_entry(
- self.plugin_configs[3].pk,
- created_at=timezone.now() - timedelta(minutes=2),
- activity="job_triggered",
- detail={
- "trigger": {
- "job_id": "4",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
-
- # Case 5: Started export with storage containing it's running
- self.create_entry(
- self.plugin_configs[4].pk,
- created_at=timezone.now() - timedelta(hours=1),
- activity="job_triggered",
- detail={
- "trigger": {
- "job_id": "5",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
- PluginStorage.objects.create(
- plugin_config_id=self.plugin_configs[4].pk,
- key="EXPORT_PARAMETERS",
- value=json.dumps({"id": "5"}),
- )
-
- # Case 6: Started export with storage containing another that's running
- self.create_entry(
- self.plugin_configs[5].pk,
- created_at=timezone.now() - timedelta(hours=1),
- activity="job_triggered",
- detail={
- "trigger": {
- "job_id": "6",
- "job_type": "Export historical events V2",
- "payload": {},
- }
- },
- )
- PluginStorage.objects.create(
- plugin_config_id=self.plugin_configs[5].pk,
- key="EXPORT_PARAMETERS",
- value=json.dumps({"id": "7"}),
- )
-
- migration = importlib.import_module("posthog.migrations.0273_mark_inactive_exports_as_finished")
- executor = MigrationExecutor(connection)
- apps = executor.loader.project_state().apps
-
- # As we are not testing with the old model state, we need to manually
- # remove the activity entries to ensure that the migration code would
- # create them.
- ActivityLog.objects.filter(activity="export_fail", is_system=True).delete()
- migration.mark_inactive_exports_as_finished(apps, None)
-
- entries = ActivityLog.objects.filter(activity="export_fail", is_system=True)
- details = [cast(dict[str, Any], entry.detail) for entry in entries]
-
- self.assertEqual({detail["trigger"]["job_id"] for detail in details}, {"1", "6"})
- self.assertEqual(
- {detail["trigger"]["failure_reason"] for detail in details},
- {"Export was killed after too much inactivity"},
- )
-
- def create_entry(self, plugin_config_id, activity, created_at, detail):
- ActivityLog.objects.create(
- team_id=self.team.pk,
- organization_id=self.organization.pk,
- scope="PluginConfig",
- item_id=plugin_config_id,
- activity=activity,
- detail=detail,
- created_at=created_at,
- )
diff --git a/posthog/test/test_migration_0287.py b/posthog/test/test_migration_0287.py
deleted file mode 100644
index f6e14f17875b..000000000000
--- a/posthog/test/test_migration_0287.py
+++ /dev/null
@@ -1,104 +0,0 @@
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class CreatingSessionRecordingModelMigrationTestCase(NonAtomicTestMigrations):
- migrate_from = "0286_index_insightcachingstate_lookup"
- migrate_to = "0287_add_session_recording_model"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- Team = apps.get_model("posthog", "Team")
- SessionRecordingPlaylist = apps.get_model("posthog", "SessionRecordingPlaylist")
- SessionRecordingPlaylistItem = apps.get_model("posthog", "SessionRecordingPlaylistItem")
-
- org = Organization.objects.create(name="o1")
- team = Team.objects.create(name="t1", organization=org)
-
- # CASE 0:
- # soft deleted playlist items
- # expect: 0 recording objects and playlist item is deleted
- playlist1 = SessionRecordingPlaylist.objects.create(name="p1", team=team)
- SessionRecordingPlaylistItem.objects.create(session_id="s_0", playlist=playlist1, deleted=True)
-
- # CASE 1:
- # 2 playlist items for the same recording
- # expect: one recording object
- playlist2 = SessionRecordingPlaylist.objects.create(name="p2", team=team)
- playlist3 = SessionRecordingPlaylist.objects.create(name="p3", team=team)
- SessionRecordingPlaylistItem.objects.create(session_id="s_1", playlist=playlist2)
- SessionRecordingPlaylistItem.objects.create(session_id="s_1", playlist=playlist3)
-
- # CASE 2:
- # 2 playlist items for different recordings on different playlists
- # expect: 2 recording objects
- playlist4 = SessionRecordingPlaylist.objects.create(name="p4", team=team)
- playlist5 = SessionRecordingPlaylist.objects.create(name="p5", team=team)
- SessionRecordingPlaylistItem.objects.create(session_id="s_2_1", playlist=playlist4)
- SessionRecordingPlaylistItem.objects.create(session_id="s_2_2", playlist=playlist5)
-
- # CASE 3:
- # 2 playlist items for different recordings on same playlist
- # expect: 2 recording objects
- playlist6 = SessionRecordingPlaylist.objects.create(name="p6", team=team)
- SessionRecordingPlaylistItem.objects.create(session_id="s_3_1", playlist=playlist6)
- SessionRecordingPlaylistItem.objects.create(session_id="s_3_2", playlist=playlist6)
-
- def test_migrate_to_create_session_recordings(self):
- SessionRecording = self.apps.get_model("posthog", "SessionRecording") # type: ignore
- SessionRecordingPlaylist = self.apps.get_model("posthog", "SessionRecordingPlaylist") # type: ignore
- SessionRecordingPlaylistItem = self.apps.get_model("posthog", "SessionRecordingPlaylistItem") # type: ignore
-
- # CASE 0:
- playlist = SessionRecordingPlaylist.objects.get(name="p1")
- assert SessionRecordingPlaylistItem.objects.filter(playlist=playlist, deleted=False).count() == 0
- assert SessionRecording.objects.filter(session_id="s_0").count() == 0
-
- # CASE 1:
- assert SessionRecording.objects.filter(session_id="s_1").count() == 1
- playlist_items = SessionRecordingPlaylistItem.objects.filter(session_id="s_1").select_related("playlist").all()
- assert len(playlist_items) == 2
- assert playlist_items[0].playlist.name == "p2"
- assert playlist_items[1].playlist.name == "p3"
-
- # CASE 2:
- assert SessionRecording.objects.filter(session_id="s_2_1").count() == 1
- assert SessionRecording.objects.filter(session_id="s_2_2").count() == 1
-
- playlist_items = (
- SessionRecordingPlaylistItem.objects.filter(session_id="s_2_1").select_related("playlist").all()
- )
- assert len(playlist_items) == 1
- assert playlist_items[0].playlist.name == "p4"
-
- playlist_items = (
- SessionRecordingPlaylistItem.objects.filter(session_id="s_2_2").select_related("playlist").all()
- )
- assert len(playlist_items) == 1
- assert playlist_items[0].playlist.name == "p5"
-
- # CASE 3:
- assert SessionRecording.objects.filter(session_id="s_3_1").count() == 1
- assert SessionRecording.objects.filter(session_id="s_3_2").count() == 1
- playlist_items = SessionRecordingPlaylistItem.objects.filter(playlist__name="p6").all()
-
- assert len(playlist_items) == 2
- assert playlist_items[0].recording_id == "s_3_1"
- assert playlist_items[1].recording_id == "s_3_2"
-
- def tearDown(self):
- Organization = self.apps.get_model("posthog", "Organization") # type: ignore
- Team = self.apps.get_model("posthog", "Team") # type: ignore
- SessionRecording = self.apps.get_model("posthog", "SessionRecording") # type: ignore
- SessionRecordingPlaylistItem = self.apps.get_model("posthog", "SessionRecordingPlaylistItem") # type: ignore
- SessionRecordingPlaylist = self.apps.get_model("posthog", "SessionRecordingPlaylist") # type: ignore
-
- SessionRecording.objects.all().delete()
- SessionRecordingPlaylistItem.objects.all().delete()
- SessionRecordingPlaylist.objects.all().delete()
- Team.objects.all().delete()
- Organization.objects.all().delete()
diff --git a/posthog/test/test_migration_0385.py b/posthog/test/test_migration_0385.py
deleted file mode 100644
index 35c4f67bea1d..000000000000
--- a/posthog/test/test_migration_0385.py
+++ /dev/null
@@ -1,59 +0,0 @@
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class FixingExceptionAutocaptureMigration(NonAtomicTestMigrations):
- migrate_from = "0384_activity_log_was_impersonated"
- migrate_to = "0385_exception_autocapture_off_for_all"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps):
- Organization = apps.get_model("posthog", "Organization")
- org = Organization.objects.create(name="o1")
-
- Team = apps.get_model("posthog", "Team")
-
- # there are three states... create a Team for each
- team_null = Team.objects.create(name="t1", organization=org)
- team_null.autocapture_exceptions_opt_in = None
- team_null.save()
-
- team_true = Team.objects.create(name="t2", organization=org)
- team_true.autocapture_exceptions_opt_in = True
- team_true.save()
-
- team_false = Team.objects.create(name="t3", organization=org)
- team_false.autocapture_exceptions_opt_in = False
- team_false.save()
-
- def test_migrate_to_create_session_recordings(self):
- apps = self.apps
- if apps is None:
- # obey mypy
- raise Exception("apps is None")
-
- Team = apps.get_model("posthog", "Team")
-
- assert list(Team.objects.all().values_list("name", "autocapture_exceptions_opt_in").order_by("name")) == [
- # unchanged
- ("t1", None),
- # set to False
- ("t2", False),
- # Unchanged
- ("t3", False),
- ]
-
- def tearDown(self):
- apps = self.apps
- if apps is None:
- # obey mypy
- raise Exception("apps is None")
-
- Organization = apps.get_model("posthog", "Organization")
- Team = apps.get_model("posthog", "Team")
-
- Team.objects.all().delete()
- Organization.objects.all().delete()
diff --git a/posthog/test/test_migration_0421.py b/posthog/test/test_migration_0421.py
deleted file mode 100644
index 3046b0f63b1a..000000000000
--- a/posthog/test/test_migration_0421.py
+++ /dev/null
@@ -1,115 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class UpdateSurveyResponseMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0420_alert"
- migrate_to = "0421_set_all_survey_responses_to_be_strings"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- PropertyDefinition = apps.get_model("posthog", "PropertyDefinition")
- Organization = apps.get_model("posthog", "Organization")
- Team = apps.get_model("posthog", "Team")
-
- self.organization = Organization.objects.create(name="o1")
- self.team = Team.objects.create(organization=self.organization, name="t1")
-
- self.property_0 = PropertyDefinition.objects.create(
- team_id=self.team.id,
- name="$survey_response",
- property_type="Numeric",
- is_numerical=True,
- )
- self.property_1 = PropertyDefinition.objects.create(
- team_id=self.team.id, name="$survey_response_1", property_type="Numeric", is_numerical=True, type=1
- )
- self.property_2 = PropertyDefinition.objects.create(
- team_id=self.team.id, name="$survey_response_2", property_type="Numeric", is_numerical=True, type=1
- )
- self.property_3 = PropertyDefinition.objects.create(
- team_id=self.team.id, name="other_property", property_type="Numeric", is_numerical=True, type=1
- )
- self.property_4 = PropertyDefinition.objects.create(
- team_id=self.team.id, name="$survey_response_2", property_type="Numeric", is_numerical=True, type=2
- )
-
- self.property_before_migration = [
- {
- "id": self.property_0.id,
- "name": self.property_0.name,
- "property_type": self.property_0.property_type,
- "is_numerical": self.property_0.is_numerical,
- "type": self.property_0.type,
- },
- {
- "id": self.property_1.id,
- "name": self.property_1.name,
- "property_type": self.property_1.property_type,
- "is_numerical": self.property_1.is_numerical,
- "type": self.property_1.type,
- },
- {
- "id": self.property_2.id,
- "name": self.property_2.name,
- "property_type": self.property_2.property_type,
- "is_numerical": self.property_2.is_numerical,
- "type": self.property_2.type,
- },
- {
- "id": self.property_3.id,
- "name": self.property_3.name,
- "property_type": self.property_3.property_type,
- "is_numerical": self.property_3.is_numerical,
- "type": self.property_3.type,
- },
- {
- "id": self.property_4.id,
- "name": self.property_4.name,
- "property_type": self.property_4.property_type,
- "is_numerical": self.property_4.is_numerical,
- "type": self.property_4.type,
- },
- ]
-
- def test_migration(self) -> None:
- # Ensure self.apps is not None
- assert self.apps is not None
-
- PropertyDefinition = self.apps.get_model("posthog", "PropertyDefinition")
-
- # Check updated properties
- updated_property_0 = PropertyDefinition.objects.get(id=self.property_0.id)
- updated_property_1 = PropertyDefinition.objects.get(id=self.property_1.id)
- updated_property_2 = PropertyDefinition.objects.get(id=self.property_2.id)
-
- self.assertEqual(updated_property_0.property_type, "String")
- self.assertFalse(updated_property_0.is_numerical)
-
- self.assertEqual(updated_property_1.property_type, "String")
- self.assertFalse(updated_property_1.is_numerical)
-
- self.assertEqual(updated_property_2.property_type, "String")
- self.assertFalse(updated_property_2.is_numerical)
-
- # Check unchanged properties
- unchanged_property_1 = PropertyDefinition.objects.get(id=self.property_3.id)
- unchanged_property_2 = PropertyDefinition.objects.get(id=self.property_4.id)
-
- self.assertEqual(unchanged_property_1.property_type, "Numeric")
- self.assertTrue(unchanged_property_1.is_numerical)
- self.assertEqual(unchanged_property_2.property_type, "Numeric")
- self.assertTrue(unchanged_property_2.is_numerical)
-
- def tearDown(self) -> None:
- # Ensure self.apps is not None
- assert self.apps is not None
-
- PropertyDefinition = self.apps.get_model("posthog", "PropertyDefinition")
- PropertyDefinition.objects.all().delete()
- super().tearDown()
diff --git a/posthog/test/test_migration_0459.py b/posthog/test/test_migration_0459.py
deleted file mode 100644
index c7f9204b6710..000000000000
--- a/posthog/test/test_migration_0459.py
+++ /dev/null
@@ -1,235 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class ConvertPersonsNodeInsightsToActorsQueryMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0458_alter_insightviewed_team_alter_insightviewed_user"
- migrate_to = "0459_convert_personsnode_insights_to_actorsquery"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- Insight = apps.get_model("posthog", "Insight")
-
- self.organization = Organization.objects.create(name="o1")
- self.project = Project.objects.create(organization=self.organization, name="p1", id=1000001)
- self.team = Team.objects.create(organization=self.organization, name="t1", project=self.project)
-
- self.insight_1 = Insight.objects.create(
- team=self.team,
- query={"full": True, "kind": "DataTableNode", "source": {"kind": "PersonsNode", "cohort": "4669"}},
- )
- self.insight_2 = Insight.objects.create(
- team=self.team,
- deleted=True,
- query={
- "full": True,
- "kind": "DataTableNode",
- "source": {"kind": "PersonsNode", "search": "@"},
- "propertiesViaUrl": True,
- },
- )
- self.insight_3 = Insight.objects.create(
- team=self.team,
- query={
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "PersonsNode",
- "properties": [{"key": "email", "type": "person", "value": "is_set", "operator": "is_set"}],
- },
- "propertiesViaUrl": True,
- },
- )
- self.insight_4 = Insight.objects.create(
- team=self.team,
- query={
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "PersonsNode",
- "cohort": "3",
- "properties": [{"key": "email", "type": "person", "value": "is_set", "operator": "is_set"}],
- },
- "propertiesViaUrl": True,
- },
- )
- self.insight_5 = Insight.objects.create(
- team=self.team,
- query={"full": True, "kind": "DataTableNode", "source": {"kind": "PersonsNode"}, "propertiesViaUrl": True},
- )
- self.insight_6 = Insight.objects.create(
- team=self.team,
- query={
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "PersonsNode",
- "fixedProperties": [{"key": "email", "type": "person", "value": "is_set", "operator": "is_set"}],
- "properties": [
- {"key": "name", "type": "person", "value": "is_set", "operator": "is_set"},
- {"key": "surname", "type": "person", "value": "is_set", "operator": "is_set"},
- {"key": "id", "type": "cohort", "value": 3},
- ],
- "limit": 100,
- "offset": 100,
- },
- "propertiesViaUrl": True,
- },
- )
- self.insight_7 = Insight.objects.create(
- team=self.team,
- query={
- "kind": "DataTableNode",
- "source": {
- "kind": "ActorsQuery",
- "cohort": 3,
- },
- },
- )
- self.insight_8 = Insight.objects.create(
- team=self.team,
- query={
- "kind": "InsightVizNode",
- "source": {
- "kind": "TrendsQuery",
- "cohort": 3,
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- },
- },
- )
-
- def test_migration(self) -> None:
- # Ensure self.apps is not None
- assert self.apps is not None
-
- self.insight_1.refresh_from_db()
- self.assertEqual(
- self.insight_1.query,
- {
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "ActorsQuery",
- "properties": [{"key": "id", "type": "cohort", "operator": "in", "value": 4669}],
- },
- },
- )
-
- self.insight_2.refresh_from_db()
- self.assertEqual(
- self.insight_2.query,
- {
- "full": True,
- "kind": "DataTableNode",
- "source": {"kind": "ActorsQuery", "search": "@", "properties": []},
- "propertiesViaUrl": True,
- },
- )
-
- self.insight_3.refresh_from_db()
- self.assertEqual(
- self.insight_3.query,
- {
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "ActorsQuery",
- "properties": [{"key": "email", "type": "person", "value": "is_set", "operator": "is_set"}],
- },
- "propertiesViaUrl": True,
- },
- )
-
- self.insight_4.refresh_from_db()
- self.assertEqual(
- self.insight_4.query,
- {
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "ActorsQuery",
- "properties": [
- {"key": "email", "type": "person", "value": "is_set", "operator": "is_set"},
- {"key": "id", "type": "cohort", "operator": "in", "value": 3},
- ],
- },
- "propertiesViaUrl": True,
- },
- )
-
- self.insight_5.refresh_from_db()
- self.assertEqual(
- self.insight_5.query,
- {
- "full": True,
- "kind": "DataTableNode",
- "source": {"kind": "ActorsQuery", "properties": []},
- "propertiesViaUrl": True,
- },
- )
-
- self.insight_6.refresh_from_db()
- self.assertEqual(
- self.insight_6.query,
- {
- "full": True,
- "kind": "DataTableNode",
- "source": {
- "kind": "ActorsQuery",
- "fixedProperties": [{"key": "email", "type": "person", "value": "is_set", "operator": "is_set"}],
- "properties": [
- {"key": "name", "type": "person", "value": "is_set", "operator": "is_set"},
- {"key": "surname", "type": "person", "value": "is_set", "operator": "is_set"},
- {"key": "id", "type": "cohort", "operator": "in", "value": 3},
- ],
- "limit": 100,
- "offset": 100,
- },
- "propertiesViaUrl": True,
- },
- )
-
- self.insight_7.refresh_from_db()
- self.assertEqual(
- self.insight_7.query,
- {
- "kind": "DataTableNode",
- "source": {
- "kind": "ActorsQuery",
- "cohort": 3,
- },
- },
- )
-
- self.insight_8.refresh_from_db()
- self.assertEqual(
- self.insight_8.query,
- {
- "kind": "InsightVizNode",
- "source": {
- "kind": "TrendsQuery",
- "series": [{"kind": "EventsNode", "event": "$pageview"}],
- "cohort": 3,
- },
- },
- )
-
- def tearDown(self) -> None:
- # Ensure self.apps is not None
- assert self.apps is not None
-
- Insight = self.apps.get_model("posthog", "Insight")
- Insight.objects.all().delete()
- self.team.delete()
- self.project.delete()
- self.organization.delete()
-
- super().tearDown()
diff --git a/posthog/test/test_migration_0766.py b/posthog/test/test_migration_0766.py
deleted file mode 100644
index c32bb43018c7..000000000000
--- a/posthog/test/test_migration_0766.py
+++ /dev/null
@@ -1,61 +0,0 @@
-import uuid
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class FixSubTemplateIdsToTemplateIdsMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0765_hogflows"
- migrate_to = "0766_fix_sub_template_ids_to_template_ids"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- HogFunction = apps.get_model("posthog", "HogFunction")
-
- self.organization = Organization.objects.create(name="o1")
- self.project = Project.objects.create(organization=self.organization, name="p1", id=1000001)
- self.team = Team.objects.create(organization=self.organization, name="t1", project=self.project)
-
- # Create HogFunctions with sub-template IDs
- self.hf_slack = HogFunction.objects.create(
- id=uuid.uuid4(),
- team=self.team,
- template_id="template-slack-error-tracking-issue-created",
- hog="return event",
- )
- self.hf_discord = HogFunction.objects.create(
- id=uuid.uuid4(),
- team=self.team,
- template_id="template-discord-survey-response",
- hog="return event",
- )
- self.hf_webhook = HogFunction.objects.create(
- id=uuid.uuid4(),
- team=self.team,
- template_id="template-webhook-error-tracking-issue-reopened",
- hog="return event",
- )
- self.hf_teams = HogFunction.objects.create(
- id=uuid.uuid4(),
- team=self.team,
- template_id="template-microsoft-teams-error-tracking-issue-created",
- hog="return event",
- )
-
- def test_migration(self):
- # After migration, all template_ids should be mapped to their parent
- self.hf_slack.refresh_from_db()
- self.hf_discord.refresh_from_db()
- self.hf_webhook.refresh_from_db()
- self.hf_teams.refresh_from_db()
- assert self.hf_slack.template_id == "template-slack"
- assert self.hf_discord.template_id == "template-discord"
- assert self.hf_webhook.template_id == "template-webhook"
- assert self.hf_teams.template_id == "template-microsoft-teams"
diff --git a/posthog/test/test_migration_0838.py b/posthog/test/test_migration_0838.py
deleted file mode 100644
index aff609d3214c..000000000000
--- a/posthog/test/test_migration_0838.py
+++ /dev/null
@@ -1,87 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-from parameterized import parameterized
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class RemoveNullValuesFromTeamArraysMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0837_alter_externaldatasource_source_type"
- migrate_to = "0838_remove_null_values_from_team_arrays"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
-
- self.organization = Organization.objects.create(name="Test Organization")
- self.project = Project.objects.create(organization=self.organization, name="Test Project", id=1000001)
- self.Team = Team
-
- # Create all test teams with specific test data before migration runs
- self.teams = {}
-
- # app_urls
- self.teams["app_mixed"] = self._create_team(
- "App mixed", app_urls=["https://valid.com", None, "https://valid2.com", None]
- )
- self.teams["app_all_nulls"] = self._create_team("App all nulls", app_urls=[None, None])
- self.teams["app_empty"] = self._create_team("App empty", app_urls=[])
- self.teams["app_clean"] = self._create_team("App clean", app_urls=["https://clean.com"])
-
- # recording_domains
- self.teams["rec_mixed"] = self._create_team(
- "Rec mixed", recording_domains=["domain1.com", None, "domain2.com", None]
- )
- self.teams["rec_all_nulls"] = self._create_team("Rec all nulls", recording_domains=[None, None])
- self.teams["rec_empty"] = self._create_team("Rec empty", recording_domains=[])
- self.teams["rec_clean"] = self._create_team("Rec clean", recording_domains=["clean.com"])
- self.teams["rec_null_field"] = self._create_team(
- "Null field", app_urls=["https://clean.com", None], recording_domains=None
- )
-
- def _create_team(self, name, app_urls=None, recording_domains=None):
- """Utility to create teams with default values"""
- return self.Team.objects.create(
- organization=self.organization,
- project=self.project,
- name=name,
- app_urls=app_urls if app_urls is not None else [],
- recording_domains=recording_domains,
- )
-
- @parameterized.expand(
- [
- ("app_mixed", ["https://valid.com", "https://valid2.com"]),
- ("app_all_nulls", []),
- ("app_empty", []),
- ("app_clean", ["https://clean.com"]),
- ]
- )
- def test_app_urls_null_removal(self, team_key, expected_app_urls):
- """Test that nulls are correctly removed from app_urls arrays"""
- team = self.teams[team_key]
- team.refresh_from_db()
-
- self.assertEqual(team.app_urls, expected_app_urls)
-
- @parameterized.expand(
- [
- ("rec_mixed", ["domain1.com", "domain2.com"]),
- ("rec_all_nulls", []),
- ("rec_empty", []),
- ("rec_clean", ["clean.com"]),
- ("rec_null_field", None),
- ]
- )
- def test_recording_domains_null_removal(self, team_key, expected_recording_domains):
- """Test that nulls are correctly removed from recording_domains arrays"""
- team = self.teams[team_key]
- team.refresh_from_db()
-
- self.assertEqual(team.recording_domains, expected_recording_domains)
diff --git a/posthog/test/test_migration_0999.py b/posthog/test/test_migration_0999.py
deleted file mode 100644
index 708a6713f308..000000000000
--- a/posthog/test/test_migration_0999.py
+++ /dev/null
@@ -1,181 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-from parameterized import parameterized
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class RemovePresortedEventsModifierMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0998_team_proactive_tasks_enabled"
- migrate_to = "0999_remove_presorted_events_modifier"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- Insight = apps.get_model("posthog", "Insight")
-
- self.organization = Organization.objects.create(name="Test Organization")
- self.project = Project.objects.create(organization=self.organization, name="Test Project", id=1000001)
- self.team = Team.objects.create(
- organization=self.organization,
- project=self.project,
- name="Test Team",
- )
- self.Insight = Insight
-
- self.insights = {}
-
- # query.modifiers only
- self.insights["query_modifiers_only"] = Insight.objects.create(
- team=self.team,
- name="Query modifiers only",
- query={"kind": "TrendsQuery", "modifiers": {"usePresortedEventsTable": True}},
- )
-
- # query.source.modifiers only
- self.insights["source_modifiers_only"] = Insight.objects.create(
- team=self.team,
- name="Source modifiers only",
- query={
- "kind": "DataVisualizationNode",
- "source": {"kind": "TrendsQuery", "modifiers": {"usePresortedEventsTable": False}},
- },
- )
-
- # Both locations
- self.insights["both_locations"] = Insight.objects.create(
- team=self.team,
- name="Both locations",
- query={
- "kind": "DataVisualizationNode",
- "modifiers": {"usePresortedEventsTable": True},
- "source": {"kind": "TrendsQuery", "modifiers": {"usePresortedEventsTable": False}},
- },
- )
-
- # Other modifiers preserved
- self.insights["other_modifiers_preserved"] = Insight.objects.create(
- team=self.team,
- name="Other modifiers preserved",
- query={
- "kind": "TrendsQuery",
- "modifiers": {"usePresortedEventsTable": True, "inCohortVia": "subquery"},
- },
- )
-
- # No usePresortedEventsTable modifier (control case)
- self.insights["no_modifier"] = Insight.objects.create(
- team=self.team,
- name="No modifier",
- query={"kind": "TrendsQuery", "modifiers": {"inCohortVia": "subquery"}},
- )
-
- # Empty modifiers
- self.insights["empty_modifiers"] = Insight.objects.create(
- team=self.team,
- name="Empty modifiers",
- query={"kind": "TrendsQuery", "modifiers": {}},
- )
-
- # No modifiers key at all
- self.insights["no_modifiers_key"] = Insight.objects.create(
- team=self.team,
- name="No modifiers key",
- query={"kind": "TrendsQuery"},
- )
-
- # Other query fields preserved
- self.insights["other_query_fields_preserved"] = Insight.objects.create(
- team=self.team,
- name="Other query fields preserved",
- query={
- "kind": "TrendsQuery",
- "series": [{"event": "pageview", "kind": "EventsNode"}],
- "dateRange": {"date_from": "-7d"},
- "modifiers": {"usePresortedEventsTable": True},
- },
- )
-
- # Other source fields preserved
- self.insights["other_source_fields_preserved"] = Insight.objects.create(
- team=self.team,
- name="Other source fields preserved",
- query={
- "kind": "DataVisualizationNode",
- "display": "LineChart",
- "source": {
- "kind": "TrendsQuery",
- "series": [{"event": "pageview", "kind": "EventsNode"}],
- "modifiers": {"usePresortedEventsTable": True},
- },
- },
- )
-
- @parameterized.expand(
- [
- (
- "query_modifiers_only",
- {"kind": "TrendsQuery", "modifiers": {}},
- ),
- (
- "source_modifiers_only",
- {"kind": "DataVisualizationNode", "source": {"kind": "TrendsQuery", "modifiers": {}}},
- ),
- (
- "both_locations",
- {
- "kind": "DataVisualizationNode",
- "modifiers": {},
- "source": {"kind": "TrendsQuery", "modifiers": {}},
- },
- ),
- (
- "other_modifiers_preserved",
- {"kind": "TrendsQuery", "modifiers": {"inCohortVia": "subquery"}},
- ),
- (
- "no_modifier",
- {"kind": "TrendsQuery", "modifiers": {"inCohortVia": "subquery"}},
- ),
- (
- "empty_modifiers",
- {"kind": "TrendsQuery", "modifiers": {}},
- ),
- (
- "no_modifiers_key",
- {"kind": "TrendsQuery"},
- ),
- (
- "other_query_fields_preserved",
- {
- "kind": "TrendsQuery",
- "series": [{"event": "pageview", "kind": "EventsNode"}],
- "dateRange": {"date_from": "-7d"},
- "modifiers": {},
- },
- ),
- (
- "other_source_fields_preserved",
- {
- "kind": "DataVisualizationNode",
- "display": "LineChart",
- "source": {
- "kind": "TrendsQuery",
- "series": [{"event": "pageview", "kind": "EventsNode"}],
- "modifiers": {},
- },
- },
- ),
- ]
- )
- def test_presorted_events_modifier_removed(self, insight_key, expected_query):
- insight = self.insights[insight_key]
- insight.refresh_from_db()
-
- self.assertEqual(insight.query, expected_query)
diff --git a/posthog/test/test_migration_1185.py b/posthog/test/test_migration_1185.py
deleted file mode 100644
index 7f00aa8b3ba6..000000000000
--- a/posthog/test/test_migration_1185.py
+++ /dev/null
@@ -1,82 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import TestMigrations
-
-from parameterized import parameterized
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class FixNonListTestAccountFiltersMigrationTest(TestMigrations):
- migrate_from = "1184_migrate_product_analytics_models"
- migrate_to = "1185_fix_non_list_test_account_filters"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
-
- self.organization = Organization.objects.create(name="Test Organization")
- self.project = Project.objects.create(organization=self.organization, name="Test Project", id=1_000_001)
- self.Team = Team
-
- # JSONField encodes whatever Python value we pass via json.dumps, so a Python str
- # becomes a JSON string in the column - the exact corruption we are repairing.
- self.teams = {
- "stringified_array": self._create_team(
- "stringified_array",
- test_account_filters='[{"key":"$browser","value":"Chrome","operator":"exact"}]',
- ),
- "stringified_non_array": self._create_team(
- "stringified_non_array",
- test_account_filters="not even an array",
- ),
- "object": self._create_team(
- "object",
- test_account_filters={"key": "$browser", "value": "Chrome"},
- ),
- "json_null": self._create_team(
- "json_null",
- test_account_filters=None,
- ),
- "already_array": self._create_team(
- "already_array",
- test_account_filters=[{"key": "email", "value": "@posthog.com", "operator": "icontains"}],
- ),
- }
-
- def _create_team(self, name: str, test_account_filters: Any) -> Any:
- return self.Team.objects.create(
- organization=self.organization,
- project=self.project,
- name=name,
- test_account_filters=test_account_filters,
- )
-
- @parameterized.expand(
- [
- # Stringified JSON array - the meaningful recovery, preserve the parsed contents.
- (
- "stringified_array",
- [{"key": "$browser", "value": "Chrome", "operator": "exact"}],
- ),
- # Stringified non-array - cannot recover, reset to [].
- ("stringified_non_array", []),
- # JSON object - reset to [].
- ("object", []),
- # JSON null - reset to [].
- ("json_null", []),
- # Already a valid array - left untouched.
- (
- "already_array",
- [{"key": "email", "value": "@posthog.com", "operator": "icontains"}],
- ),
- ]
- )
- def test_test_account_filters_normalized(self, team_key: str, expected: list) -> None:
- team = self.teams[team_key]
- team.refresh_from_db()
- self.assertEqual(team.test_account_filters, expected)
diff --git a/posthog/test/test_migration_1274.py b/posthog/test/test_migration_1274.py
deleted file mode 100644
index 6ff3ca9b42de..000000000000
--- a/posthog/test/test_migration_1274.py
+++ /dev/null
@@ -1,130 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import TestMigrations
-
-from parameterized import parameterized
-
-from posthog.models.oauth_provisioning import ProvisioningConfig
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class BackfillProvisioningConfigMigrationTest(TestMigrations):
- migrate_from = "1273_oauth_provisioning_config"
- migrate_to = "1274_backfill_oauth_provisioning_config"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- OAuthApplication = apps.get_model("posthog", "OAuthApplication")
- self.OAuthApplication = OAuthApplication
-
- # A partner PostHog vouched for, carrying a partner type and a custom quota.
- self.vouched = self._create_app(
- "vouched",
- is_provisioning_partner=True,
- provisioning_partner_type="wizard",
- provisioning_active=True,
- provisioning_can_create_accounts=True,
- provisioning_can_provision_resources=True,
- provisioning_can_issue_deep_links=True,
- provisioning_rate_limit_account_requests=250,
- provisioning_rate_limit_account_requests_source="admin",
- )
- # A CIMD client that registered itself: partner, but nobody vouched for it.
- self.self_registered = self._create_app(
- "self_registered",
- is_cimd_client=True,
- cimd_metadata_url="https://selfreg.example.com/.well-known/oauth-client-metadata.json",
- is_provisioning_partner=True,
- provisioning_active=True,
- provisioning_can_create_accounts=True,
- provisioning_can_provision_resources=True,
- )
- # An admin-created partner whose type field was simply left blank.
- self.blank_type = self._create_app(
- "blank_type",
- is_provisioning_partner=True,
- provisioning_active=True,
- provisioning_can_provision_resources=True,
- )
- # A self-registered partner an admin killed: flag cleared, kill switch set, deactivated.
- # None of that shows up in the three columns that used to select rows for this backfill.
- self.killed = self._create_app(
- "killed",
- is_cimd_client=True,
- cimd_metadata_url="https://killed.example.com/.well-known/oauth-client-metadata.json",
- provisioning_disabled=True,
- )
- # Capabilities that older migrations granted keyed on provisioning_auth_method and
- # client_id, on a row that 1268 did not make a partner.
- self.legacy = self._create_app(
- "legacy",
- provisioning_can_issue_deep_links=True,
- provisioning_issues_personal_api_key=True,
- )
- # An ordinary OAuth app that has nothing to do with provisioning.
- self.plain = self._create_app("plain")
-
- def _create_app(self, slug: str, **fields: Any):
- return self.OAuthApplication.objects.create(
- name=f"App {slug}",
- client_id=f"client-{slug}",
- client_secret="",
- client_type="confidential",
- authorization_grant_type="authorization-code",
- redirect_uris="https://example.com/callback",
- algorithm="RS256",
- **fields,
- )
-
- @parameterized.expand(
- [
- # A partner type was the old github-grants gate, so it carries over as the grant.
- ("vouched", "can_use_github_grants", True),
- # Wizard runs were ungated before; a vouched-for partner keeps them.
- ("vouched", "can_start_wizard_runs", True),
- ("vouched", "can_issue_deep_links", True),
- # Self-registration never vouched for anything, so both elevated capabilities go.
- ("self_registered", "can_use_github_grants", False),
- ("self_registered", "can_start_wizard_runs", False),
- # Still allowed to do the ordinary provisioning it was already doing.
- ("self_registered", "can_create_accounts", True),
- ("self_registered", "active", True),
- # Non-CIMD apps only exist because an admin made them, which is what the old gate
- # treated as vouched-for. Preserved so a blank type doesn't lock one out.
- ("blank_type", "can_use_github_grants", True),
- # Wizard runs had no such carve-out, and no partner type means no grant.
- ("blank_type", "can_start_wizard_runs", False),
- # The kill switch is the one capability whose default fails open, so a row that
- # carries it has to be backfilled however unconfigured it otherwise looks - or the
- # next CIMD registration re-grants the partner everything.
- ("killed", "disabled", True),
- # These two fail closed instead, so losing them silently breaks a live integration.
- ("legacy", "can_issue_deep_links", True),
- ("legacy", "issues_personal_api_key", True),
- # Ordinary OAuth apps are the bulk of the table and never a provisioning partner, so
- # an unfiltered backfill must not hand them either capability that reads permissively
- # off an unconfigured row - the old gate let anything non-CIMD through, and
- # provisioning_can_provision_resources was added with default=True.
- ("plain", "can_use_github_grants", False),
- ("plain", "can_provision_resources", False),
- # And the partners that do hold it have to keep it.
- ("vouched", "can_provision_resources", True),
- ]
- )
- def test_capability_backfill(self, app_attr: str, key: str, expected: bool) -> None:
- app = self.OAuthApplication.objects.get(pk=getattr(self, app_attr).pk)
- assert app._provisioning_config[key] is expected
-
- def test_rate_limits_and_source_carry_over(self) -> None:
- config = self.OAuthApplication.objects.get(pk=self.vouched.pk)._provisioning_config
- assert config["rate_limits"]["account_requests"] == 250
- assert config["rate_limit_source"] == "admin"
-
- def test_non_partner_app_grants_nothing(self) -> None:
- # Every row is backfilled, so what keeps an ordinary OAuth app harmless is the mapping
- # rather than being skipped: its config has to mean the same as the column's {} default.
- config = self.OAuthApplication.objects.get(pk=self.plain.pk)._provisioning_config
- assert ProvisioningConfig.model_validate(config) == ProvisioningConfig()
diff --git a/posthog/test/test_migration_1279.py b/posthog/test/test_migration_1279.py
deleted file mode 100644
index 0ec46ff93858..000000000000
--- a/posthog/test/test_migration_1279.py
+++ /dev/null
@@ -1,49 +0,0 @@
-from importlib import import_module
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-
-from posthog.models import IdentityProviderConfig, LinkedIdentityProviderConfig, OrganizationDomain
-
-migration = import_module("posthog.migrations.1288_backfill_linked_identity_provider_configs")
-
-
-class TestLinkedIdentityProviderConfigBackfill(BaseTest):
- def test_backfills_existing_domain_config_links_and_skips_unlinked_domains(self) -> None:
- linked_config = IdentityProviderConfig.objects.create(organization=self.organization)
- orphan_config = IdentityProviderConfig.objects.create(organization=self.organization)
- linked_domain = OrganizationDomain.objects.create(
- organization=self.organization,
- domain="linked.example.com",
- identity_provider_config=linked_config,
- )
- OrganizationDomain.objects.create(
- organization=self.organization,
- domain="unlinked.example.com",
- )
-
- migration.backfill_linked_identity_provider_configs(apps, None)
-
- assert list(
- LinkedIdentityProviderConfig.objects.values_list("organization_domain_id", "identity_provider_config_id")
- ) == [(linked_domain.id, linked_config.id)]
- assert not LinkedIdentityProviderConfig.objects.filter(identity_provider_config_id=orphan_config.id).exists()
-
- def test_backfill_is_safe_to_run_again(self) -> None:
- config = IdentityProviderConfig.objects.create(organization=self.organization)
- domain = OrganizationDomain.objects.create(
- organization=self.organization,
- domain="linked.example.com",
- identity_provider_config=config,
- )
-
- migration.backfill_linked_identity_provider_configs(apps, None)
- migration.backfill_linked_identity_provider_configs(apps, None)
-
- assert (
- LinkedIdentityProviderConfig.objects.filter(
- organization_domain_id=domain.id, identity_provider_config_id=config.id
- ).count()
- == 1
- )
diff --git a/posthog/test/test_migration_1281.py b/posthog/test/test_migration_1281.py
deleted file mode 100644
index 22cc9cc5fb26..000000000000
--- a/posthog/test/test_migration_1281.py
+++ /dev/null
@@ -1,122 +0,0 @@
-import importlib
-from collections.abc import Collection
-from types import SimpleNamespace
-
-import pytest
-
-from django.contrib.auth import get_user_model
-from django.contrib.auth.models import Group, Permission
-from django.contrib.contenttypes.models import ContentType
-from django.db import connection
-from django.db.migrations.executor import MigrationExecutor
-
-migration = importlib.import_module("posthog.migrations.1281_migrate_managed_warehouse_models")
-
-
-def _assert_assignments(
- permission: Permission,
- *,
- user_ids: Collection[object],
- group_ids: Collection[object],
-) -> None:
- User = get_user_model()
- assert set(User.objects.filter(user_permissions=permission).values_list("id", flat=True)) == user_ids
- assert set(Group.objects.filter(permissions=permission).values_list("id", flat=True)) == group_ids
-
-
[email protected]("model_name", migration.MODELS_TO_COPY)
-def test_content_type_copy_preserves_grants_across_forward_reverse_and_reapply(model_name: str) -> None:
- migration_apps = (
- MigrationExecutor(connection).loader.project_state([("posthog", "1281_migrate_managed_warehouse_models")]).apps
- )
- source_content_type, _ = ContentType.objects.get_or_create(app_label="posthog", model=model_name)
- target_content_type, _ = ContentType.objects.get_or_create(app_label="managed_warehouse", model=model_name)
-
- source_only = Permission.objects.create(
- content_type=source_content_type,
- codename=f"migration_source_only_{model_name}",
- name="Source-only migration permission",
- )
- source_shared = Permission.objects.create(
- content_type=source_content_type,
- codename=f"migration_shared_{model_name}",
- name="Shared migration permission",
- )
- target_shared = Permission.objects.create(
- content_type=target_content_type,
- codename=source_shared.codename,
- name=source_shared.name,
- )
- target_only = Permission.objects.create(
- content_type=target_content_type,
- codename=f"migration_target_only_{model_name}",
- name="Target-only migration permission",
- )
-
- User = get_user_model()
- source_user = User.objects.create(
- email=f"source-{model_name}@example.com",
- distinct_id=f"source-{model_name}",
- )
- target_user = User.objects.create(
- email=f"target-{model_name}@example.com",
- distinct_id=f"target-{model_name}",
- )
- source_group = Group.objects.create(name=f"source-{model_name}")
- target_group = Group.objects.create(name=f"target-{model_name}")
-
- source_user.user_permissions.add(source_only, source_shared)
- source_group.permissions.add(source_only, source_shared)
- target_user.user_permissions.add(target_shared, target_only)
- target_group.permissions.add(target_shared, target_only)
-
- schema_editor = SimpleNamespace(connection=connection)
- migration.update_content_types(migration_apps, schema_editor)
-
- assert ContentType.objects.filter(pk=source_content_type.pk).exists()
- assert ContentType.objects.filter(pk=target_content_type.pk).exists()
- copied_source_only = Permission.objects.get(
- content_type=target_content_type,
- codename=source_only.codename,
- )
- target_shared.refresh_from_db()
- _assert_assignments(
- copied_source_only,
- user_ids={source_user.pk},
- group_ids={source_group.pk},
- )
- _assert_assignments(
- target_shared,
- user_ids={source_user.pk, target_user.pk},
- group_ids={source_group.pk, target_group.pk},
- )
-
- migration.reverse_content_types(migration_apps, schema_editor)
-
- source_shared.refresh_from_db()
- copied_target_only = Permission.objects.get(
- content_type=source_content_type,
- codename=target_only.codename,
- )
- _assert_assignments(
- source_shared,
- user_ids={source_user.pk, target_user.pk},
- group_ids={source_group.pk, target_group.pk},
- )
- _assert_assignments(
- copied_target_only,
- user_ids={target_user.pk},
- group_ids={target_group.pk},
- )
-
- migration.update_content_types(migration_apps, schema_editor)
-
- assert Permission.objects.filter(content_type=source_content_type, codename=source_shared.codename).count() == 1
- assert Permission.objects.filter(content_type=target_content_type, codename=source_shared.codename).count() == 1
- target_shared.refresh_from_db()
- _assert_assignments(
- target_shared,
- user_ids={source_user.pk, target_user.pk},
- group_ids={source_group.pk, target_group.pk},
- )
diff --git a/posthog/test/test_migration_1286.py b/posthog/test/test_migration_1286.py
deleted file mode 100644
index 1ff43a191a88..000000000000
--- a/posthog/test/test_migration_1286.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from importlib import import_module
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-from django.utils import timezone
-
-from posthog.models import IdentityProviderConfig, OrganizationDomain
-
-migration = import_module("posthog.migrations.1286_cleanup_orphaned_identity_provider_configs")
-
-
-class TestCleanupOrphanedIdentityProviderConfigs(BaseTest):
- def _backdate(self, config: IdentityProviderConfig) -> None:
- # created_at is auto_now_add, so it has to be rewritten with an update
- IdentityProviderConfig.objects.filter(pk=config.pk).update(
- created_at=timezone.now() - migration.UNLINKED_GRACE_PERIOD * 2
- )
-
- def test_migration_deletes_only_configs_without_domains(self):
- orphaned_config = IdentityProviderConfig.objects.create(organization=self.organization)
- linked_config = IdentityProviderConfig.objects.create(organization=self.organization)
- self._backdate(orphaned_config)
- self._backdate(linked_config)
- OrganizationDomain.objects.create(
- organization=self.organization,
- domain="linked.posthog.com",
- identity_provider_config=linked_config,
- )
-
- migration.delete_orphaned_identity_provider_configs(apps, None)
-
- assert not IdentityProviderConfig.objects.filter(pk=orphaned_config.pk).exists()
- assert IdentityProviderConfig.objects.filter(pk=linked_config.pk).exists()
-
- def test_migration_keeps_recently_created_unlinked_configs(self):
- # A config created via the standalone create endpoint may not be linked to a domain yet, since
- # the frontend links it in a follow-up request
- in_progress_config = IdentityProviderConfig.objects.create(organization=self.organization)
-
- migration.delete_orphaned_identity_provider_configs(apps, None)
-
- assert IdentityProviderConfig.objects.filter(pk=in_progress_config.pk).exists()
diff --git a/posthog/test/test_migration_1296.py b/posthog/test/test_migration_1296.py
deleted file mode 100644
index 3502a6a74618..000000000000
--- a/posthog/test/test_migration_1296.py
+++ /dev/null
@@ -1,152 +0,0 @@
-from datetime import timedelta
-from typing import Any
-
-from posthog.test.base import NonAtomicTestMigrations
-
-from django.utils import timezone
-
-from parameterized import parameterized
-
-
-# Non-atomic because rewinding to `migrate_from` unapplies every later migration, and those include
-# `atomic = False` ones whose CONCURRENTLY index operations Postgres refuses inside a transaction.
-class BackfillCimdVerificationTokenUrlMigrationTest(NonAtomicTestMigrations):
- migrate_from = "1295_cimdverificationtoken_cimd_url"
- migrate_to = "1296_backfill_cimd_verification_token_url"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- OAuthApplication = apps.get_model("posthog", "OAuthApplication")
- CIMDVerificationToken = apps.get_model("posthog", "CIMDVerificationToken")
- self.CIMDVerificationToken = CIMDVerificationToken
-
- base_time = timezone.now() - timedelta(days=30)
-
- # The historical model skips Organization.save's slug generation, so every org would
- # otherwise collide on the unique empty slug.
- def make_org(slug: str) -> Any:
- return Organization.objects.create(name=f"Org {slug}", slug=slug)
-
- def make_app(slug: str, org: Any, url: str, created: Any = base_time) -> Any:
- app = OAuthApplication.objects.create(
- name=f"App {slug}",
- client_id=f"client-{slug}",
- client_secret="",
- client_type="confidential",
- authorization_grant_type="authorization-code",
- redirect_uris="https://example.com/callback",
- algorithm="RS256",
- organization=org,
- is_cimd_client=True,
- cimd_metadata_url=url,
- )
- # `created` is auto_now_add, so the value passed to create() above is
- # discarded on INSERT; .update() bypasses pre_save and lands it for real.
- OAuthApplication.objects.filter(pk=app.pk).update(created=created)
- return app
-
- def make_token(
- slug: str,
- org: Any,
- created_at: Any = base_time - timedelta(days=1),
- last_used_at: Any = base_time,
- cimd_url: str | None = None,
- ) -> Any:
- return CIMDVerificationToken.objects.create(
- organization=org,
- label=slug,
- secure_value=f"secure-{slug}",
- mask_value="x" * 11,
- created_at=created_at,
- last_used_at=last_used_at,
- cimd_url=cimd_url,
- )
-
- self.tokens: dict[str, Any] = {}
-
- # Unambiguous: one verified app, one corroborated token.
- org_happy = make_org("happy")
- make_app("happy", org_happy, "https://happy.example.com/.well-known/oauth-client-metadata.json")
- self.tokens["happy"] = make_token("happy", org_happy)
-
- # Two tokens on the org: can't tell which one verified the app.
- org_two_tokens = make_org("two-tokens")
- make_app("two-tokens", org_two_tokens, "https://two-tokens.example.com/.well-known/oauth-client-metadata.json")
- self.tokens["two_tokens_1"] = make_token("two-tokens-1", org_two_tokens)
- self.tokens["two_tokens_2"] = make_token("two-tokens-2", org_two_tokens)
-
- # Two apps at different URLs: ambiguous which one the token belongs to.
- org_diff_urls = make_org("diff-urls")
- make_app("diff-urls-1", org_diff_urls, "https://diff-urls-1.example.com/.well-known/oauth-client-metadata.json")
- make_app("diff-urls-2", org_diff_urls, "https://diff-urls-2.example.com/.well-known/oauth-client-metadata.json")
- self.tokens["diff_urls"] = make_token("diff-urls", org_diff_urls)
-
- # Two apps whose URLs differ only in spelling: cimd_metadata_url is unique, so this
- # is the only way two rows can name one document. They agree, so it is not ambiguous.
- org_same_url = make_org("same-url")
- make_app("same-url-1", org_same_url, "https://same-url.example.com/.well-known/oauth-client-metadata.json")
- make_app("same-url-2", org_same_url, "https://SAME-URL.example.com:443/.well-known/oauth-client-metadata.json")
- self.tokens["same_url"] = make_token("same-url", org_same_url)
-
- # Token never verified anything: no claim to any URL.
- org_never_used = make_org("never-used")
- make_app("never-used", org_never_used, "https://never-used.example.com/.well-known/oauth-client-metadata.json")
- self.tokens["never_used"] = make_token("never-used", org_never_used, last_used_at=None)
-
- # Token issued after the app self-registered, which is the ordinary sequence and
- # must still backfill.
- org_created_after = make_org("created-after")
- make_app(
- "created-after",
- org_created_after,
- "https://created-after.example.com/.well-known/oauth-client-metadata.json",
- )
- self.tokens["created_after_app"] = make_token(
- "created-after",
- org_created_after,
- created_at=base_time + timedelta(days=1),
- last_used_at=base_time + timedelta(days=2),
- )
-
- # Token already carries a deliberately-set cimd_url: replay must not clobber it.
- org_already_bound = make_org("already-bound")
- make_app(
- "already-bound",
- org_already_bound,
- "https://already-bound-app.example.com/.well-known/oauth-client-metadata.json",
- )
- self.tokens["already_bound"] = make_token(
- "already-bound", org_already_bound, cimd_url="https://already-bound.example.com/manual"
- )
-
- # App URL carries an explicit :443 that normalization must strip.
- org_port = make_org("port-443")
- make_app("port-443", org_port, "https://port-443.example.com:443/.well-known/oauth-client-metadata.json")
- self.tokens["port_443"] = make_token("port-443", org_port)
-
- # App URL carries a trailing slash that normalization must strip.
- org_slash = make_org("trailing-slash")
- make_app(
- "trailing-slash", org_slash, "https://trailing-slash.example.com/.well-known/oauth-client-metadata.json/"
- )
- self.tokens["trailing_slash"] = make_token("trailing-slash", org_slash)
-
- @parameterized.expand(
- [
- ("happy", "https://happy.example.com/.well-known/oauth-client-metadata.json"),
- ("two_tokens_1", None),
- ("two_tokens_2", None),
- ("diff_urls", None),
- ("same_url", "https://same-url.example.com/.well-known/oauth-client-metadata.json"),
- ("never_used", None),
- ("created_after_app", "https://created-after.example.com/.well-known/oauth-client-metadata.json"),
- ("already_bound", "https://already-bound.example.com/manual"),
- ("port_443", "https://port-443.example.com/.well-known/oauth-client-metadata.json"),
- ("trailing_slash", "https://trailing-slash.example.com/.well-known/oauth-client-metadata.json"),
- ]
- )
- def test_backfill_outcome(self, token_key: str, expected_cimd_url: str | None) -> None:
- token = self.CIMDVerificationToken.objects.get(pk=self.tokens[token_key].pk)
- assert token.cimd_url == expected_cimd_url
diff --git a/products/ai_observability/backend/migrations/test/__init__.py b/products/ai_observability/backend/migrations/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/ai_observability/backend/migrations/test/test_migration_0026.py b/products/ai_observability/backend/migrations/test/test_migration_0026.py
deleted file mode 100644
index 681871c17e34..000000000000
--- a/products/ai_observability/backend/migrations/test/test_migration_0026.py
+++ /dev/null
@@ -1,93 +0,0 @@
-from typing import Any
-
-from posthog.test.base import NonAtomicTestMigrations
-
-from django.db import connection
-from django.db.migrations.executor import MigrationExecutor
-
-
-# Non-atomic: the ALTER TABLE in 0026 cannot run in the same transaction as the FK-bearing
-# fixture inserts (pending trigger events).
-class RemoveTrialEvaluationsMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0023_llmpromptlabel"
- migrate_to = "0026_retire_trial_columns"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- @property
- def app(self) -> str:
- return "ai_observability"
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- Evaluation = apps.get_model("ai_observability", "Evaluation")
- EvaluationConfig = apps.get_model("ai_observability", "EvaluationConfig")
-
- org = Organization.objects.create(name="Test Organization")
- project = Project.objects.create(id=999_998, organization=org, name="Test Project")
- team = Team.objects.create(organization=org, project=project, name="Test Team")
- self.team_id = team.id
- self.organization_id = org.id
- self.project_id = project.id
-
- EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=50)
-
- def create_evaluation(name: str, status_reason: str, detail: str) -> Any:
- return Evaluation.objects.create(
- team=team,
- name=name,
- evaluation_type="llm_judge",
- output_type="boolean",
- enabled=False,
- status="error",
- status_reason=status_reason,
- status_reason_detail=detail,
- )
-
- self.trial_limit_eval_id = create_evaluation(
- "trial limit", "trial_limit_reached", "Trial evaluation limit reached."
- ).id
- self.model_not_allowed_eval_id = create_evaluation(
- "model not allowed", "model_not_allowed", "Model not on the trial plan."
- ).id
- self.control_eval_id = create_evaluation("control", "provider_key_deleted", "Key was deleted.").id
-
- def test_migration(self) -> None:
- assert self.apps is not None
- Evaluation = self.apps.get_model("ai_observability", "Evaluation")
- EvaluationConfig = self.apps.get_model("ai_observability", "EvaluationConfig")
- Team = self.apps.get_model("posthog", "Team")
-
- for eval_id in (self.trial_limit_eval_id, self.model_not_allowed_eval_id):
- migrated = Evaluation.objects.get(id=eval_id)
- self.assertEqual(migrated.status_reason, "provider_key_required")
- self.assertIsNone(migrated.status_reason_detail)
-
- control = Evaluation.objects.get(id=self.control_eval_id)
- self.assertEqual(control.status_reason, "provider_key_deleted")
- self.assertEqual(control.status_reason_detail, "Key was deleted.")
-
- # New configs no longer know about the retired columns, so the insert must be absorbed by
- # their DB defaults — pods on the previous release read these columns and must never see NULL.
- post_migration_team = Team.objects.create(
- organization_id=self.organization_id, project_id=self.project_id, name="Post-migration team"
- )
- EvaluationConfig.objects.create(team=post_migration_team)
- with connection.cursor() as cursor:
- cursor.execute(
- "SELECT trial_eval_limit, trial_evals_used FROM llm_analytics_evaluationconfig WHERE team_id = %s",
- [post_migration_team.id],
- )
- self.assertEqual(cursor.fetchone(), (100, 0))
-
- # Reverse (SET NOT NULL) must not trip over rows created after the columns were retired.
- executor = MigrationExecutor(connection)
- executor.loader.build_graph()
- executor.migrate([(self.app, self.migrate_from)])
-
- old_apps = executor.loader.project_state([(self.app, self.migrate_from)]).apps
- OldEvaluationConfig = old_apps.get_model("ai_observability", "EvaluationConfig")
- self.assertEqual(OldEvaluationConfig.objects.get(team_id=post_migration_team.id).trial_eval_limit, 100)
- self.assertEqual(OldEvaluationConfig.objects.get(team_id=self.team_id).trial_evals_used, 50)
diff --git a/products/ai_observability/backend/migrations/test/test_migration_0029.py b/products/ai_observability/backend/migrations/test/test_migration_0029.py
deleted file mode 100644
index 5277dadbdc73..000000000000
--- a/products/ai_observability/backend/migrations/test/test_migration_0029.py
+++ /dev/null
@@ -1,53 +0,0 @@
-import importlib
-
-from posthog.test.base import BaseTest
-
-from django.apps import apps
-
-from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
-from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationStatus, EvaluationStatusReason
-
-disable_reports_for_disabled_evaluations = importlib.import_module(
- "products.ai_observability.backend.migrations.0029_disable_reports_for_disabled_evaluations"
-).disable_reports_for_disabled_evaluations
-
-
-class TestDisableReportsForDisabledEvaluationsMigration(BaseTest):
- def _create_evaluation(
- self,
- status: EvaluationStatus,
- status_reason: EvaluationStatusReason | None = None,
- ) -> Evaluation:
- return Evaluation.objects.create(
- team=self.team,
- name=f"{status} evaluation",
- evaluation_type="llm_judge",
- evaluation_config={"prompt": "test"},
- output_type="boolean",
- output_config={},
- enabled=status == EvaluationStatus.ACTIVE,
- status=status,
- status_reason=status_reason,
- created_by=self.user,
- conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
- )
-
- def test_only_paused_evaluations_disable_their_reports(self) -> None:
- paused_report = EvaluationReport.objects.create(
- team=self.team,
- evaluation=self._create_evaluation(EvaluationStatus.PAUSED),
- )
- errored_report = EvaluationReport.objects.create(
- team=self.team,
- evaluation=self._create_evaluation(
- EvaluationStatus.ERROR,
- EvaluationStatusReason.PROVIDER_KEY_RATE_LIMITED,
- ),
- )
-
- disable_reports_for_disabled_evaluations(apps, None)
-
- paused_report.refresh_from_db()
- errored_report.refresh_from_db()
- self.assertFalse(paused_report.enabled)
- self.assertTrue(errored_report.enabled)
diff --git a/products/canvas/backend/tests/test_migration_0002_desktop_tree.py b/products/canvas/backend/tests/test_migration_0002_desktop_tree.py
deleted file mode 100644
index 1fc0f54861a2..000000000000
--- a/products/canvas/backend/tests/test_migration_0002_desktop_tree.py
+++ /dev/null
@@ -1,79 +0,0 @@
-from typing import Any
-
-from posthog.test.base import NonAtomicTestMigrations
-
-
-class MigrateDesktopTreeHomeCanvasTest(NonAtomicTestMigrations):
- """0002 converts desktop file-system rows to first-class models. Two folder
- rows can resolve to the same channel and both carry meta.homeCanvasId (e.g.
- a path-renamed duplicate); is_home is unique per channel, so only the first
- may win or the second insert aborts the migration with an IntegrityError.
- """
-
- migrate_from = "0001_initial"
- migrate_to = "0003_migrate_desktop_tree"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- @property
- def app(self) -> str:
- return "canvas"
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- User = apps.get_model("posthog", "User")
- FileSystem = apps.get_model("posthog", "FileSystem")
-
- org = Organization.objects.create(name="Org")
- project = Project.objects.create(id=999_997, organization=org, name="Proj")
- team = Team.objects.create(organization=org, project=project, name="Team")
- user = User.objects.create(email="[email protected]", distinct_id="c-distinct")
- self.team_id = team.id
-
- # One top-level folder ("general") whose tree holds a home canvas, plus a
- # second same-named folder row (a duplicate) ALSO pointing at a home
- # canvas. Both resolve to the same "general" channel.
- folder_a = FileSystem.objects.create(
- team=team,
- path="general",
- depth=1,
- type="folder",
- surface="desktop",
- created_by=user,
- meta={"homeCanvasId": "11111111-1111-1111-1111-111111111111"},
- )
- folder_b = FileSystem.objects.create(
- team=team,
- path="general",
- depth=1,
- type="folder",
- surface="desktop",
- created_by=user,
- meta={"homeCanvasId": "22222222-2222-2222-2222-222222222222"},
- )
- self.folder_a_id = folder_a.id
- self.folder_b_id = folder_b.id
-
- for home_id, path in (
- ("11111111-1111-1111-1111-111111111111", "general/Home A"),
- ("22222222-2222-2222-2222-222222222222", "general/Home B"),
- ):
- FileSystem.objects.create(
- id=home_id,
- team=team,
- path=path,
- depth=2,
- type="dashboard",
- surface="desktop",
- created_by=user,
- meta={"channelId": str(folder_a.id)},
- )
-
- def test_two_home_canvas_pointers_in_one_channel_do_not_crash(self) -> None:
- Canvas = self.apps.get_model("canvas", "Canvas") # type: ignore[union-attr]
- canvases = list(Canvas.objects.filter(team_id=self.team_id))
- # Both dashboards migrated; exactly one is_home (no unique-constraint crash).
- assert len(canvases) == 2
- assert sum(1 for c in canvases if c.is_home) == 1
diff --git a/products/data_modeling/backend/migrations/test/__init__.py b/products/data_modeling/backend/migrations/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/data_modeling/backend/migrations/test/test_migration_0006.py b/products/data_modeling/backend/migrations/test/test_migration_0006.py
deleted file mode 100644
index cb0022587f8a..000000000000
--- a/products/data_modeling/backend/migrations/test/test_migration_0006.py
+++ /dev/null
@@ -1,96 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-# skipped in prod because slow. passes locally. to run this test comment this out
-pytestmark = pytest.mark.skip("historical migration tests slow overall test run")
-
-
-class BackfillNodesEdgesMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0005_remove_node_name_unique_within_team_dag_and_more"
- migrate_to = "0006_backfill_nodes_edges_from_saved_queries"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- @property
- def app(self) -> str:
- return "data_modeling"
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- DataWarehouseSavedQuery = apps.get_model("data_warehouse", "DataWarehouseSavedQuery")
- Node = apps.get_model("data_modeling", "Node")
-
- org = Organization.objects.create(name="Test Organization")
- proj = Project.objects.create(id=999999, organization=org, name="Test Project")
- team = Team.objects.create(organization=org, project=proj, name="Test Team")
- self.team_id = team.id
- # case 1: saved query without node → SHOULD be backfilled
- self.new_saved_query = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="new_view",
- query={"kind": "HogQLQuery", "query": "SELECT 1"},
- deleted=False,
- )
- # case 2: saved query with existing node → should NOT be backfilled (already handled)
- self.existing_saved_query = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="existing_view",
- query={"kind": "HogQLQuery", "query": "SELECT 2"},
- deleted=False,
- )
- Node.objects.create(
- team=team,
- saved_query=self.existing_saved_query,
- name="existing_view",
- dag_id=f"posthog_{team.id}",
- type="view",
- properties={},
- )
- # case 3: deleted saved query → should NOT be backfilled
- self.deleted_saved_query = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="deleted_view",
- query={"kind": "HogQLQuery", "query": "SELECT 3"},
- deleted=True,
- )
- # case 4: saved query with dependency → should create node with edge
- self.dependent_saved_query = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="dependent_view",
- query={"kind": "HogQLQuery", "query": "SELECT * FROM new_view"},
- deleted=False,
- )
-
- def test_migration(self) -> None:
- assert self.apps is not None
-
- Node = self.apps.get_model("data_modeling", "Node")
- Edge = self.apps.get_model("data_modeling", "Edge")
-
- # case 1: new saved query without existing node → backfilled
- new_node = Node.objects.filter(saved_query_id=self.new_saved_query.id).first()
- self.assertIsNotNone(new_node)
- self.assertEqual(new_node.name, "new_view")
- self.assertTrue(new_node.properties.get("backfilled"))
- # case 2: existing saved query with node → NOT backfilled (node exists but no backfilled property)
- existing_node = Node.objects.filter(saved_query_id=self.existing_saved_query.id).first()
- self.assertIsNotNone(existing_node)
- self.assertFalse(existing_node.properties.get("backfilled"))
- # case 3: deleted saved query → NOT backfilled
- deleted_node = Node.objects.filter(saved_query_id=self.deleted_saved_query.id).first()
- self.assertIsNone(deleted_node)
- # case 4: dependent saved query → backfilled with edge
- dependent_node = Node.objects.filter(saved_query_id=self.dependent_saved_query.id).first()
- self.assertIsNotNone(dependent_node)
- self.assertEqual(dependent_node.name, "dependent_view")
- self.assertTrue(dependent_node.properties.get("backfilled"))
- # edge from new_view to dependent_view
- edge = Edge.objects.filter(source=new_node, target=dependent_node).first()
- self.assertIsNotNone(edge)
- self.assertTrue(edge.properties.get("backfilled"))
- # total: 3 nodes (new_view backfilled, existing_view pre-existing, dependent_view backfilled)
- self.assertEqual(Node.objects.filter(team_id=self.team_id).count(), 3)
diff --git a/products/data_warehouse/backend/migrations/test/test_migration_0013.py b/products/data_warehouse/backend/migrations/test/test_migration_0013.py
deleted file mode 100644
index 22a1f03f4118..000000000000
--- a/products/data_warehouse/backend/migrations/test/test_migration_0013.py
+++ /dev/null
@@ -1,232 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-from parameterized import parameterized
-
-from products.warehouse_sources.backend.facade.models import (
- DataWarehouseCredential as DataWarehouseCredentialModel,
- DataWarehouseTable as DataWarehouseTableModel,
- ExternalDataSource as ExternalDataSourceModel,
-)
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class DeletingCredentialsMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0012_externaldatasource_description"
- migrate_to = "0013_credential_deletion"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- @property
- def app(self) -> str:
- return "data_warehouse"
-
- def setUp(self):
- """Override to specify posthog migration state alongside data_warehouse migration"""
- from django.db import connection
- from django.db.migrations.executor import MigrationExecutor
-
- # Migrate from both data_warehouse 0012 AND posthog 0955 (which includes default_anonymize_ips)
- migrate_from = [
- ("data_warehouse", self.migrate_from),
- ("posthog", "0955_alter_organization_is_ai_data_processing_approved"),
- ]
- migrate_to = [("data_warehouse", self.migrate_to)]
-
- executor = MigrationExecutor(connection)
- old_apps = executor.loader.project_state(migrate_from).apps
-
- # Reverse to the original migration
- executor.migrate(migrate_from)
-
- self.setUpBeforeMigration(old_apps)
-
- # Run the migration to test
- executor = MigrationExecutor(connection)
- executor.loader.build_graph() # reload
- executor.migrate(migrate_to)
-
- self.apps = executor.loader.project_state(migrate_to).apps
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- DataWarehouseTable: DataWarehouseTableModel = apps.get_model("data_warehouse", "DataWarehouseTable")
- DataWarehouseCredential: DataWarehouseCredentialModel = apps.get_model(
- "data_warehouse", "DataWarehouseCredential"
- )
- ExternalDataSource: ExternalDataSourceModel = apps.get_model("data_warehouse", "ExternalDataSource")
-
- # At migration 0012, posthog migration 0955 has been applied (per dependency),
- # which means default_anonymize_ips field exists and needs to be set explicitly
- org = Organization.objects.create(name="Test Organization", default_anonymize_ips=False)
- proj = Project.objects.create(id=999999, organization=org, name="Test Project")
- team = Team.objects.create(organization=org, project=proj, name="Test Team")
-
- self.DataWarehouseTable = DataWarehouseTable
- self.DataWarehouseCredential = DataWarehouseCredential
- self.ExternalDataSource = ExternalDataSource
-
- self.credentials = {}
- self.tables = {}
- self.sources = {}
-
- # Credential 1: Used by table with external_data_source_id (should be deleted)
- self.credentials["to_delete_1"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key1", access_secret="secret1"
- )
-
- # Credential 2: Used by table with external_data_source_id (should be deleted)
- self.credentials["to_delete_2"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key2", access_secret="secret2"
- )
-
- # Credential 3: Used by table WITHOUT external_data_source_id (should be kept)
- self.credentials["to_keep_1"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key3", access_secret="secret3"
- )
-
- # Credential 4: Orphaned credential not used by any table
- self.credentials["to_keep_2"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key4", access_secret="secret4"
- )
-
- # Credential 5: Not referenced by any table (should be kept)
- self.credentials["unused"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key5", access_secret="secret5"
- )
-
- # External data sources
- self.sources["source_1"] = ExternalDataSource.objects.create(
- team=team, source_id="src1", connection_id="conn1", status="Completed"
- )
-
- self.sources["source_2"] = ExternalDataSource.objects.create(
- team=team, source_id="src2", connection_id="conn2", status="Completed"
- )
-
- # Table 1: Has external_data_source_id AND credential_id (credential should be deleted, credential_id should be set to NULL)
- self.tables["with_source_and_cred_1"] = DataWarehouseTable.objects.create(
- team=team,
- name="table1",
- format="Parquet",
- url_pattern="s3://bucket/table1",
- external_data_source=self.sources["source_1"],
- credential=self.credentials["to_delete_1"],
- )
-
- # Table 2: Has external_data_source_id AND credential_id with different credential (credential should be deleted, credential_id should be set to NULL)
- self.tables["with_source_and_cred_2"] = DataWarehouseTable.objects.create(
- team=team,
- name="table2",
- format="Parquet",
- url_pattern="s3://bucket/table2",
- external_data_source=self.sources["source_2"],
- credential=self.credentials["to_delete_2"],
- )
-
- # Table 3: Has external_data_source_id but credential_id is NULL (nothing should change)
- self.tables["with_source_no_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="table3",
- format="Parquet",
- url_pattern="s3://bucket/table3",
- external_data_source=self.sources["source_1"],
- credential=None,
- )
-
- # Table 4: Has credential_id but NO external_data_source_id (credential should be kept, credential_id should remain)
- self.tables["no_source_with_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="table4",
- format="Parquet",
- url_pattern="s3://bucket/table4",
- external_data_source=None,
- credential=self.credentials["to_keep_1"],
- )
-
- # Table 5: Has neither external_data_source_id nor credential_id (nothing should change)
- self.tables["no_source_no_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="table5",
- format="Parquet",
- url_pattern="s3://bucket/table5",
- external_data_source=None,
- credential=None,
- )
-
- # Table 6: Multiple tables referencing same credential with external_data_source_id
- self.tables["duplicate_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="table6",
- format="Parquet",
- url_pattern="s3://bucket/table6",
- external_data_source=self.sources["source_2"],
- credential=self.credentials["to_delete_1"], # Same as table1
- )
-
- @parameterized.expand(
- [
- ("with_source_and_cred_1", None),
- ("with_source_and_cred_2", None),
- ("duplicate_cred", None),
- ]
- )
- def test_tables_with_source_and_credential_have_credential_nulled(self, table_key, expected_credential):
- """Tables with both external_data_source_id and credential_id should have credential_id set to NULL"""
- table = self.DataWarehouseTable.objects.get(id=self.tables[table_key].id)
- self.assertEqual(table.credential_id, expected_credential)
-
- @parameterized.expand(
- [
- ("with_source_no_cred", None),
- ("no_source_no_cred", None),
- ]
- )
- def test_tables_without_credential_remain_unchanged(self, table_key, expected_credential):
- """Tables without credential_id should remain unchanged"""
-
- table = self.DataWarehouseTable.objects.get(id=self.tables[table_key].id)
- self.assertEqual(table.credential_id, expected_credential)
-
- def test_table_without_source_keeps_credential(self):
- """Tables without external_data_source_id should keep their credential_id"""
-
- table = self.DataWarehouseTable.objects.get(id=self.tables["no_source_with_cred"].id)
- self.assertEqual(table.credential_id, self.credentials["to_keep_1"].id)
-
- @parameterized.expand(
- [
- ("to_delete_1",),
- ("to_delete_2",),
- ]
- )
- def test_credentials_referenced_by_tables_with_source_are_deleted(self, credential_key):
- """Credentials referenced by tables with external_data_source_id should be deleted"""
- with self.assertRaises(self.DataWarehouseCredential.DoesNotExist):
- self.DataWarehouseCredential.objects.get(id=self.credentials[credential_key].id)
-
- @parameterized.expand(
- [
- ("to_keep_1",),
- ("to_keep_2",),
- ("unused",),
- ]
- )
- def test_credentials_not_referenced_or_without_source_are_kept(self, credential_key):
- """Credentials not referenced by tables with external_data_source_id should be kept"""
- credential = self.DataWarehouseCredential.objects.get(id=self.credentials[credential_key].id)
- self.assertIsNotNone(credential)
-
- def test_all_table_counts(self):
- """Verify all tables still exist after migration"""
- self.assertEqual(self.DataWarehouseTable.objects.count(), 6)
-
- def test_credential_counts(self):
- """Verify correct number of credentials deleted"""
- # Started with 5 credentials, 2 should be deleted (to_delete_1 and to_delete_2)
- self.assertEqual(self.DataWarehouseCredential.objects.count(), 3)
diff --git a/products/data_warehouse/backend/migrations/test/test_migration_0014.py b/products/data_warehouse/backend/migrations/test/test_migration_0014.py
deleted file mode 100644
index 063a76c6f005..000000000000
--- a/products/data_warehouse/backend/migrations/test/test_migration_0014.py
+++ /dev/null
@@ -1,191 +0,0 @@
-from typing import Any
-
-import pytest
-from posthog.test.base import NonAtomicTestMigrations
-
-from parameterized import parameterized
-
-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery as DataWarehouseSavedQueryModel
-from products.warehouse_sources.backend.facade.models import (
- DataWarehouseCredential as DataWarehouseCredentialModel,
- DataWarehouseTable as DataWarehouseTableModel,
-)
-
-pytestmark = pytest.mark.skip("old migrations slow overall test run down")
-
-
-class MatViewCredentialDeletionMigrationTest(NonAtomicTestMigrations):
- migrate_from = "0013_credential_deletion"
- migrate_to = "0014_mat_view_credential_deletion"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- @property
- def app(self) -> str:
- return "data_warehouse"
-
- def setUp(self):
- """Override to specify posthog migration state alongside data_warehouse migration"""
- from django.db import connection
- from django.db.migrations.executor import MigrationExecutor
-
- migrate_from = [
- ("data_warehouse", self.migrate_from),
- ("posthog", "0955_alter_organization_is_ai_data_processing_approved"),
- ]
- migrate_to = [("data_warehouse", self.migrate_to)]
-
- executor = MigrationExecutor(connection)
- old_apps = executor.loader.project_state(migrate_from).apps
-
- executor.migrate(migrate_from)
-
- self.setUpBeforeMigration(old_apps)
-
- executor = MigrationExecutor(connection)
- executor.loader.build_graph()
- executor.migrate(migrate_to)
-
- self.apps = executor.loader.project_state(migrate_to).apps
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- Project = apps.get_model("posthog", "Project")
- Team = apps.get_model("posthog", "Team")
- DataWarehouseTable: DataWarehouseTableModel = apps.get_model("data_warehouse", "DataWarehouseTable")
- DataWarehouseCredential: DataWarehouseCredentialModel = apps.get_model(
- "data_warehouse", "DataWarehouseCredential"
- )
- DataWarehouseSavedQuery: DataWarehouseSavedQueryModel = apps.get_model(
- "data_warehouse", "DataWarehouseSavedQuery"
- )
-
- org = Organization.objects.create(name="Test Organization", default_anonymize_ips=False)
- proj = Project.objects.create(id=999999, organization=org, name="Test Project")
- team = Team.objects.create(organization=org, project=proj, name="Test Team")
-
- self.DataWarehouseTable = DataWarehouseTable
- self.DataWarehouseCredential = DataWarehouseCredential
- self.DataWarehouseSavedQuery = DataWarehouseSavedQuery
-
- self.credentials = {}
- self.tables = {}
- self.saved_queries = {}
-
- # Credential 1: Used by table that is materialized view (should be nulled)
- self.credentials["mat_view_cred"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key1", access_secret="secret1"
- )
-
- # Credential 2: Used by table that is materialized view (should be nulled)
- self.credentials["mat_view_cred_2"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key2", access_secret="secret2"
- )
-
- # Credential 3: Used by regular table (should be kept)
- self.credentials["regular_table_cred"] = DataWarehouseCredential.objects.create(
- team=team, access_key="key3", access_secret="secret3"
- )
-
- # Table 1: Has credential and is referenced by a saved query (credential should be nulled)
- self.tables["materialized_with_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="materialized_table_1",
- format="Parquet",
- url_pattern="s3://bucket/mat_table1",
- credential=self.credentials["mat_view_cred"],
- )
-
- # Table 2: Has credential and is referenced by a saved query (credential should be nulled)
- self.tables["materialized_with_cred_2"] = DataWarehouseTable.objects.create(
- team=team,
- name="materialized_table_2",
- format="Parquet",
- url_pattern="s3://bucket/mat_table2",
- credential=self.credentials["mat_view_cred_2"],
- )
-
- # Table 3: Has credential but NOT referenced by saved query (credential should remain)
- self.tables["regular_with_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="regular_table",
- format="Parquet",
- url_pattern="s3://bucket/regular_table",
- credential=self.credentials["regular_table_cred"],
- )
-
- # Table 4: No credential and is referenced by saved query (nothing should change)
- self.tables["materialized_no_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="materialized_table_3",
- format="Parquet",
- url_pattern="s3://bucket/mat_table3",
- credential=None,
- )
-
- # Table 5: No credential and NOT referenced by saved query (nothing should change)
- self.tables["regular_no_cred"] = DataWarehouseTable.objects.create(
- team=team,
- name="regular_table_2",
- format="Parquet",
- url_pattern="s3://bucket/regular_table2",
- credential=None,
- )
-
- # Saved queries (materialized views) referencing tables
- self.saved_queries["mat_view_1"] = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="materialized_view_1",
- query={"query": "SELECT * FROM materialized_table_1"},
- table=self.tables["materialized_with_cred"],
- )
-
- self.saved_queries["mat_view_2"] = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="materialized_view_2",
- query={"query": "SELECT * FROM materialized_table_2"},
- table=self.tables["materialized_with_cred_2"],
- )
-
- self.saved_queries["mat_view_3"] = DataWarehouseSavedQuery.objects.create(
- team=team,
- name="materialized_view_3",
- query={"query": "SELECT * FROM materialized_table_3"},
- table=self.tables["materialized_no_cred"],
- )
-
- @parameterized.expand(
- [
- ("materialized_with_cred", None),
- ("materialized_with_cred_2", None),
- ("materialized_no_cred", None),
- ]
- )
- def test_materialized_view_tables_have_credential_nulled(self, table_key, expected_credential):
- """Tables referenced by saved queries should have credential_id set to NULL"""
- table = self.DataWarehouseTable.objects.get(id=self.tables[table_key].id)
- self.assertEqual(table.credential_id, expected_credential)
-
- @parameterized.expand(
- [
- ("regular_with_cred", "regular_table_cred"),
- ("regular_no_cred", None),
- ]
- )
- def test_non_materialized_tables_remain_unchanged(self, table_key, credential_key):
- """Tables not referenced by saved queries should keep their credentials"""
- table = self.DataWarehouseTable.objects.get(id=self.tables[table_key].id)
- expected_credential_id = self.credentials[credential_key].id if credential_key else None
- self.assertEqual(table.credential_id, expected_credential_id)
-
- def test_all_credentials_still_exist(self):
- """All credentials should still exist after migration"""
- self.assertEqual(self.DataWarehouseCredential.objects.count(), 3)
-
- def test_all_tables_still_exist(self):
- """All tables should still exist after migration"""
- self.assertEqual(self.DataWarehouseTable.objects.count(), 5)
-
- def test_all_saved_queries_still_exist(self):
- """All saved queries should still exist after migration"""
- self.assertEqual(self.DataWarehouseSavedQuery.objects.count(), 3)
diff --git a/products/data_warehouse/backend/migrations/test/test_migration_0020.py b/products/data_warehouse/backend/migrations/test/test_migration_0020.py
deleted file mode 100644
index 6434a237fca6..000000000000
--- a/products/data_warehouse/backend/migrations/test/test_migration_0020.py
+++ /dev/null
@@ -1,115 +0,0 @@
-import uuid
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.data_warehouse.backend.migrations.0020_migrate_github_job_inputs_to_auth_type"
-)
-migrate_github_job_inputs = migration_module.migrate_github_job_inputs
-reverse_migrate_github_job_inputs = migration_module.reverse_migrate_github_job_inputs
-
-
-def github_source_factory(team):
- def _create(job_inputs):
- return ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Github",
- job_inputs=job_inputs,
- )
-
- return _create
-
-
-class TestMigrateGithubJobInputs:
- @pytest.mark.parametrize(
- "input_job_inputs, expected_job_inputs",
- [
- (
- {"personal_access_token": "ghp_test123", "repository": "owner/repo"},
- {
- "auth_method": {"selection": "pat", "personal_access_token": "ghp_test123"},
- "repository": "owner/repo",
- },
- ),
- (
- {"github_integration_id": 42, "repository": "org/project"},
- {
- "auth_method": {"selection": "oauth", "github_integration_id": "42"},
- "repository": "org/project",
- },
- ),
- (
- {
- "auth_method": {"selection": "pat", "personal_access_token": "ghp_existing"},
- "repository": "owner/repo",
- },
- {
- "auth_method": {"selection": "pat", "personal_access_token": "ghp_existing"},
- "repository": "owner/repo",
- },
- ),
- ],
- ids=["pat_to_nested", "oauth_to_nested", "already_migrated_skipped"],
- )
- def test_forward_migration(self, input_job_inputs, expected_job_inputs, github_source_factory):
- source = github_source_factory(input_job_inputs)
-
- migrate_github_job_inputs(apps, None)
-
- source.refresh_from_db()
- assert source.job_inputs == expected_job_inputs
-
- @pytest.mark.parametrize(
- "input_job_inputs, expected_job_inputs",
- [
- (
- {
- "auth_method": {"selection": "pat", "personal_access_token": "ghp_test123"},
- "repository": "owner/repo",
- },
- {"personal_access_token": "ghp_test123", "repository": "owner/repo"},
- ),
- (
- {
- "auth_method": {"selection": "oauth", "github_integration_id": "42"},
- "repository": "org/project",
- },
- {"github_integration_id": "42", "repository": "org/project"},
- ),
- ],
- ids=["nested_pat_to_flat", "nested_oauth_to_flat"],
- )
- def test_reverse_migration(self, input_job_inputs, expected_job_inputs, github_source_factory):
- source = github_source_factory(input_job_inputs)
-
- reverse_migrate_github_job_inputs(apps, None)
-
- source.refresh_from_db()
- assert source.job_inputs == expected_job_inputs
-
- def test_non_github_sources_unaffected(self, team):
- stripe_source = ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Stripe",
- job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"}},
- )
-
- migrate_github_job_inputs(apps, None)
-
- stripe_source.refresh_from_db()
- assert stripe_source.job_inputs == {"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"}}
diff --git a/products/data_warehouse/backend/migrations/test/test_migration_0041.py b/products/data_warehouse/backend/migrations/test/test_migration_0041.py
deleted file mode 100644
index de87b9bbb5ab..000000000000
--- a/products/data_warehouse/backend/migrations/test/test_migration_0041.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import uuid
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.data_warehouse.backend.migrations.0041_migrate_stripe_job_inputs_to_auth_type"
-)
-migrate_stripe_job_inputs = migration_module.migrate_stripe_job_inputs
-reverse_migrate_stripe_job_inputs = migration_module.reverse_migrate_stripe_job_inputs
-
-
-def stripe_source_factory(team):
- def _create(job_inputs):
- return ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Stripe",
- job_inputs=job_inputs,
- )
-
- return _create
-
-
-class TestMigrateStripeJobInputs:
- @pytest.mark.parametrize(
- "input_job_inputs, expected_job_inputs",
- [
- (
- {"stripe_secret_key": "rk_live_test123", "stripe_account_id": "acct_123"},
- {
- "auth_method": {"selection": "api_key", "stripe_secret_key": "rk_live_test123"},
- "stripe_account_id": "acct_123",
- },
- ),
- (
- {
- "auth_method": {"selection": "api_key", "stripe_secret_key": "rk_live_existing"},
- "stripe_account_id": "acct_456",
- },
- {
- "auth_method": {"selection": "api_key", "stripe_secret_key": "rk_live_existing"},
- "stripe_account_id": "acct_456",
- },
- ),
- ],
- ids=["api_key_to_nested", "already_migrated_skipped"],
- )
- def test_forward_migration(self, input_job_inputs, expected_job_inputs, stripe_source_factory):
- source = stripe_source_factory(input_job_inputs)
-
- migrate_stripe_job_inputs(apps, None)
-
- source.refresh_from_db()
- assert source.job_inputs == expected_job_inputs
-
- @pytest.mark.parametrize(
- "input_job_inputs, expected_job_inputs",
- [
- (
- {
- "auth_method": {"selection": "api_key", "stripe_secret_key": "rk_live_test123"},
- "stripe_account_id": "acct_123",
- },
- {"stripe_secret_key": "rk_live_test123", "stripe_account_id": "acct_123"},
- ),
- ],
- ids=["nested_api_key_to_flat"],
- )
- def test_reverse_migration(self, input_job_inputs, expected_job_inputs, stripe_source_factory):
- source = stripe_source_factory(input_job_inputs)
-
- reverse_migrate_stripe_job_inputs(apps, None)
-
- source.refresh_from_db()
- assert source.job_inputs == expected_job_inputs
-
- def test_non_stripe_sources_unaffected(self, team):
- github_source = ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Github",
- job_inputs={"personal_access_token": "ghp_test123"},
- )
-
- migrate_stripe_job_inputs(apps, None)
-
- github_source.refresh_from_db()
- assert github_source.job_inputs == {"personal_access_token": "ghp_test123"}
diff --git a/products/data_warehouse/backend/migrations/test/test_migration_0046.py b/products/data_warehouse/backend/migrations/test/test_migration_0046.py
deleted file mode 100644
index 5a4ad0fe011c..000000000000
--- a/products/data_warehouse/backend/migrations/test/test_migration_0046.py
+++ /dev/null
@@ -1,163 +0,0 @@
-import uuid
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.data_warehouse.backend.migrations.0046_fix_vitally_region_job_inputs"
-)
-forwards = migration_module.forwards
-
-
-def vitally_source_factory(team):
- def _create(job_inputs):
- return ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Vitally",
- job_inputs=job_inputs,
- )
-
- return _create
-
-
-class TestFixVitallyRegionJobInputs:
- @pytest.mark.parametrize(
- "input_job_inputs, expected_job_inputs",
- [
- (
- # Exact shape reported from prod.
- {
- "region": {
- "selection": {"selection": "EU", "subdomain": ""},
- "subdomain": "None",
- }
- },
- {"region": {"selection": "EU", "subdomain": ""}},
- ),
- (
- # US variant — prefer the outer subdomain when it's a real value.
- {
- "region": {
- "selection": {"selection": "US", "subdomain": ""},
- "subdomain": "acme",
- }
- },
- {"region": {"selection": "US", "subdomain": "acme"}},
- ),
- (
- # Outer subdomain is garbage, inner has the real one.
- {
- "region": {
- "selection": {"selection": "US", "subdomain": "acme"},
- "subdomain": "None",
- }
- },
- {"region": {"selection": "US", "subdomain": "acme"}},
- ),
- (
- # Neither subdomain is usable — fall back to empty string.
- {
- "region": {
- "selection": {"selection": "EU", "subdomain": ""},
- "subdomain": "",
- }
- },
- {"region": {"selection": "EU", "subdomain": ""}},
- ),
- (
- # Other sibling keys on job_inputs are preserved.
- {
- "secret_token": "sk_live_abc",
- "region": {
- "selection": {"selection": "EU", "subdomain": ""},
- "subdomain": "None",
- },
- },
- {
- "secret_token": "sk_live_abc",
- "region": {"selection": "EU", "subdomain": ""},
- },
- ),
- ],
- ids=[
- "reported_eu_shape_heals",
- "us_outer_subdomain_preserved",
- "us_falls_back_to_inner_subdomain",
- "no_usable_subdomain_defaults_to_empty",
- "sibling_keys_preserved",
- ],
- )
- def test_forward_migration_heals_corrupted_rows(
- self, input_job_inputs, expected_job_inputs, vitally_source_factory
- ):
- source = vitally_source_factory(input_job_inputs)
-
- forwards(apps, None)
-
- source.refresh_from_db()
- assert source.job_inputs == expected_job_inputs
-
- @pytest.mark.parametrize(
- "job_inputs",
- [
- # Canonical shape — no-op.
- {"region": {"selection": "EU", "subdomain": ""}},
- {"region": {"selection": "US", "subdomain": "acme"}},
- # No region at all.
- {"secret_token": "sk_live_abc"},
- # region is not a dict.
- {"region": "EU"},
- # region.selection is a dict but the inner selection is unrecognised — leave it alone
- # so it surfaces in an audit rather than being silently mangled.
- {"region": {"selection": {"foo": "bar"}, "subdomain": ""}},
- {"region": {"selection": {"selection": "ZZ", "subdomain": ""}, "subdomain": ""}},
- # Non-dict job_inputs.
- None,
- ],
- ids=[
- "canonical_eu",
- "canonical_us",
- "no_region_key",
- "region_is_string",
- "inner_selection_not_a_region_key",
- "inner_selection_unrecognised_literal",
- "job_inputs_is_none",
- ],
- )
- def test_forward_migration_leaves_other_shapes_untouched(self, job_inputs, vitally_source_factory):
- source = vitally_source_factory(job_inputs)
-
- forwards(apps, None)
-
- source.refresh_from_db()
- assert source.job_inputs == job_inputs
-
- def test_non_vitally_sources_unaffected(self, team):
- # Deliberately construct a non-Vitally source whose `region.selection` is a dict —
- # the migration must not touch anything that isn't Vitally.
- stripe_source = ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Stripe",
- job_inputs={"region": {"selection": {"selection": "EU", "subdomain": ""}, "subdomain": "None"}},
- )
-
- forwards(apps, None)
-
- stripe_source.refresh_from_db()
- assert stripe_source.job_inputs == {
- "region": {"selection": {"selection": "EU", "subdomain": ""}, "subdomain": "None"}
- }
diff --git a/products/early_access_features/backend/test/test_migration_backfill.py b/products/early_access_features/backend/test/test_migration_backfill.py
deleted file mode 100644
index a1bd43d0dd37..000000000000
--- a/products/early_access_features/backend/test/test_migration_backfill.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import importlib
-
-from posthog.test.base import APIBaseTest
-
-from django.apps import apps
-
-from products.early_access_features.backend.models import EarlyAccessFeature
-from products.feature_flags.backend.models.feature_flag import FeatureFlag
-
-m8 = importlib.import_module(
- "products.early_access_features.backend.migrations.0008_backfill_earlyaccessfeature_created_by"
-)
-
-
-class TestEarlyAccessFeatureCreatedByBackfill(APIBaseTest):
- def test_backfills_from_flag_creator_and_leaves_others_untouched(self) -> None:
- other_user = self._create_user("[email protected]")
- flag = FeatureFlag.objects.create(team=self.team, key="flag-with-creator", created_by=other_user)
- unset = EarlyAccessFeature.objects.create(team=self.team, name="unset", stage="beta", feature_flag=flag)
- already_set = EarlyAccessFeature.objects.create(
- team=self.team, name="already-set", stage="beta", feature_flag=flag, created_by=self.user
- )
- flagless = EarlyAccessFeature.objects.create(team=self.team, name="flagless", stage="beta")
-
- m8.backfill_created_by(apps, None)
-
- unset.refresh_from_db()
- already_set.refresh_from_db()
- flagless.refresh_from_db()
- assert unset.created_by_id == other_user.id
- assert already_set.created_by_id == self.user.id
- assert flagless.created_by_id is None
diff --git a/products/feature_flags/backend/test/test_migration_0011_clean_filters.py b/products/feature_flags/backend/test/test_migration_0011_clean_filters.py
deleted file mode 100644
index 15e85ae243ca..000000000000
--- a/products/feature_flags/backend/test/test_migration_0011_clean_filters.py
+++ /dev/null
@@ -1,203 +0,0 @@
-from importlib import import_module
-from typing import Any
-
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from products.feature_flags.backend.filters_validation import collect_filters_violations
-
-_migration = import_module("products.feature_flags.backend.migrations.0011_clean_flag_filters_recoverable_violations")
-_clean_filters = _migration._clean_filters
-
-# (name, dirty, expected, expected_rules, audit_clean_after)
-# audit_clean_after is False for cases that deliberately leave unrecoverable
-# violations in place (unknown operators, junk rollout strings, bool values).
-CASES: list[tuple[str, dict[str, Any], dict[str, Any] | None, set[str], bool]] = [
- (
- "payload_raw_string_reencoded_valid_json_untouched",
- {
- "groups": [],
- "multivariate": {
- "variants": [{"key": "v1", "rollout_percentage": 50.0}, {"key": "v2", "rollout_percentage": 50.0}]
- },
- "payloads": {"v1": "hello world", "v2": '{"a": 1}'},
- },
- {
- "groups": [],
- "multivariate": {
- "variants": [{"key": "v1", "rollout_percentage": 50.0}, {"key": "v2", "rollout_percentage": 50.0}]
- },
- "payloads": {"v1": '"hello world"', "v2": '{"a": 1}'},
- },
- {"payload_not_json"},
- True,
- ),
- (
- "payload_nan_token_reencoded_as_string",
- {"groups": [], "payloads": {"true": "NaN"}},
- {"groups": [], "payloads": {"true": '"NaN"'}},
- {"payload_not_json"},
- True,
- ),
- (
- "in_not_in_remapped_on_person",
- {
- "groups": [
- {
- "properties": [
- {"key": "email", "type": "person", "operator": "in", "value": ["a", "b"]},
- {"key": "plan", "type": "person", "operator": "not_in", "value": ["x"]},
- ]
- }
- ]
- },
- {
- "groups": [
- {
- "properties": [
- {"key": "email", "type": "person", "operator": "exact", "value": ["a", "b"]},
- {"key": "plan", "type": "person", "operator": "is_not", "value": ["x"]},
- ]
- }
- ]
- },
- {"in_not_in_non_cohort"},
- True,
- ),
- (
- "cohort_in_operator_left_untouched",
- {"groups": [{"properties": [{"key": "id", "type": "cohort", "operator": "in", "value": 42}]}]},
- None,
- set(),
- True,
- ),
- (
- "operator_typos_mapped_unknown_left",
- {
- "groups": [
- {
- "properties": [
- {"key": "k", "type": "person", "operator": "contains", "value": "x"},
- {"key": "k2", "type": "person", "operator": "matches regex", "value": "^a"},
- {"key": "k3", "type": "person", "operator": "is_contained_within", "value": "y"},
- ]
- }
- ]
- },
- {
- "groups": [
- {
- "properties": [
- {"key": "k", "type": "person", "operator": "icontains", "value": "x"},
- {"key": "k2", "type": "person", "operator": "regex", "value": "^a"},
- {"key": "k3", "type": "person", "operator": "is_contained_within", "value": "y"},
- ]
- }
- ]
- },
- {"operator_typo"},
- False,
- ),
- (
- "numeric_string_rollout_coerced_junk_and_out_of_range_left",
- {"groups": [{"rollout_percentage": "50"}, {"rollout_percentage": "abc"}, {"rollout_percentage": "150"}]},
- {"groups": [{"rollout_percentage": 50.0}, {"rollout_percentage": "abc"}, {"rollout_percentage": "150"}]},
- {"rollout_percentage_string"},
- False,
- ),
- (
- "dangling_variant_override_nulled_valid_kept",
- {
- "groups": [{"variant": "ghost"}, {"variant": "real"}],
- "multivariate": {"variants": [{"key": "real", "rollout_percentage": 100}]},
- },
- {
- "groups": [{"variant": None}, {"variant": "real"}],
- "multivariate": {"variants": [{"key": "real", "rollout_percentage": 100}]},
- },
- {"dangling_variant_override"},
- True,
- ),
- (
- "numeric_value_stringified_bool_left",
- {
- "groups": [
- {
- "properties": [
- {"key": "v", "type": "person", "operator": "gt", "value": 5},
- {"key": "b", "type": "person", "operator": "gt", "value": True},
- ]
- }
- ]
- },
- {
- "groups": [
- {
- "properties": [
- {"key": "v", "type": "person", "operator": "gt", "value": "5"},
- {"key": "b", "type": "person", "operator": "gt", "value": True},
- ]
- }
- ]
- },
- {"non_string_value"},
- False,
- ),
- (
- "empty_multivariate_nulled_with_override_and_payload_keys",
- {
- "groups": [{"variant": "control"}],
- "multivariate": {"variants": []},
- "payloads": {"true": "1", "control": "2"},
- },
- {"groups": [{"variant": None}], "multivariate": None, "payloads": {"true": "1"}},
- {"multivariate_empty", "dangling_variant_override"},
- True,
- ),
- (
- "typo_remap_chains_into_stringification",
- {"groups": [{"properties": [{"key": "n", "type": "person", "operator": "contains", "value": 7}]}]},
- {"groups": [{"properties": [{"key": "n", "type": "person", "operator": "icontains", "value": "7"}]}]},
- {"operator_typo", "non_string_value"},
- True,
- ),
- (
- "fully_valid_flag_untouched",
- {
- "groups": [
- {
- "properties": [{"key": "email", "type": "person", "operator": "icontains", "value": "@x.com"}],
- "rollout_percentage": 50,
- "variant": "a",
- }
- ],
- "multivariate": {"variants": [{"key": "a", "rollout_percentage": 100.0}]},
- "payloads": {"a": '"payload"'},
- "aggregation_group_type_index": None,
- },
- None,
- set(),
- True,
- ),
-]
-
-
-class TestCleanFiltersTransform(SimpleTestCase):
- @parameterized.expand([(name, dirty, expected, rules) for name, dirty, expected, rules, _ in CASES])
- def test_transform(self, _name: str, dirty: dict, expected: dict | None, expected_rules: set[str]) -> None:
- cleaned, rules = _clean_filters(dirty)
- assert rules == expected_rules
- assert cleaned == (dirty if expected is None else expected)
-
- @parameterized.expand([(name, dirty) for name, dirty, *_ in CASES])
- def test_transform_is_idempotent(self, _name: str, dirty: dict) -> None:
- cleaned, _ = _clean_filters(dirty)
- second, second_rules = _clean_filters(cleaned)
- assert second == cleaned
- assert second_rules == set()
-
- @parameterized.expand([(name, dirty) for name, dirty, _, _, audit_clean in CASES if audit_clean])
- def test_recoverable_output_passes_the_audit_rule_set(self, _name: str, dirty: dict) -> None:
- cleaned, _ = _clean_filters(dirty)
- assert collect_filters_violations(cleaned) == []
diff --git a/products/legal_documents/backend/tests/test_reconcile_tasks.py b/products/legal_documents/backend/tests/test_reconcile_tasks.py
index 007ee25eb342..5d2df5b9e11d 100644
--- a/products/legal_documents/backend/tests/test_reconcile_tasks.py
+++ b/products/legal_documents/backend/tests/test_reconcile_tasks.py
@@ -1,7 +1,3 @@
-from typing import Any
-
-from posthog.test.base import NonAtomicTestMigrations
-
from django.test import SimpleTestCase
from posthog.celery import app
@@ -26,49 +22,3 @@ class TestArchiveSignedLegalDocumentPdfRetryConfig(SimpleTestCase):
assert archive_signed_legal_document_pdf.retry_backoff == 30
assert archive_signed_legal_document_pdf.retry_backoff_max == 600
assert archive_signed_legal_document_pdf.retry_jitter is True
-
-
-class BackfillSignedPdfStoredMigrationTest(NonAtomicTestMigrations):
- """0006 marks pre-existing signed rows as archived. The old flow only flipped
- status to `signed` after the PDF was already written to object storage, so every
- row signed before this migration has its PDF sitting in storage already. The
- reconciliation sweep only looks at signed_pdf_stored=False rows, so an unmarked
- signed row would get silently re-swept and would hide its download link.
- """
-
- migrate_from = "0005_legaldocument_signed_pdf_stored"
- migrate_to = "0006_backfill_signed_pdf_stored"
-
- CLASS_DATA_LEVEL_SETUP = False
-
- @property
- def app(self) -> str:
- return "legal_documents"
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- Organization = apps.get_model("posthog", "Organization")
- LegalDocument = apps.get_model("legal_documents", "LegalDocument")
-
- org = Organization.objects.create(name="Acme, Inc.")
- self.signed_id = LegalDocument.objects.create(
- organization=org,
- document_type="BAA",
- company_name="Acme, Inc.",
- company_address="1 Analytics Way",
- representative_email="[email protected]",
- status="signed",
- ).id
- self.pending_id = LegalDocument.objects.create(
- organization=org,
- document_type="DPA",
- company_name="Acme, Inc.",
- company_address="1 Analytics Way",
- representative_email="[email protected]",
- status="submitted_for_signature",
- ).id
-
- def test_backfills_signed_rows_only(self) -> None:
- LegalDocument = self.apps.get_model("legal_documents", "LegalDocument") # type: ignore[union-attr]
-
- assert LegalDocument.objects.get(id=self.signed_id).signed_pdf_stored is True
- assert LegalDocument.objects.get(id=self.pending_id).signed_pdf_stored is False
diff --git a/products/replay_vision/backend/tests/test_migration_backfill.py b/products/replay_vision/backend/tests/test_migration_backfill.py
deleted file mode 100644
index 80ee900c1309..000000000000
--- a/products/replay_vision/backend/tests/test_migration_backfill.py
+++ /dev/null
@@ -1,153 +0,0 @@
-import uuid
-import importlib
-
-from posthog.test.base import APIBaseTest
-
-from django.apps import apps
-from django.test import override_settings
-from django.utils import timezone
-
-from parameterized import parameterized
-
-from posthog.models import Team
-
-from products.replay_vision.backend.models.replay_observation import (
- ObservationStatus,
- ObservationTrigger,
- ReplayObservation,
-)
-from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-
-m33 = importlib.import_module("products.replay_vision.backend.migrations.0033_backfill_replayobservationusage_team_id")
-m37 = importlib.import_module("products.replay_vision.backend.migrations.0037_backfill_replayobservationusage_credits")
-m56 = importlib.import_module("products.replay_vision.backend.migrations.0057_closed_beta_launch_reset")
-
-
-class TestReceiptBackfillMigrations(APIBaseTest):
- def test_backfills_team_model_and_credits_and_survives_orphans(self) -> None:
- # A retired beta model (KeyTextTransform must extract it unquoted so it matches the credit map),
- # plus an orphaned receipt whose observation was deleted (subquery -> NULL): the keyset loop must
- # not spin on it, and it must land on the baseline credits.
- scanner = ReplayScanner.objects.create(
- team=self.team,
- name="s",
- scanner_type=ScannerType.MONITOR,
- scanner_config={"prompt": "p"},
- model=ScannerModel.GEMINI_3_7_FLASH,
- )
- obs = ReplayObservation.objects.create(
- scanner=scanner,
- team=self.team,
- session_id="s1",
- status=ObservationStatus.SUCCEEDED,
- scanner_snapshot={
- "model": "gemini-3.1-flash-lite-preview",
- "name": "s",
- "scanner_type": "monitor",
- "scanner_version": 1,
- "provider": "google",
- "emits_signals": False,
- "scanner_config": {},
- },
- triggered_by=ObservationTrigger.ON_DEMAND,
- completed_at=timezone.now(),
- )
- live = ReplayObservationUsage.objects.create(
- observation_id=obs.id,
- organization_id=self.organization.id,
- observation_created_at=timezone.now(),
- )
- orphan = ReplayObservationUsage.objects.create(
- observation_id=uuid.uuid4(),
- organization_id=self.organization.id,
- observation_created_at=timezone.now(),
- )
-
- m33.backfill_team_id(apps, None)
- m37.backfill_model_and_credits(apps, None)
-
- live.refresh_from_db()
- orphan.refresh_from_db()
- assert (live.team_id, live.model, live.credits) == (self.team.id, "gemini-3.1-flash-lite-preview", 2)
- assert (orphan.team_id, orphan.model, orphan.credits) == (None, None, 5)
-
-
-class TestClosedBetaLaunchReset(APIBaseTest):
- @override_settings(CLOUD_DEPLOYMENT="US")
- def test_us_disables_scanners_except_internal_and_zeroes_receipts(self) -> None:
- internal_team = (
- self.team
- if self.team.id == m56.INTERNAL_TEAM_ID
- else Team.objects.create(id=m56.INTERNAL_TEAM_ID, organization=self.organization, name="internal")
- )
- beta_team = Team.objects.create(organization=self.organization, name="beta")
- internal_scanner = ReplayScanner.objects.create(
- team=internal_team,
- name="internal",
- scanner_type=ScannerType.MONITOR,
- scanner_config={"prompt": "p"},
- model=ScannerModel.GEMINI_3_7_FLASH,
- )
- beta_scanner = ReplayScanner.objects.create(
- team=beta_team,
- name="beta",
- scanner_type=ScannerType.MONITOR,
- scanner_config={"prompt": "p"},
- model=ScannerModel.GEMINI_3_7_FLASH,
- )
- receipt = ReplayObservationUsage.objects.create(
- observation_id=uuid.uuid4(),
- organization_id=self.organization.id,
- team_id=beta_team.id,
- observation_created_at=timezone.now(),
- model=ScannerModel.GEMINI_3_7_FLASH,
- credits=15,
- )
-
- m56.reset_closed_beta_state(apps, None)
-
- internal_scanner.refresh_from_db()
- beta_scanner.refresh_from_db()
- receipt.refresh_from_db()
- assert internal_scanner.enabled
- assert not beta_scanner.enabled
- assert receipt.credits == 0
-
- @parameterized.expand(
- [
- ("eu_team_2_not_exempt", "EU", False, 0),
- ("self_hosted_untouched", None, True, 15),
- ]
- )
- def test_reset_outside_us(
- self, _name: str, deployment: str | None, expect_enabled: bool, expect_credits: int
- ) -> None:
- team_2 = (
- self.team
- if self.team.id == m56.INTERNAL_TEAM_ID
- else Team.objects.create(id=m56.INTERNAL_TEAM_ID, organization=self.organization, name="two")
- )
- scanner = ReplayScanner.objects.create(
- team=team_2,
- name="s",
- scanner_type=ScannerType.MONITOR,
- scanner_config={"prompt": "p"},
- model=ScannerModel.GEMINI_3_7_FLASH,
- )
- receipt = ReplayObservationUsage.objects.create(
- observation_id=uuid.uuid4(),
- organization_id=self.organization.id,
- team_id=team_2.id,
- observation_created_at=timezone.now(),
- model=ScannerModel.GEMINI_3_7_FLASH,
- credits=15,
- )
-
- with override_settings(CLOUD_DEPLOYMENT=deployment):
- m56.reset_closed_beta_state(apps, None)
-
- scanner.refresh_from_db()
- receipt.refresh_from_db()
- assert scanner.enabled is expect_enabled
- assert receipt.credits == expect_credits
diff --git a/products/replay_vision/backend/tests/test_migration_revert_preview.py b/products/replay_vision/backend/tests/test_migration_revert_preview.py
deleted file mode 100644
index ba37ec71f4f5..000000000000
--- a/products/replay_vision/backend/tests/test_migration_revert_preview.py
+++ /dev/null
@@ -1,88 +0,0 @@
-import datetime as dt
-import importlib
-
-from posthog.test.base import APIBaseTest
-
-from django.apps import apps
-from django.utils import timezone
-
-from products.replay_vision.backend.models.replay_observation import (
- ObservationStatus,
- ObservationTrigger,
- ReplayObservation,
-)
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-
-m54 = importlib.import_module("products.replay_vision.backend.migrations.0054_revert_remapped_preview_scanners")
-
-PREVIEW = "gemini-3-flash-preview"
-FLASH = "gemini-3.6-flash"
-LEGACY_FLASH = "gemini-3.5-flash"
-
-REMAP_AT = dt.datetime(2026, 7, 21, 22, 15, tzinfo=dt.UTC)
-BEFORE = REMAP_AT - dt.timedelta(days=2)
-AFTER = REMAP_AT + dt.timedelta(days=1)
-
-
-class TestRevertRemappedPreviewScanners(APIBaseTest):
- def _scanner(self, name: str, model: str, created_at: dt.datetime, version: int = 1) -> ReplayScanner:
- scanner = ReplayScanner.objects.create(
- team=self.team,
- name=name,
- scanner_type=ScannerType.MONITOR,
- scanner_config={"prompt": "p"},
- model=model,
- scanner_version=version,
- )
- # created_at is auto_now_add, so override it with a raw UPDATE.
- ReplayScanner.objects.filter(pk=scanner.pk).update(created_at=created_at)
- scanner.refresh_from_db()
- return scanner
-
- def _observation(self, scanner: ReplayScanner, session_id: str, snap_model: str, snap_version: int) -> None:
- ReplayObservation.objects.create(
- scanner=scanner,
- team=self.team,
- session_id=session_id,
- status=ObservationStatus.SUCCEEDED,
- completed_at=timezone.now(),
- triggered_by=ObservationTrigger.SCHEDULE,
- scanner_snapshot={
- "name": scanner.name,
- "scanner_type": "monitor",
- "scanner_version": snap_version,
- "model": snap_model,
- "provider": "google",
- "emits_signals": False,
- "scanner_config": {"prompt": "p"},
- },
- )
-
- def test_reverts_pre_remap_36_scanners_except_positively_legacy_flash(self) -> None:
- # Pre-remap, snapshot at current version proves preview: a clear remap victim.
- confident = self._scanner("confident", FLASH, BEFORE, version=2)
- self._observation(confident, "a1", PREVIEW, 2)
-
- # Pre-remap, no snapshot evidence at current version: uncertain, swept back to preview.
- uncertain = self._scanner("uncertain", FLASH, BEFORE)
-
- # Pre-remap, snapshot at current version recorded the 15-credit 3.5-flash tier: keep 3.6.
- legacy_flash = self._scanner("legacy_flash", FLASH, BEFORE, version=1)
- self._observation(legacy_flash, "c1", LEGACY_FLASH, 1)
-
- # Created after the remap, so 0052 never touched it: keep 3.6.
- post_remap = self._scanner("post_remap", FLASH, AFTER)
-
- # A different model is out of scope entirely.
- untouched = self._scanner("lite", ScannerModel.GEMINI_3_5_FLASH_LITE, BEFORE)
-
- m54._do_revert(apps, REMAP_AT)
-
- for scanner in (confident, uncertain, legacy_flash, post_remap, untouched):
- scanner.refresh_from_db()
-
- assert confident.model == ScannerModel.GEMINI_3_FLASH_PREVIEW
- assert uncertain.model == ScannerModel.GEMINI_3_FLASH_PREVIEW
- assert legacy_flash.model == FLASH
- assert post_remap.model == FLASH
- assert untouched.model == ScannerModel.GEMINI_3_5_FLASH_LITE
diff --git a/products/warehouse_sources/backend/migrations/test/test_migration_0075.py b/products/warehouse_sources/backend/migrations/test/test_migration_0075.py
deleted file mode 100644
index dacfa9cdad8e..000000000000
--- a/products/warehouse_sources/backend/migrations/test/test_migration_0075.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import uuid
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.warehouse_sources.backend.migrations.0075_backfill_externaldatasource_api_version"
-)
-backfill_api_version = migration_module.backfill_api_version
-
-
-def source_factory(team):
- def _create(source_type, api_version=None):
- return ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type=source_type,
- api_version=api_version,
- job_inputs={},
- )
-
- return _create
-
-
-class TestBackfillApiVersion:
- @pytest.mark.parametrize(
- "source_type, existing_pin, expected_pin",
- [
- ("Stripe", None, "2024-09-30.acacia"), # snapshot mapping applies
- ("Postgres", None, "v1"), # unversioned type falls back to the default label
- ("Stripe", "2026-02-25.clover", "2026-02-25.clover"), # existing pins are never overwritten
- ],
- )
- def test_backfill(self, source_factory, source_type, existing_pin, expected_pin):
- source = source_factory(source_type, api_version=existing_pin)
-
- backfill_api_version(apps, None)
- backfill_api_version(apps, None) # idempotent
-
- source.refresh_from_db()
- assert source.api_version == expected_pin
diff --git a/products/warehouse_sources/backend/migrations/test/test_migration_0120.py b/products/warehouse_sources/backend/migrations/test/test_migration_0120.py
deleted file mode 100644
index b6c56aeb7b67..000000000000
--- a/products/warehouse_sources/backend/migrations/test/test_migration_0120.py
+++ /dev/null
@@ -1,51 +0,0 @@
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.warehouse_sources.backend.migrations.0120_fix_sentry_events_incremental_field"
-)
-forwards = migration_module.forwards
-
-
-def schema_factory(team):
- def _create(source_type, schema_name, incremental_field):
- source = ExternalDataSource.objects.create(
- source_id="src", connection_id="conn", team=team, source_type=source_type
- )
- return ExternalDataSchema.objects.create(
- name=schema_name,
- team=team,
- source=source,
- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
- sync_type_config={"incremental_field": incremental_field},
- )
-
- return _create
-
-
-class TestFixSentryEventsIncrementalField:
- @pytest.mark.parametrize(
- "source_type, schema_name, incremental_field, expected",
- [
- ("Sentry", "issue_events", "dateCreated", "dateReceived"), # broken value gets fixed
- ("Sentry", "project_events", "dateCreated", "dateReceived"), # both affected schemas fixed
- ("Sentry", "issue_events", "dateReceived", "dateReceived"), # already-correct value untouched
- ("Sentry", "issues", "lastSeen", "lastSeen"), # unrelated schema name untouched
- ("Stripe", "issue_events", "dateCreated", "dateCreated"), # unrelated source type untouched
- ],
- )
- def test_forwards(self, schema_factory, source_type, schema_name, incremental_field, expected):
- schema = schema_factory(source_type, schema_name, incremental_field)
-
- forwards(apps, None)
- forwards(apps, None) # idempotent
-
- schema.refresh_from_db()
- assert schema.sync_type_config["incremental_field"] == expected
diff --git a/products/warehouse_sources/backend/migrations/test/test_migration_0124.py b/products/warehouse_sources/backend/migrations/test/test_migration_0124.py
deleted file mode 100644
index 686ff49675aa..000000000000
--- a/products/warehouse_sources/backend/migrations/test/test_migration_0124.py
+++ /dev/null
@@ -1,73 +0,0 @@
-import importlib
-
-import pytest
-
-from django.apps import apps
-from django.db import connection
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource, PendingSourceCredential
-
-migration_module = importlib.import_module(
- "products.warehouse_sources.backend.migrations.0124_rename_planetscale_source_type_to_mysql"
-)
-forwards = migration_module.rename_planetscale_to_planetscale_mysql
-backwards = migration_module.rename_planetscale_mysql_to_planetscale
-
-
-class _SchemaEditor:
- """The migration writes raw SQL, so it needs something that can execute it."""
-
- def execute(self, sql, params=None):
- with connection.cursor() as cursor:
- cursor.execute(sql, params)
-
-
-def _source(team, source_type):
- return ExternalDataSource.objects.create(source_id="src", connection_id="conn", team=team, source_type=source_type)
-
-
-def _credential(team, source_type):
- # `PendingSourceCredential` is fail-closed team-scoped: its default manager raises
- # `TeamScopeError` outside a request that set an ambient team scope. The migration this covers
- # updates every team's rows anyway, so the fixture writes through `unscoped()`.
- return PendingSourceCredential.objects.unscoped().create(team=team, source_type=source_type, payload={})
-
-
-class TestRenamePlanetScaleSourceType:
- def test_forwards_renames_only_planetscale_rows(self, team):
- planetscale = _source(team, "PlanetScale")
- mysql = _source(team, "MySQL")
- credential = _credential(team, "PlanetScale")
-
- forwards(apps, _SchemaEditor())
-
- planetscale.refresh_from_db()
- mysql.refresh_from_db()
- credential.refresh_from_db()
- assert planetscale.source_type == "PlanetScaleMySQL"
- assert credential.source_type == "PlanetScaleMySQL"
- # A plain MySQL source shares neither product nor value, so it must be left alone.
- assert mysql.source_type == "MySQL"
-
- def test_backwards_restores_the_old_value(self, team):
- source = _source(team, "PlanetScale")
- credential = _credential(team, "PlanetScale")
-
- forwards(apps, _SchemaEditor())
- backwards(apps, _SchemaEditor())
-
- source.refresh_from_db()
- credential.refresh_from_db()
- assert source.source_type == "PlanetScale"
- assert credential.source_type == "PlanetScale"
-
- def test_backwards_leaves_the_postgres_source_type_alone(self, team):
- # The Postgres source is new in this change, so rolling the rename back must not fold it
- # into a value that only ever meant the MySQL product.
- postgres = _source(team, "PlanetScalePostgres")
-
- backwards(apps, _SchemaEditor())
-
- postgres.refresh_from_db()
- assert postgres.source_type == "PlanetScalePostgres"
diff --git a/products/warehouse_sources/backend/migrations/test/test_migration_0131.py b/products/warehouse_sources/backend/migrations/test/test_migration_0131.py
deleted file mode 100644
index c5b44b1a4fcc..000000000000
--- a/products/warehouse_sources/backend/migrations/test/test_migration_0131.py
+++ /dev/null
@@ -1,59 +0,0 @@
-import uuid
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.warehouse_sources.backend.migrations.0131_pin_leadfeeder_null_api_version_to_v1"
-)
-pin_null_leadfeeder_rows_to_v1 = migration_module.pin_null_leadfeeder_rows_to_v1
-
-
-def source_factory(team):
- def _create(source_type, api_version=None):
- return ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type=source_type,
- api_version=api_version,
- job_inputs={},
- )
-
- return _create
-
-
-class TestPinLeadfeederNullApiVersion:
- def test_pins_only_null_leadfeeder_rows(self, source_factory):
- unpinned = source_factory("Leadfeeder", api_version=None)
- pinned_unified = source_factory("Leadfeeder", api_version="2026-08-07")
- other_source = source_factory("Stripe", api_version=None)
-
- pin_null_leadfeeder_rows_to_v1(apps, None)
-
- unpinned.refresh_from_db()
- pinned_unified.refresh_from_db()
- other_source.refresh_from_db()
- assert unpinned.api_version == "v1"
- # An existing concrete pin (e.g. a source already moved to the unified API) must never be
- # overwritten.
- assert pinned_unified.api_version == "2026-08-07"
- # Non-Leadfeeder sources are untouched.
- assert other_source.api_version is None
-
- def test_is_idempotent(self, source_factory):
- source = source_factory("Leadfeeder", api_version=None)
-
- pin_null_leadfeeder_rows_to_v1(apps, None)
- pin_null_leadfeeder_rows_to_v1(apps, None)
-
- source.refresh_from_db()
- assert source.api_version == "v1"
diff --git a/products/warehouse_sources/backend/migrations/test/test_migration_0139.py b/products/warehouse_sources/backend/migrations/test/test_migration_0139.py
deleted file mode 100644
index ac5e8bae9017..000000000000
--- a/products/warehouse_sources/backend/migrations/test/test_migration_0139.py
+++ /dev/null
@@ -1,63 +0,0 @@
-import uuid
-import importlib
-
-import pytest
-
-from django.apps import apps
-
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
-
-migration_module = importlib.import_module(
- "products.warehouse_sources.backend.migrations.0139_repin_linkedin_ads_api_version"
-)
-repin_linkedin_ads_v1_to_202607 = migration_module.repin_linkedin_ads_v1_to_202607
-
-
-def source_factory(team):
- def _create(source_type, api_version=None):
- return ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type=source_type,
- api_version=api_version,
- job_inputs={},
- )
-
- return _create
-
-
-class TestRepinLinkedinAdsApiVersion:
- def test_repins_only_v1_pinned_linkedin_ads_rows(self, source_factory):
- legacy_pinned = source_factory("LinkedinAds", api_version="v1")
- already_current = source_factory("LinkedinAds", api_version="202607")
- unpinned = source_factory("LinkedinAds", api_version=None)
- other_source = source_factory("Stripe", api_version="v1")
-
- repin_linkedin_ads_v1_to_202607(apps, None)
-
- legacy_pinned.refresh_from_db()
- already_current.refresh_from_db()
- unpinned.refresh_from_db()
- other_source.refresh_from_db()
- assert legacy_pinned.api_version == "202607"
- # A pin already on the current default is untouched.
- assert already_current.api_version == "202607"
- # NULL already resolves to the (now "202607") default, so it's left alone rather than
- # stamped with a concrete value.
- assert unpinned.api_version is None
- # Non-LinkedinAds sources on the same legacy label are untouched.
- assert other_source.api_version == "v1"
-
- def test_is_idempotent(self, source_factory):
- source = source_factory("LinkedinAds", api_version="v1")
-
- repin_linkedin_ads_v1_to_202607(apps, None)
- repin_linkedin_ads_v1_to_202607(apps, None)
-
- source.refresh_from_db()
- assert source.api_version == "202607"