:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(surveys): validate linked insight on survey save (#57564)
Tom Piccirellof0f7561e7604
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex fe4fbdc4ae91..7e97e82cfb04 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -63,7 +63,7 @@ from posthog.helpers.trigram_search import (MIN_NAME_TRIGRAM_SIMILARITY,normalize_search_term,)-from posthog.models import Action+from posthog.models import Action, Insightfrom posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.feature_flag import FeatureFlag@@ -1059,6 +1059,13 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):except FeatureFlag.DoesNotExist:raise serializers.ValidationError("Targeting Feature Flag with this ID does not exist")+ linked_insight_id = data.get("linked_insight_id")+ if linked_insight_id:+ try:+ Insight.objects.get(pk=linked_insight_id, team_id=self.context["team_id"])+ except Insight.DoesNotExist:+ raise serializers.ValidationError("Insight with this ID does not exist")+# Validate linkedFlagVariant if providedconditions = data.get("conditions") or {}linked_flag_variant = conditions.get("linkedFlagVariant")diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex ba80aeae225a..205e889caceb 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -24,7 +24,7 @@ from rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeature-from posthog.models import Action, FeatureFlag, Person, Team+from posthog.models import Action, FeatureFlag, Insight, Person, Teamfrom posthog.models.cohort.cohort import Cohortfrom posthog.models.organization import Organization, OrganizationMembership@@ -1602,6 +1602,83 @@ class TestSurvey(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "Feature Flag with this ID does not exist" in str(response.json())+ def test_creating_survey_with_linked_insight_from_different_team_returns_400(self):+ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ other_insight = Insight.objects.create(team=other_team, name="other-team-insight", created_by=self.user)++ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Test Survey",+ "type": "popover",+ "questions": [{"type": "open", "question": "Test?"}],+ "linked_insight_id": other_insight.id,+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Insight with this ID does not exist" in str(response.json())+ assert not Survey.objects.filter(linked_insight_id=other_insight.id).exists()++ def test_updating_survey_with_linked_insight_from_different_team_returns_400(self):+ own_insight = Insight.objects.create(team=self.team, name="own-insight", created_by=self.user)+ survey = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Test Survey",+ "type": "popover",+ "questions": [{"type": "open", "question": "Test?"}],+ "linked_insight_id": own_insight.id,+ },+ format="json",+ ).json()++ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ other_insight = Insight.objects.create(team=other_team, name="other-team-insight", created_by=self.user)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/surveys/{survey['id']}/",+ data={"linked_insight_id": other_insight.id},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Insight with this ID does not exist" in str(response.json())+ assert Survey.objects.get(id=survey["id"]).linked_insight_id == own_insight.id++ def test_creating_survey_with_nonexistent_linked_insight_returns_400(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Test Survey",+ "type": "popover",+ "questions": [{"type": "open", "question": "Test?"}],+ "linked_insight_id": 999999,+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Insight with this ID does not exist" in str(response.json())++ def test_can_create_survey_with_linked_insight_in_same_team(self):+ own_insight = Insight.objects.create(team=self.team, name="own-insight", created_by=self.user)++ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Test Survey",+ "type": "popover",+ "questions": [{"type": "open", "question": "Test?"}],+ "linked_insight_id": own_insight.id,+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert Survey.objects.get(id=response.json()["id"]).linked_insight_id == own_insight.id+def test_deleting_survey_deletes_targeting_flag(self):response = self.client.post(f"/api/projects/{self.team.id}/surveys/",