: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
chore(django): rm dead cohort code after flags removal (#64107)
Nick Best7ebc30581ac1
diff --git a/ee/clickhouse/models/test/test_filters.py b/ee/clickhouse/models/test/test_filters.pyindex 23f6e406da17..8069b63dfc39 100644--- a/ee/clickhouse/models/test/test_filters.py+++ b/ee/clickhouse/models/test/test_filters.py@@ -1,7 +1,7 @@import jsonfrom typing import Optional-from posthog.test.base import ClickhouseTestMixin, _create_event, _create_person+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_personfrom posthog.clickhouse.client import query_with_columns, sync_executefrom posthog.constants import FILTER_TEST_ACCOUNTS@@ -10,10 +10,7 @@ from posthog.models.event.sql import GET_EVENTS_WITH_PROPERTIESfrom posthog.models.event.util import ClickhouseEventSerializerfrom posthog.models.filters import Filterfrom posthog.models.filters.retention_filter import RetentionFilter-from posthog.models.filters.test.test_filter import (- TestFilter as PGTestFilters,- property_to_Q_test_factory,-)+from posthog.models.filters.test.test_filter import TestFilter as PGTestFiltersfrom posthog.models.property.util import parse_prop_grouped_clausesfrom posthog.queries.util import PersonPropertiesModefrom posthog.test.test_journeys import journeys_for@@ -540,7 +537,7 @@ class TestFilters(PGTestFilters):)-class TestFiltering(ClickhouseTestMixin, property_to_Q_test_factory(_filter_persons, _create_person)): # type: ignore+class TestFiltering(ClickhouseTestMixin, BaseTest):def test_simple(self):_create_event(team=self.team, distinct_id="test", event="$pageview")_create_event(diff --git a/posthog/models/filters/test/test_filter.py b/posthog/models/filters/test/test_filter.pyindex 3ba4e66b6042..674ada9e03de 100644--- a/posthog/models/filters/test/test_filter.py+++ b/posthog/models/filters/test/test_filter.py@@ -1,26 +1,10 @@-import json-import datetime-from collections.abc import Callable-from typing import Any, Optional, cast+from typing import cast-from freezegun import freeze_time-from posthog.test.base import (- BaseTest,- QueryMatchingTest,- _create_person,- flush_persons_and_events,- snapshot_postgres_queries,- snapshot_postgres_queries_context,-)--from django.db.models import CharField, F, Func, Q+from posthog.test.base import BaseTestfrom posthog.constants import FILTER_TEST_ACCOUNTS-from posthog.models import Filter, Person, Team+from posthog.models import Filterfrom posthog.models.property import Property-from posthog.queries.base import properties_to_Q, property_group_to_Q--from products.cohorts.backend.models.cohort import Cohortclass TestFilter(BaseTest):@@ -144,1523 +128,3 @@ class TestFilter(BaseTest):}},)---def property_to_Q_test_factory(filter_persons: Callable, person_factory):- class TestPropertiesToQ(BaseTest):- def test_simple_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com"},- )- person_factory(team_id=self.team.pk, distinct_ids=["person2"], properties={"url": 1})- person_factory(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}},- )- person_factory(team_id=self.team.pk, distinct_ids=["person4"])-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- }- ]- }- )-- results = filter_persons(filter, self.team)- self.assertEqual(len(results), 1)-- def test_multiple_equality_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com"},- )- person_factory(team_id=self.team.pk, distinct_ids=["person2"], properties={"url": 1})- person_factory(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}},- )- person_factory(team_id=self.team.pk, distinct_ids=["person4"])- person_factory(- team_id=self.team.pk,- distinct_ids=["person5"],- properties={"url": "https://example.com"},- )-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": ["https://whatever.com", "https://example.com"],- }- ]- }- )-- results = filter_persons(filter, self.team)- self.assertEqual(len(results), 2)-- def test_incomplete_data(self):- filter = Filter(- data={- "properties": [- {- "key": "$current_url",- "operator": "not_icontains",- "type": "event",- }- ]- }- )- self.assertListEqual(filter.property_groups.values, [])-- def test_contains_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"url": "https://whatever.com"},- )- person_factory(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"url": "https://example.com"},- )-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": "whatever",- "operator": "icontains",- }- ]- }- )-- results = filter_persons(filter, self.team)- self.assertEqual(len(results), 1)-- def test_regex_persons(self):- p1_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"url": "https://whatever.com"},- ).uuid- )- p2_uuid = str(person_factory(team_id=self.team.pk, distinct_ids=["p2"]).uuid)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": r"\.com$",- "operator": "regex",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertCountEqual(results, [p1_uuid])-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": r"\.eee$",- "operator": "not_regex",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertCountEqual(results, [p1_uuid, p2_uuid])-- def test_invalid_regex_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"url": "https://whatever.com"},- )- person_factory(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"url": "https://example.com"},- )-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": r"?*",- "operator": "regex",- }- ]- }- )- self.assertEqual(len(filter_persons(filter, self.team)), 0)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": r"?*",- "operator": "not_regex",- }- ]- }- )- self.assertEqual(len(filter_persons(filter, self.team)), 0)-- def test_is_not_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"url": "https://whatever.com"},- )- p2_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"url": "https://example.com"},- ).uuid- )-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- "operator": "is_not",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertCountEqual(results, [p2_uuid])-- def test_does_not_contain_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"url": "https://whatever.com"},- )- p2_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"url": "https://example.com"},- ).uuid- )- p3_uuid = str(person_factory(team_id=self.team.pk, distinct_ids=["p3"]).uuid)- p4_uuid = str(person_factory(team_id=self.team.pk, distinct_ids=["p4"], properties={"url": None}).uuid)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": "whatever.com",- "operator": "not_icontains",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertCountEqual(results, [p2_uuid, p3_uuid, p4_uuid])-- def test_multiple_persons(self):- p1_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"url": "https://whatever.com", "another_key": "value"},- ).uuid- )- person_factory(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"url": "https://whatever.com"},- )-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "url",- "value": "whatever.com",- "operator": "icontains",- },- {"type": "person", "key": "another_key", "value": "value"},- ]- }- )- results = filter_persons(filter, self.team)- self.assertCountEqual(results, [p1_uuid])-- def test_boolean_filters_persons(self):- p1_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"is_first_user": True},- ).uuid- )- person_factory(team_id=self.team.pk, distinct_ids=["p2"])-- filter = Filter(data={"properties": [{"type": "person", "key": "is_first_user", "value": ["true"]}]})- results = filter_persons(filter, self.team)- self.assertEqual(results, [p1_uuid])-- def test_is_not_set_and_is_set_persons(self):- p1_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"is_first_user": True},- ).uuid- )- p2_uuid = str(person_factory(team_id=self.team.pk, distinct_ids=["p2"]).uuid)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "is_first_user",- "value": "",- "operator": "is_set",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertEqual(results, [p1_uuid])-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "is_first_user",- "value": "",- "operator": "is_not_set",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertEqual(results, [p2_uuid])-- def test_is_not_true_false_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"is_first_user": True},- )- p2_uuid = str(person_factory(team_id=self.team.pk, distinct_ids=["p2"]).uuid)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "is_first_user",- "value": ["true"],- "operator": "is_not",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertEqual(results, [p2_uuid])-- def test_is_date_before_persons(self):- p1_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["p1"],- properties={"some-timestamp": "2022-03-01"},- ).uuid- )- person_factory(- team_id=self.team.pk,- distinct_ids=["p2"],- properties={"some-timestamp": "2022-05-01"},- )-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "some-timestamp",- "value": "2022-04-01",- "operator": "is_date_before",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertEqual(results, [p1_uuid])-- def test_json_object(self):- p1_uuid = person_factory(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"name": {"first_name": "Mary", "last_name": "Smith"}},- )- filter = Filter(- data={- "properties": [- {- "key": "name",- "value": json.dumps({"first_name": "Mary", "last_name": "Smith"}),- "type": "person",- }- ]- }- )- results = filter_persons(filter, self.team)- self.assertEqual(results, [str(p1_uuid.uuid)])-- def test_filter_out_team_members_persons(self):- person_factory(- team_id=self.team.pk,- distinct_ids=["team_member"],- properties={"email": "[email protected]"},- )- p2_uuid = str(- person_factory(- team_id=self.team.pk,- distinct_ids=["random_user"],- properties={"email": "[email protected]"},- ).uuid- )- self.team.test_account_filters = [- {- "key": "email",- "value": "@posthog.com",- "operator": "not_icontains",- "type": "person",- }- ]- self.team.save()- filter = Filter(data={FILTER_TEST_ACCOUNTS: True}, team=self.team)-- results = filter_persons(filter, self.team)- self.assertEqual(results, [p2_uuid])-- return TestPropertiesToQ---def _filter_persons(filter: Filter, team: Team):- flush_persons_and_events()- persons = Person.objects.filter(properties_to_Q(team.pk, filter.property_groups.flat))- persons = persons.filter(team_id=team.pk)- return [str(uuid) for uuid in persons.values_list("uuid", flat=True)]---class TestDjangoPropertiesToQ(property_to_Q_test_factory(_filter_persons, _create_person), QueryMatchingTest): # type: ignore- @snapshot_postgres_queries- def test_array_property_as_string_on_persons(self):- Person.objects.create(- team=self.team,- distinct_ids=["person1"],- properties={"urls": ["https://whatever.com", '["abcd"]', "efg"]},- )- Person.objects.create(team=self.team, distinct_ids=["person2"], properties={"urls": ['["abcd"]']})- Person.objects.create(team=self.team, distinct_ids=["person3"], properties={"urls": '["abcd"]'})- Person.objects.create(team=self.team, distinct_ids=["person4"], properties={"urls": "['abcd']"})- Person.objects.create(team=self.team, distinct_ids=["person5"])-- # some idiosyncracies on how this works, but we shouldn't error out on this- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "urls",- "operator": "icontains",- "value": '["abcd"]',- }- ]- }- )-- persons = Person.objects.filter(property_group_to_Q(self.team.pk, filter.property_groups))- persons = persons.filter(team_id=self.team.pk)- results = sorted([person.distinct_ids[0] for person in persons])-- self.assertEqual(len(results), 1)- self.assertEqual(results[0], "person3")-- def test_person_cohort_properties(self):- person1_distinct_id = "person1"- person1 = Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"$some_prop": 1},- )- cohort1 = Cohort.objects.create(team=self.team, groups=[{"properties": {"$some_prop": 1}}], name="cohort1")- cohort1.people.add(person1)-- filter = Filter(data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]})-- with self.assertNumQueries(2):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertTrue(matched_person)-- def test_person_cohort_properties_with_zero_value(self):- person1_distinct_id = "person1"- person1 = Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"$some_prop": 0},- )- cohort1 = Cohort.objects.create(team=self.team, groups=[{"properties": {"$some_prop": 0}}], name="cohort1")- cohort1.people.add(person1)-- filter = Filter(data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]})-- with self.assertNumQueries(2):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertTrue(matched_person)-- def test_person_cohort_properties_with_negation(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=["example_id"],- properties={"$some_prop": "matches"},- )-- user_in = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "AND",- "values": [- {- "key": "$some_prop",- "value": "matches",- "type": "person",- },- ],- }- ],- }- },- name="user_in_this_cohort",- )- not_in_1_cohort = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- "values": [- {- "key": "$bad_prop",- "value": "nomatchihope",- "type": "person",- },- ],- },- ],- }- },- name="user_not_in_1",- )-- cohort1 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "AND",- "values": [- {- "key": "id",- "negation": False,- "type": "cohort",- "value": user_in.pk,- },- {- "key": "id",- "negation": True,- "type": "cohort",- "value": not_in_1_cohort.pk,- },- ],- }- },- name="overall_cohort",- )-- filter = Filter(data={"properties": [{"key": "id", "value": cohort1.pk, "type": "cohort"}]})-- with self.assertNumQueries(4):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertTrue(matched_person)-- def test_group_property_filters_direct(self):- filter = Filter(- data={- "properties": [- {- "key": "some_prop",- "value": 5,- "type": "group",- "group_type_index": 1,- }- ]- }- )- query_filter = properties_to_Q(self.team.pk, filter.property_groups.flat)- self.assertEqual(- query_filter,- Q(- Q(group_properties__some_prop=5)- & Q(group_properties__has_key="some_prop")- & ~Q(group_properties__some_prop=None)- ),- )-- def test_person_relative_date_parsing(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"created_at": "2021-04-04T12:00:00Z"},- )- filter = Filter(- data={"properties": [{"key": "created_at", "value": "2d", "type": "person", "operator": "is_date_after"}]}- )-- with self.assertNumQueries(1), freeze_time("2021-04-06T10:00:00"):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertTrue(matched_person)-- def test_person_matching_greater_than_filter(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"registration_ts": 5},- )- filter = Filter(- data={"properties": [{"key": "registration_ts", "value": "4", "type": "person", "operator": "gt"}]}- )-- with self.assertNumQueries(1):- matched_person = (- Person.objects.annotate(- **{- "properties_registrationts_68f210b8c014e1b_type": Func(- F("properties__registration_ts"),- function="JSONB_TYPEOF",- output_field=CharField(),- )- }- )- .filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertTrue(matched_person)-- def test_broken_person_filter_never_matching(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"registration_ts": 1716447600},- )- # This broken filter came from this issue: https://github.com/PostHog/posthog/issues/23213- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- # This is the valid condition- {- "key": "registration_ts",- "type": "person",- "value": "1716274800",- "negation": False,- "operator": "gte",- },- # This is the invalid condition (lte operator comparing against a list of values)- {- "key": "registration_ts",- "type": "person",- "value": ["1716447600"],- "negation": False,- "operator": "lte",- },- ],- }- ],- }- }- )-- with self.assertNumQueries(1):- matched_person = (- Person.objects.annotate(- **{- "properties_registrationts_68f210b8c014e1b_type": Func(- F("properties__registration_ts"),- function="JSONB_TYPEOF",- output_field=CharField(),- )- }- )- .filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- # This shouldn't pass because we have an AND condition with a broken lte operator- # (we should never have a lte operator comparing against a list of values)- # So this should never match- self.assertFalse(matched_person)-- def test_broken_condition_does_not_break_entire_filter(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"registration_ts": 1716447600},- )- # Create a cohort with an OR filter that has an invalid condition- # (a lte operator comparing against a list of values)- # This should still evaluate to True, though, because the other condition is valid- cohort = Cohort.objects.create(- team=self.team,- name="Test OR Cohort",- filters={- "properties": {- "type": "OR",- "values": [- {- "type": "OR",- # This is the valid condition- "values": [- {- "key": "registration_ts",- "type": "person",- "value": "1716274800",- "negation": False,- "operator": "gte",- },- # This is the invalid condition- {- "key": "registration_ts",- "type": "person",- "value": ["1716447600"],- "negation": False,- "operator": "lte",- },- ],- }- ],- }- },- )- filter = Filter(data={"properties": [{"key": "id", "value": cohort.pk, "type": "cohort"}]})- with self.assertNumQueries(2):- matched_person = (- Person.objects.annotate(- **{- "properties_registrationts_68f210b8c014e1b_type": Func(- F("properties__registration_ts"),- function="JSONB_TYPEOF",- output_field=CharField(),- )- }- )- .filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- # This should now pass because the cohort filter still has one valid condition- self.assertTrue(matched_person)-- def test_person_matching_real_filter(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"registration_ts": 1716447600},- )- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "key": "registration_ts",- "type": "person",- "value": "1716274800",- "negation": False,- "operator": "gt",- },- {- "key": "registration_ts",- "type": "person",- "value": ["1716447600"],- "negation": False,- "operator": "exact",- },- ],- }- ],- }- }- )- with self.assertNumQueries(1):- matched_person = (- Person.objects.annotate(- **{- "properties_registrationts_68f210b8c014e1b_type": Func(- F("properties__registration_ts"),- function="JSONB_TYPEOF",- output_field=CharField(),- )- }- )- .filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertTrue(matched_person)-- def test_person_relative_date_parsing_with_override_property(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"created_at": "2021-04-04T12:00:00Z"},- )- filter = Filter(- data={"properties": [{"key": "created_at", "value": "2m", "type": "person", "operator": "is_date_after"}]}- )-- with self.assertNumQueries(1):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(- properties_to_Q(- self.team.pk,- filter.property_groups.flat,- override_property_values={"created_at": "2022-10-06T10:00:00Z"},- )- )- .exists()- )- self.assertFalse(matched_person)-- @freeze_time("2021-04-06T10:00:00")- def test_person_relative_date_parsing_with_invalid_date(self):- person1_distinct_id = "example_id"- Person.objects.create(- team=self.team,- distinct_ids=[person1_distinct_id],- properties={"created_at": "2021-04-04T12:00:00Z"},- )- filter = Filter(- data={- "properties": [- {"key": "created_at", "value": ["2m", "3d"], "type": "person", "operator": "is_date_after"}- ]- }- )-- with snapshot_postgres_queries_context(self):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- # needs an exact match- self.assertFalse(matched_person)-- filter = Filter(- data={- "properties": [{"key": "created_at", "value": "bazinga", "type": "person", "operator": "is_date_after"}]- }- )-- with snapshot_postgres_queries_context(self):- matched_person = (- Person.objects.filter(- team_id=self.team.pk,- persondistinctid__distinct_id=person1_distinct_id,- )- .filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- .exists()- )- self.assertFalse(matched_person)-- def _filter_with_date_range(- self, date_from: datetime.datetime, date_to: Optional[datetime.datetime] = None- ) -> Filter:- data = {- "properties": [{"key": "some_prop", "value": 5, "type": "group", "group_type_index": 1}],- "date_from": date_from,- }- if date_to:- data["date_to"] = date_to-- return Filter(data=data)-- def test_numerical_person_properties(self):- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"$a_number": 4})- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"$a_number": 5})- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"$a_number": 6})- _create_person(team_id=self.team.pk, distinct_ids=["p4"], properties={"$a_number": 14})-- flush_persons_and_events()-- def filter_persons_with_annotation(filter: Filter, team: Team):- persons = Person.objects.annotate(- **{- "properties_anumber_27b11200b8ed4fb_type": Func(- F("properties__$a_number"), function="JSONB_TYPEOF", output_field=CharField()- )- }- ).filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- persons = persons.filter(team_id=team.pk)- return [str(uuid) for uuid in persons.values_list("uuid", flat=True)]-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "$a_number",- "value": "4",- "operator": "gt",- }- ]- }- )- self.assertEqual(len(filter_persons_with_annotation(filter, self.team)), 3)-- filter = Filter(data={"properties": [{"type": "person", "key": "$a_number", "value": 5}]})- self.assertEqual(len(filter_persons_with_annotation(filter, self.team)), 1)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "$a_number",- "value": 6,- "operator": "lt",- }- ]- }- )- self.assertEqual(len(filter_persons_with_annotation(filter, self.team)), 2)-- @snapshot_postgres_queries- def test_icontains_with_array_value(self):- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"$key": "red-123"})- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"$key": "blue-123"})- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"$key": 6})-- flush_persons_and_events()-- def filter_persons_with_annotation(filter: Filter, team: Team):- persons = Person.objects.annotate(- **{- "properties_$key_type": Func(- F("properties__$key"), function="JSONB_TYPEOF", output_field=CharField()- )- }- ).filter(properties_to_Q(self.team.pk, filter.property_groups.flat))- persons = persons.filter(team_id=team.pk)- return [str(uuid) for uuid in persons.values_list("uuid", flat=True)]-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "$key",- "value": ["red"],- "operator": "icontains",- }- ]- }- )- self.assertEqual(len(filter_persons_with_annotation(filter, self.team)), 0)-- filter = Filter(- data={- "properties": [- {- "type": "person",- "key": "$key",- "value": "red",- "operator": "icontains",- }- ]- }- )- self.assertEqual(len(filter_persons_with_annotation(filter, self.team)), 1)---def filter_persons_with_property_group(- filter: Filter, team: Team, property_overrides: Optional[dict[str, Any]] = None-) -> list[str]:- if property_overrides is None:- property_overrides = {}- flush_persons_and_events()- persons = Person.objects.filter(property_group_to_Q(team.pk, filter.property_groups, property_overrides))- persons = persons.filter(team_id=team.pk)- return sorted([person.distinct_ids[0] for person in persons])---class TestDjangoPropertyGroupToQ(BaseTest, QueryMatchingTest):- def test_simple_property_group_to_q(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com"},- )- _create_person(team_id=self.team.pk, distinct_ids=["person2"], properties={"url": 1})- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "url", "value": 1},- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team)- self.assertEqual(len(results), 2)- self.assertEqual(["person1", "person2"], results)-- def test_multiple_properties_property_group_to_q(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com", "bla": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"url": 1, "bla": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}, "bla": 3},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "bla", "value": 1},- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team)- self.assertEqual(len(results), 1)- self.assertEqual(["person1"], results)-- def test_nested_property_group_to_q(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com", "bla": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"url": 1, "bla": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}, "bla": 3},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "bla", "value": 1},- ],- },- {- "type": "AND",- "values": [{"type": "person", "key": "bla", "value": 3}],- },- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team)- self.assertEqual(len(results), 2)- self.assertEqual(["person1", "person3"], results)-- def test_property_group_to_q_with_property_overrides(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com", "bla": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"url": 1, "bla": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}, "bla": 3},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "bla", "value": 1},- ],- },- {- "type": "AND",- "values": [{"type": "person", "key": "bla", "value": 3}],- },- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team, {"bla": 2})- # all discarded because bla is neither 1 nor 3- self.assertEqual(len(results), 0)-- @snapshot_postgres_queries- def test_property_group_to_q_with_cohorts(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com", "bla": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"url": 1, "bla": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}, "bla": 3},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- cohort1 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {"type": "person", "key": "bla", "value": 1},- {"type": "person", "key": "bla", "value": 2},- ],- }- },- name="cohort1",- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "bla", "value": 1},- {"type": "cohort", "key": "id", "value": cohort1.pk},- ],- },- {- "type": "AND",- "values": [{"type": "person", "key": "bla", "value": 3}],- },- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team)- self.assertEqual(len(results), 2)- self.assertEqual(["person1", "person3"], results)-- @snapshot_postgres_queries- def test_property_group_to_q_with_negation_cohorts(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"bla": 1, "other": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"bla": 2, "other": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"bla": 3, "other": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person4"],- properties={"bla": 4, "other": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person5"],- properties={"bla": 5, "other": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person6"],- properties={"bla": 6, "other": 1},- )-- cohort1 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {"type": "person", "key": "bla", "value": 1},- {"type": "person", "key": "bla", "value": 2},- ],- }- },- name="cohort1",- )-- cohort2 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {"type": "person", "key": "bla", "value": 3},- {"type": "person", "key": "bla", "value": 4},- ],- }- },- name="cohort2",- )-- cohort3 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "OR",- "values": [- {"type": "person", "key": "other", "value": 1},- ],- }- },- name="cohort3",- )-- cohort4 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "AND",- "values": [- {- "type": "cohort",- "key": "id",- "value": cohort1.pk,- "negation": True,- },- {- "type": "cohort",- "key": "id",- "value": cohort2.pk,- "negation": True,- },- {"type": "cohort", "key": "id", "value": cohort3.pk},- ],- }- },- name="cohort2",- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {"type": "cohort", "key": "id", "value": cohort4.pk},- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team)- self.assertEqual(len(results), 2)- self.assertEqual(["person5", "person6"], results)-- @snapshot_postgres_queries- def test_property_group_to_q_with_cohorts_no_match(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com", "bla": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"url": 1, "bla": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}, "bla": 3},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- cohort1 = Cohort.objects.create(- team=self.team,- filters={- "properties": {- "type": "AND",- "values": [- {"type": "person", "key": "bla", "value": 1},- {"type": "person", "key": "bla", "value": 2},- ],- }- },- name="cohort1",- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "bla", "value": 1},- {"type": "cohort", "key": "id", "value": cohort1.pk},- ],- },- {- "type": "AND",- "values": [{"type": "person", "key": "bla", "value": 3}],- },- ],- }- }- )-- results = filter_persons_with_property_group(filter, self.team)- self.assertEqual(len(results), 1)- self.assertEqual(["person3"], results)-- def test_property_group_to_q_with_behavioural_cohort(self):- _create_person(- team_id=self.team.pk,- distinct_ids=["person1"],- properties={"url": "https://whatever.com", "bla": 1},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person2"],- properties={"url": 1, "bla": 2},- )- _create_person(- team_id=self.team.pk,- distinct_ids=["person3"],- properties={"url": {"bla": "bla"}, "bla": 3},- )- _create_person(team_id=self.team.pk, distinct_ids=["person4"])-- cohort2 = Cohort.objects.create(- team=self.team,- groups=[{"event_id": "$pageview", "days": 7}],- name="cohort2",- )-- filter = Filter(- data={- "properties": {- "type": "OR",- "values": [- {- "type": "AND",- "values": [- {- "type": "person",- "key": "url",- "value": "https://whatever.com",- },- {"type": "person", "key": "bla", "value": 1},- {"type": "cohort", "key": "id", "value": cohort2.pk},- ],- },- {- "type": "AND",- "values": [{"type": "person", "key": "bla", "value": 3}],- },- ],- }- }- )-- with self.assertRaises(ValueError):- filter_persons_with_property_group(filter, self.team)diff --git a/posthog/queries/base.py b/posthog/queries/base.pyindex 22be6b576bfb..9efdd263006e 100644--- a/posthog/queries/base.py+++ b/posthog/queries/base.py@@ -1,26 +1,19 @@import re-import hashlibimport datetimefrom collections.abc import Callable-from typing import Any, Optional, TypeVar, Union, cast+from typing import Any, Optional, TypeVarfrom zoneinfo import ZoneInfo-from django.db.models import Exists, OuterRef, Q, Value-from dateutil import parserfrom dateutil.relativedelta import relativedeltafrom rest_framework.exceptions import ValidationError-from posthog.constants import PropertyOperatorTypefrom posthog.models.filters.filter import Filterfrom posthog.models.filters.path_filter import PathFilter-from posthog.models.property import Property, PropertyGroup-from posthog.models.property.property import OperatorType, ValueT+from posthog.models.property.property import ValueTfrom posthog.models.team import Teamfrom posthog.queries.util import convert_to_datetime_aware-from posthog.utils import get_compare_period_dates, is_valid_regex--from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, CohortPeople+from posthog.utils import get_compare_period_datesFilterType = TypeVar("FilterType", Filter, PathFilter)@@ -80,116 +73,6 @@ def handle_compare(filter, func: Callable, team: Team, **kwargs) -> list:return all_entities-def match_property(property: Property, override_property_values: dict[str, Any]) -> bool:- # only looks for matches where key exists in override_property_values- # doesn't support operator is_not_set-- if property.key not in override_property_values:- raise ValidationError("can't match properties without an override value")-- key = property.key- operator = property.operator or "exact"- value = property.value- override_value = override_property_values[key]-- if operator in ("exact", "is_not"):-- def compute_exact_match(value: ValueT, override_value: Any) -> bool:- parsed_value = property._parse_value(value)- if is_truthy_or_falsy_property_value(parsed_value):- # Do boolean handling, such that passing in "true" or "True" or "false" or "False" as override value is equivalent- truthy = parsed_value in (True, [True], "true", ["true"], "True", ["True"])- return str(override_value).lower() == str(truthy).lower()-- if isinstance(value, list):- return str(override_value).lower() in [str(val).lower() for val in value]- return str(value).lower() == str(override_value).lower()-- if operator == "exact":- return compute_exact_match(value, override_value)- else:- return not compute_exact_match(value, override_value)-- if operator == "is_set":- return key in override_property_values-- if operator == "is_not_set":- if key in override_property_values:- return False- raise ValidationError("can't match properties with operator is_not_set")-- if operator == "icontains":- return str(value).lower() in str(override_value).lower()-- if operator == "not_icontains":- return str(value).lower() not in str(override_value).lower()-- if operator in ("regex", "not_regex"):- pattern = sanitize_regex_pattern(str(value))- try:- # Make the pattern more flexible by using DOTALL flag to allow . to match newlines- # Added IGNORECASE for more flexibility- compiled_pattern = re.compile(pattern, re.DOTALL | re.IGNORECASE)- match = compiled_pattern.search(str(override_value))-- if operator == "regex":- return match is not None- else:- return match is None-- except re.error:- return False-- if operator in ("gt", "gte", "lt", "lte"):- # :TRICKY: We adjust comparison based on the override value passed in,- # to make sure we handle both numeric and string comparisons appropriately.- def compare(lhs, rhs, operator):- if operator == "gt":- return lhs > rhs- elif operator == "gte":- return lhs >= rhs- elif operator == "lt":- return lhs < rhs- elif operator == "lte":- return lhs <= rhs- else:- raise ValueError(f"Invalid operator: {operator}")-- parsed_value = None- try:- parsed_value = float(value) # type: ignore- except Exception:- pass-- if parsed_value is not None and override_value is not None:- if isinstance(override_value, str):- return compare(override_value, str(value), operator)- else:- return compare(override_value, parsed_value, operator)- else:- return compare(str(override_value), str(value), operator)-- if operator in ["is_date_before", "is_date_after", "is_date_exact"]:- parsed_date = determine_parsed_date_for_property_matching(value)-- if not parsed_date:- return False-- parsed_override_date = determine_parsed_incoming_date(override_value)-- if not parsed_override_date:- return False-- if operator == "is_date_before":- return parsed_override_date < parsed_date- elif operator == "is_date_after":- return parsed_override_date > parsed_date- elif operator == "is_date_exact":- return parsed_override_date == parsed_date-- return False--def determine_parsed_incoming_date(value: ValueT | datetime.date | datetime.datetime | float,) -> datetime.datetime | None:@@ -238,282 +121,6 @@ def determine_parsed_date_for_property_matching(value: ValueT) -> datetime.datetreturn parsed_date-def empty_or_null_with_value_q(- column: str,- key: str,- operator: Optional[OperatorType],- value: ValueT,- negated: bool = False,-) -> Q:- if operator == "exact" or operator is None:- value_as_given = Property._parse_value(value)- value_as_coerced_to_number = Property._parse_value(value, convert_to_number=True)- # TRICKY: Don't differentiate between 'true' and '"true"' when database matching (one is boolean, other is string)- if is_truthy_or_falsy_property_value(value_as_given):- truthy = value_as_given in (True, [True], "true", ["true"], "True", ["True"])- target_filter = lookup_q(f"{column}__{key}", truthy) | lookup_q(f"{column}__{key}", str(truthy).lower())- elif value_as_given == value_as_coerced_to_number:- target_filter = lookup_q(f"{column}__{key}", value_as_given)- else:- target_filter = lookup_q(f"{column}__{key}", value_as_given) | lookup_q(- f"{column}__{key}", value_as_coerced_to_number- )- else:- parsed_value = None- if operator in ("gt", "gte", "lt", "lte"):- if isinstance(value, list):- # If the value is a list for these operators,- # we should not return any results, as we can't compare a list to a single value- # TODO: should we try and parse each value in the list and return results based on that?- return Q(pk__isnull=True)-- # At this point, we know that the value is not a list, so we can safely parse it- # There might still be exceptions, but we're catching them below- try:- parsed_value = float(value)- except Exception:- pass-- if parsed_value is not None:- # When we can coerce given value to a number, check whether the value in DB is a number- # and do a numeric comparison. Otherwise, do a string comparison.- sanitized_key = sanitize_property_key(key)- target_filter = Q(- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- Q(**{f"{column}__{key}__{operator}": str(value), f"{column}_{sanitized_key}_type": Value("string")})- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- | Q(**{f"{column}__{key}__{operator}": parsed_value, f"{column}_{sanitized_key}_type": Value("number")})- )- else:- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- target_filter = Q(**{f"{column}__{key}__{operator}": value})-- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- query_filter = Q(target_filter & Q(**{f"{column}__has_key": key}) & ~Q(**{f"{column}__{key}": None}))-- if negated:- return ~query_filter- return query_filter---def lookup_q(key: str, value: Any) -> Q:- # exact and is_not operators can pass lists as arguments. Handle those lookups!- if isinstance(value, list):- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- return Q(**{f"{key}__in": value})- return Q(**{key: value})---def property_to_Q(- project_id: int,- property: Property,- override_property_values: Optional[dict[str, Any]] = None,- cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,- using_database: str = "default",-) -> Q:- if override_property_values is None:- override_property_values = {}- if property.type not in ["person", "group", "cohort", "event", "flag"]:- # We need to support event type for backwards compatibility, even though it's treated as a person property type- # Note: "flag" type is not supported here as flag dependencies are handled at the API layer during validation- raise ValueError(f"property_to_Q: type is not supported: {repr(property.type)}")-- value = property._parse_value(property.value)- if property.type == "cohort":- cohort_id = int(cast(Union[str, int], value))- if cohorts_cache is not None:- if cohorts_cache.get(cohort_id) is None:- queried_cohort = (- Cohort.objects.db_manager(using_database)- .filter(pk=cohort_id, team__project_id=project_id, deleted=False)- .first()- )- cohorts_cache[cohort_id] = queried_cohort or ""-- cohort = cohorts_cache[cohort_id]- else:- cohort = (- Cohort.objects.db_manager(using_database)- .filter(pk=cohort_id, team__project_id=project_id, deleted=False)- .first()- )-- if not cohort:- # Don't match anything if cohort doesn't exist- return Q(pk__isnull=True)-- if cohort.is_static:- return Q(- Exists(- CohortPeople.objects.db_manager(using_database) # nosemgrep: no-direct-persons-db-orm- .filter(- cohort_id=cohort_id,- person_id=OuterRef("id"),- cohort__id=cohort_id,- )- .only("id")- )- )- else:- # :TRICKY: This has potential to create an infinite loop if the cohort is recursive.- # But, this shouldn't happen because we check for cyclic cohorts on creation.- return property_group_to_Q(- project_id,- cohort.properties,- override_property_values,- cohorts_cache,- using_database,- )-- # short circuit query if key exists in override_property_values- if property.key in override_property_values:- # if match found, add an explicit match-all Q object- # if not found, return falsy Q- if not match_property(property, override_property_values):- return Q(pk__isnull=True)- else:- # TRICKY: We need to return an explicit match-all Q object, instead of an empty Q object,- # because the empty Q object, when OR'ed with other Q objects, results in removing the empty Q object.- # This isn't what we want here, because this is an explicit true match, which when OR'ed with others,- # should not be removed, and return True.- # See https://code.djangoproject.com/ticket/32554 for gotcha explanation- return Q(pk__isnull=False)-- # if no override matches, return a true Q object-- column = "group_properties" if property.type == "group" else "properties"-- if property.operator == "is_set":- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- return Q(**{f"{column}__{property.key}__isnull": False})- if property.operator == "is_not_set":- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- return Q(**{f"{column}__{property.key}__isnull": True})- if property.operator in ("regex", "not_regex") and not is_valid_regex(str(value)):- # Return no data for invalid regexes- return Q(pk=-1)- if isinstance(property.operator, str) and property.operator.startswith("not_"):- return empty_or_null_with_value_q(- column,- property.key,- cast(OperatorType, property.operator[4:]),- value,- negated=True,- )-- if property.operator in ("is_date_after", "is_date_before"):- effective_operator = "gt" if property.operator == "is_date_after" else "lt"- effective_value = value-- # First try relative date parsing- relative_date = relative_date_parse_for_feature_flag_matching(str(value))- if relative_date:- effective_value = relative_date.isoformat()- else:- # Parse the date string and convert to ISO format for consistent comparison- # This ensures we're comparing dates in the same format (ISO 8601)- parsed_date = determine_parsed_date_for_property_matching(value)- if parsed_date:- effective_value = parsed_date.isoformat()-- # nosemgrep: orm-field-injection -- key prefixed by JSONField column; __ is JSON key traversal, not FK- return Q(**{f"{column}__{property.key}__{effective_operator}": effective_value})-- if property.operator == "is_not":- # is_not is inverse of exact- return empty_or_null_with_value_q(column, property.key, "exact", value, negated=True)-- # NOTE: existence clause necessary when overall clause is negated- return empty_or_null_with_value_q(column, property.key, property.operator, property.value)---def property_group_to_Q(- project_id: int,- property_group: PropertyGroup,- override_property_values: Optional[dict[str, Any]] = None,- cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,- using_database: str = "default",-) -> Q:- if override_property_values is None:- override_property_values = {}- filters = Q()-- if not property_group or len(property_group.values) == 0:- return filters-- if isinstance(property_group.values[0], PropertyGroup):- for group in property_group.values:- group_filter = property_group_to_Q(- project_id,- cast(PropertyGroup, group),- override_property_values,- cohorts_cache,- using_database,- )- if property_group.type == PropertyOperatorType.OR:- filters |= group_filter- else:- filters &= group_filter- else:- for property in property_group.values:- property = cast(Property, property)- property_filter = property_to_Q(- project_id,- property,- override_property_values,- cohorts_cache,- using_database,- )- if property_group.type == PropertyOperatorType.OR:- if property.negation:- filters |= ~property_filter- else:- filters |= property_filter- else:- if property.negation:- filters &= ~property_filter- else:- filters &= property_filter-- return filters---def properties_to_Q(- project_id: int,- properties: list[Property],- override_property_values: Optional[dict[str, Any]] = None,- cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,- using_database: str = "default",-) -> Q:- """- Converts a filter to Q, for use in Django ORM .filter()- If you're filtering a Person/Group QuerySet, use is_direct_query to avoid doing an unnecessary nested loop- """- if override_property_values is None:- override_property_values = {}- filters = Q()-- if len(properties) == 0:- return filters-- return property_group_to_Q(- project_id,- PropertyGroup(type=PropertyOperatorType.AND, values=properties),- override_property_values,- cohorts_cache,- using_database,- )---def is_truthy_or_falsy_property_value(value: Any) -> bool:- # Does not resolve 0 and 1 as true, but does resolve the strings as true- return (- value in ("true", ["true"], [True], [False], "false", ["false"], "True", ["True"], "False", ["False"])- or value is True- or value is False- )--# Note: Any changes to this function need to be reflected in the rust version# rust/feature-flags/src/properties/relative_date.rsdef relative_date_parse_for_feature_flag_matching(value: str) -> Optional[datetime.datetime]:@@ -544,64 +151,3 @@ def relative_date_parse_for_feature_flag_matching(value: str) -> Optional[datetireturn parsed_dtelse:return None---def sanitize_property_key(key: Any) -> str:- string_key = str(key)- # remove all but a-zA-Z0-9 characters from the key- substitute = re.sub(r"[^a-zA-Z0-9]", "", string_key)-- # :TRICKY: We also want to prevent clashes between key1_ and key1, or key1 and key2 so we add- # a salt based on hash of the key- # This is because we don't want to overwrite the value of key1 when we're trying to read key2- # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1- hash_value = hashlib.sha1(string_key.encode("utf-8")).hexdigest()[:15]- return f"{substitute}_{hash_value}"---def sanitize_regex_pattern(pattern: str) -> str:- # If it doesn't look like a property match pattern, return it as-is- if not ('"' in pattern or "'" in pattern or ":" in pattern):- return pattern-- # First, temporarily replace escaped quotes with markers- pattern = pattern.replace(r"\"", "__ESCAPED_DOUBLE_QUOTE__")- pattern = pattern.replace(r"\'", "__ESCAPED_SINGLE_QUOTE__")-- # Replace unescaped quotes with a pattern that matches either quote type- pattern = pattern.replace('"', "['\"]")-- # Add optional whitespace around colons to handle Python dict format- pattern = pattern.replace(":", r"\s*:\s*")-- # Now restore the escaped quotes, but convert them to also match either quote type- pattern = pattern.replace("__ESCAPED_DOUBLE_QUOTE__", "['\"]")- pattern = pattern.replace("__ESCAPED_SINGLE_QUOTE__", "['\"]")-- # If the pattern looks like a property match (key:value), convert it to use lookaheads- if "['\"]" in pattern:- # Split the pattern if it's trying to match multiple properties- parts = pattern.split("[^}]*")- converted_parts = []- for part in parts:- if "['\"]" in part:- # Extract the key and value from patterns like ['"]key['"]\s*:\s*['"]value['"]- try:- # Use a non-capturing group for quotes and match the exact key name- # This ensures we don't match partial keys or keys that are substrings of others- key = re.search(r'\[\'"\]((?:[^\'"\s:}]+))\[\'"\]\\s\*:\\s\*\[\'"\](.*?)\[\'"\]', part)- if key:- key_name, value = key.groups()- # Escape special regex characters in the key name- escaped_key_name = re.escape(key_name)- # Convert to a positive lookahead that matches the exact key-value pair- converted = f"(?=.*['\"]?{escaped_key_name}['\"]?\\s*:\\s*['\"]?{value}['\"]?)"- converted_parts.append(converted)- except Exception:- # If we can't parse it, use the original pattern- converted_parts.append(part)- else:- converted_parts.append(part)- pattern = "".join(converted_parts)-- return patterndiff --git a/posthog/queries/test/test_base.py b/posthog/queries/test/test_base.pyindex 95da2d0c8306..282360e2bc59 100644--- a/posthog/queries/test/test_base.py+++ b/posthog/queries/test/test_base.py@@ -1,27 +1,14 @@-import reimport datetimefrom zoneinfo import ZoneInfo-import pytestimport unittestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest-from unittest.mock import patch-from django.test import TestCase--from dateutil import parser, tz-from rest_framework.exceptions import ValidationError+from dateutil import tzfrom posthog.models.filters.path_filter import PathFilter-from posthog.models.property.property import Property-from posthog.queries.base import (- determine_parsed_incoming_date,- match_property,- relative_date_parse_for_feature_flag_matching,- sanitize_property_key,- sanitize_regex_pattern,-)+from posthog.queries.base import determine_parsed_incoming_date, relative_date_parse_for_feature_flag_matchingclass TestBase(APIBaseTest):@@ -41,241 +28,7 @@ class TestBase(APIBaseTest):)-class TestMatchProperties(TestCase):- def test_match_properties_exact(self):- property_a = Property(key="key", value="value")-- self.assertTrue(match_property(property_a, {"key": "value"}))-- self.assertFalse(match_property(property_a, {"key": "value2"}))- self.assertFalse(match_property(property_a, {"key": ""}))- self.assertFalse(match_property(property_a, {"key": None}))-- with self.assertRaises(ValidationError):- match_property(property_a, {"key2": "value"})- match_property(property_a, {})-- property_b = Property(key="key", value="value", operator="exact")- self.assertTrue(match_property(property_b, {"key": "value"}))-- self.assertFalse(match_property(property_b, {"key": "value2"}))-- property_c = Property(key="key", value=["value1", "value2", "value3"], operator="exact")- self.assertTrue(match_property(property_c, {"key": "value1"}))- self.assertTrue(match_property(property_c, {"key": "value2"}))- self.assertTrue(match_property(property_c, {"key": "value3"}))-- self.assertFalse(match_property(property_c, {"key": "value4"}))-- with self.assertRaises(ValidationError):- match_property(property_c, {"key2": "value"})-- def test_match_properties_not_in(self):- property_a = Property(key="key", value="value", operator="is_not")- self.assertTrue(match_property(property_a, {"key": "value2"}))- self.assertTrue(match_property(property_a, {"key": ""}))- self.assertTrue(match_property(property_a, {"key": None}))-- property_c = Property(key="key", value=["value1", "value2", "value3"], operator="is_not")- self.assertTrue(match_property(property_c, {"key": "value4"}))- self.assertTrue(match_property(property_c, {"key": "value5"}))- self.assertTrue(match_property(property_c, {"key": "value6"}))- self.assertTrue(match_property(property_c, {"key": ""}))- self.assertTrue(match_property(property_c, {"key": None}))-- self.assertFalse(match_property(property_c, {"key": "value2"}))- self.assertFalse(match_property(property_c, {"key": "value3"}))- self.assertFalse(match_property(property_c, {"key": "value1"}))-- with self.assertRaises(ValidationError):- match_property(property_a, {"key2": "value"})- match_property(property_c, {"key2": "value1"}) # overrides don't have 'key'-- def test_match_properties_is_set(self):- property_a = Property(key="key", operator="is_set")- self.assertTrue(match_property(property_a, {"key": "value"}))- self.assertTrue(match_property(property_a, {"key": "value2"}))- self.assertTrue(match_property(property_a, {"key": ""}))- self.assertTrue(match_property(property_a, {"key": None}))-- with self.assertRaises(ValidationError):- match_property(property_a, {"key2": "value"})- match_property(property_a, {})-- def test_match_properties_icontains(self):- property_a = Property(key="key", value="valUe", operator="icontains")- self.assertTrue(match_property(property_a, {"key": "value"}))- self.assertTrue(match_property(property_a, {"key": "value2"}))- self.assertTrue(match_property(property_a, {"key": "value3"}))- self.assertTrue(match_property(property_a, {"key": "vaLue4"}))- self.assertTrue(match_property(property_a, {"key": "343tfvalue5"}))-- self.assertFalse(match_property(property_a, {"key": "Alakazam"}))- self.assertFalse(match_property(property_a, {"key": 123}))-- property_b = Property(key="key", value="3", operator="icontains")- self.assertTrue(match_property(property_b, {"key": "3"}))- self.assertTrue(match_property(property_b, {"key": 323}))- self.assertTrue(match_property(property_b, {"key": "val3"}))-- self.assertFalse(match_property(property_b, {"key": "three"}))-- def test_match_properties_regex(self):- property_a = Property(key="key", value=r"\.com$", operator="regex")- self.assertTrue(match_property(property_a, {"key": "value.com"}))- self.assertTrue(match_property(property_a, {"key": "value2.com"}))-- self.assertFalse(match_property(property_a, {"key": ".com343tfvalue5"}))- self.assertFalse(match_property(property_a, {"key": "Alakazam"}))- self.assertFalse(match_property(property_a, {"key": 123}))-- property_b = Property(key="key", value="3", operator="regex")- self.assertTrue(match_property(property_b, {"key": "3"}))- self.assertTrue(match_property(property_b, {"key": 323}))- self.assertTrue(match_property(property_b, {"key": "val3"}))-- self.assertFalse(match_property(property_b, {"key": "three"}))-- # invalid regex- property_c = Property(key="key", value=r"?*", operator="regex")- self.assertFalse(match_property(property_c, {"key": "value"}))- self.assertFalse(match_property(property_c, {"key": "value2"}))-- # non string value- property_d = Property(key="key", value=4, operator="regex")- self.assertTrue(match_property(property_d, {"key": "4"}))- self.assertTrue(match_property(property_d, {"key": 4}))-- self.assertFalse(match_property(property_d, {"key": "value"}))-- # ensure regex compilation happens only once. to do this, we mock out re.compile,- # and make the return value of the mock match what the actual function would return.- # this allows us to intercept the call and assert that it was called exactly once.- property_e = Property(key="key", value=5, operator="regex")- pattern = re.compile("5")- with patch("re.compile") as mock_compile:- mock_compile.return_value = pattern- self.assertTrue(match_property(property_e, {"key": "5"}))-- mock_compile.assert_called_once_with("5", re.IGNORECASE | re.DOTALL)-- def test_match_properties_math_operators(self):- property_a = Property(key="key", value=1, operator="gt")- self.assertTrue(match_property(property_a, {"key": 2}))- self.assertTrue(match_property(property_a, {"key": 3}))-- self.assertFalse(match_property(property_a, {"key": 0}))- self.assertFalse(match_property(property_a, {"key": -1}))- # now we handle type mismatches so this should be true- self.assertTrue(match_property(property_a, {"key": "23"}))-- property_b = Property(key="key", value=1, operator="lt")- self.assertTrue(match_property(property_b, {"key": 0}))- self.assertTrue(match_property(property_b, {"key": -1}))- self.assertTrue(match_property(property_b, {"key": -3}))-- self.assertFalse(match_property(property_b, {"key": 1}))- self.assertFalse(match_property(property_b, {"key": "1"}))- self.assertFalse(match_property(property_b, {"key": "3"}))-- property_c = Property(key="key", value=1, operator="gte")- self.assertTrue(match_property(property_c, {"key": 1}))- self.assertTrue(match_property(property_c, {"key": 2}))-- self.assertFalse(match_property(property_c, {"key": 0}))- self.assertFalse(match_property(property_c, {"key": -1}))- # now we handle type mismatches so this should be true- self.assertTrue(match_property(property_c, {"key": "3"}))-- property_d = Property(key="key", value="43", operator="lt")- self.assertTrue(match_property(property_d, {"key": "41"}))- self.assertTrue(match_property(property_d, {"key": "42"}))- self.assertTrue(match_property(property_d, {"key": 42}))-- self.assertFalse(match_property(property_d, {"key": "43"}))- self.assertFalse(match_property(property_d, {"key": "44"}))- self.assertFalse(match_property(property_d, {"key": 44}))-- property_e = Property(key="key", value="30", operator="lt")- self.assertTrue(match_property(property_e, {"key": "29"}))-- # depending on the type of override, we adjust type comparison- self.assertTrue(match_property(property_e, {"key": "100"}))- self.assertFalse(match_property(property_e, {"key": 100}))-- property_f = Property(key="key", value="123aloha", operator="gt")- self.assertFalse(match_property(property_f, {"key": "123"}))- self.assertFalse(match_property(property_f, {"key": 122}))-- # this turns into a string comparison- self.assertTrue(match_property(property_f, {"key": 129}))-- def test_match_property_date_operators(self):- property_a = Property(key="key", value="2022-05-01", operator="is_date_before")- self.assertTrue(match_property(property_a, {"key": "2022-03-01"}))- self.assertTrue(match_property(property_a, {"key": "2022-04-30"}))- self.assertTrue(match_property(property_a, {"key": datetime.date(2022, 4, 30)}))- self.assertTrue(match_property(property_a, {"key": datetime.datetime(2022, 4, 30, 1, 2, 3)}))- self.assertTrue(- match_property(- property_a,- {"key": datetime.datetime(2022, 4, 30, 1, 2, 3, tzinfo=tz.gettz("Europe/Madrid"))},- )- )- self.assertTrue(match_property(property_a, {"key": parser.parse("2022-04-30")}))- self.assertFalse(match_property(property_a, {"key": "2022-05-30"}))-- # can't be invalid string- self.assertFalse(match_property(property_a, {"key": "abcdef"}))-- property_b = Property(key="key", value="2022-05-01", operator="is_date_after")- self.assertTrue(match_property(property_b, {"key": "2022-05-02"}))- self.assertTrue(match_property(property_b, {"key": "2022-05-30"}))- self.assertTrue(match_property(property_b, {"key": datetime.datetime(2022, 5, 30)}))- self.assertTrue(match_property(property_b, {"key": parser.parse("2022-05-30")}))- self.assertFalse(match_property(property_b, {"key": "2022-04-30"}))-- # can't be invalid string- self.assertFalse(match_property(property_b, {"key": "abcdef"}))-- # Invalid flag property- property_c = Property(key="key", value=1234, operator="is_date_before")-- self.assertFalse(match_property(property_c, {"key": 1}))- self.assertFalse(match_property(property_c, {"key": "2022-05-30"}))-- # Timezone aware property- property_d = Property(key="key", value="2022-04-05 12:34:12 BST", operator="is_date_before")- self.assertFalse(match_property(property_d, {"key": "2022-05-30"}))-- self.assertTrue(match_property(property_d, {"key": "2022-03-30"}))- self.assertTrue(match_property(property_d, {"key": "2022-04-05 12:34:11 BST"}))- self.assertTrue(match_property(property_d, {"key": "2022-04-05 12:34:11 CET"}))-- self.assertFalse(match_property(property_d, {"key": "2022-04-05 12:34:13 CET"}))-- def test_match_property_date_operators_with_numeric_timestamps(self):- property_a = Property(key="key", value="2027-03-21T00:00:00Z", operator="is_date_after")- self.assertTrue(match_property(property_a, {"key": 1836277747}))- self.assertTrue(match_property(property_a, {"key": 1836277747.867530}))- self.assertFalse(match_property(property_a, {"key": 1747794128}))-- property_b = Property(key="key", value="2027-03-21T00:00:00Z", operator="is_date_before")- self.assertFalse(match_property(property_b, {"key": 1836277747}))- self.assertFalse(match_property(property_b, {"key": 1836277747.867530}))- self.assertTrue(match_property(property_b, {"key": 1747794128}))-- property_e = Property(key="key", value="2028-03-10T05:09:07Z", operator="is_date_exact")- self.assertTrue(match_property(property_e, {"key": 1836277747}))-- def test_match_property_date_operators_with_string_timestamps(self):- property_a = Property(key="key", value="2027-03-21T00:00:00Z", operator="is_date_after")- self.assertTrue(match_property(property_a, {"key": "1836277747"}))- self.assertFalse(match_property(property_a, {"key": "1747794128"}))-- property_e = Property(key="key", value="2028-03-10T05:09:07Z", operator="is_date_exact")- self.assertTrue(match_property(property_e, {"key": "1836277747"}))-+class TestDetermineParsedIncomingDate(unittest.TestCase):def test_determine_parsed_incoming_date_with_int_timestamp(self):self.assertEqual(determine_parsed_incoming_date(1836277747), datetime.datetime(2028, 3, 10, 5, 9, 7, tzinfo=ZoneInfo("UTC"))@@ -306,165 +59,6 @@ class TestMatchProperties(TestCase):expected = datetime.datetime(2028, 3, 10, 5, 9, 7, 867530, tzinfo=ZoneInfo("UTC"))self.assertEqual(determine_parsed_incoming_date(timestamp), expected)- @freeze_time("2022-05-01")- def test_match_property_relative_date_operators(self):- property_a = Property(key="key", value="6h", operator="is_date_before")- self.assertTrue(match_property(property_a, {"key": "2022-03-01"}))- self.assertTrue(match_property(property_a, {"key": "2022-04-30"}))- self.assertTrue(match_property(property_a, {"key": datetime.datetime(2022, 4, 30, 1, 2, 3)}))- # The date gets converted to datetime at midnight UTC, which is before 6 hours ago- self.assertTrue(match_property(property_a, {"key": datetime.date(2022, 4, 30)}))-- self.assertFalse(match_property(property_a, {"key": datetime.datetime(2022, 4, 30, 19, 2, 3)}))- self.assertTrue(- match_property(- property_a,- {"key": datetime.datetime(2022, 4, 30, 1, 2, 3, tzinfo=tz.gettz("Europe/Madrid"))},- )- )- self.assertTrue(match_property(property_a, {"key": parser.parse("2022-04-30")}))- self.assertFalse(match_property(property_a, {"key": "2022-05-30"}))-- # can't be invalid string- self.assertFalse(match_property(property_a, {"key": "abcdef"}))-- property_b = Property(key="key", value="1h", operator="is_date_after")- self.assertTrue(match_property(property_b, {"key": "2022-05-02"}))- self.assertTrue(match_property(property_b, {"key": "2022-05-30"}))- self.assertTrue(match_property(property_b, {"key": datetime.datetime(2022, 5, 30)}))- self.assertTrue(match_property(property_b, {"key": parser.parse("2022-05-30")}))- self.assertFalse(match_property(property_b, {"key": "2022-04-30"}))-- # can't be invalid string- self.assertFalse(match_property(property_b, {"key": "abcdef"}))-- # Invalid flag property- property_c = Property(key="key", value=1234, operator="is_date_after")-- self.assertTrue(match_property(property_c, {"key": "2022-05-30"}))-- # # Timezone aware property- property_d = Property(key="key", value="12d", operator="is_date_before")- self.assertFalse(match_property(property_d, {"key": "2022-05-30"}))-- self.assertTrue(match_property(property_d, {"key": "2022-03-30"}))- self.assertTrue(match_property(property_d, {"key": "2022-04-05 12:34:11+01:00"}))- self.assertTrue(match_property(property_d, {"key": "2022-04-19 01:34:11+02:00"}))-- self.assertFalse(match_property(property_d, {"key": "2022-04-19 02:00:01+02:00"}))-- # Try all possible relative dates- property_e = Property(key="key", value="1h", operator="is_date_before")- self.assertFalse(match_property(property_e, {"key": "2022-05-01 00:00:00"}))- self.assertTrue(match_property(property_e, {"key": "2022-04-30 22:00:00"}))-- property_f = Property(key="key", value="-1d", operator="is_date_before")- self.assertTrue(match_property(property_f, {"key": "2022-04-29 23:59:00"}))- self.assertFalse(match_property(property_f, {"key": "2022-04-30 00:00:01"}))-- property_g = Property(key="key", value="1w", operator="is_date_before")- self.assertTrue(match_property(property_g, {"key": "2022-04-23 00:00:00"}))- self.assertFalse(match_property(property_g, {"key": "2022-04-24 00:00:00"}))- self.assertFalse(match_property(property_g, {"key": "2022-04-24 00:00:01"}))-- property_h = Property(key="key", value="1m", operator="is_date_before")- self.assertTrue(match_property(property_h, {"key": "2022-03-01 00:00:00"}))- self.assertFalse(match_property(property_h, {"key": "2022-04-05 00:00:00"}))-- property_i = Property(key="key", value="1y", operator="is_date_before")- self.assertTrue(match_property(property_i, {"key": "2021-04-28 00:00:00"}))- self.assertFalse(match_property(property_i, {"key": "2021-05-01 00:00:01"}))-- property_j = Property(key="key", value="-122h", operator="is_date_after")- self.assertTrue(match_property(property_j, {"key": "2022-05-01 00:00:00"}))- self.assertFalse(match_property(property_j, {"key": "2022-04-23 01:00:00"}))-- property_k = Property(key="key", value="2d", operator="is_date_after")- self.assertTrue(match_property(property_k, {"key": "2022-05-01 00:00:00"}))- self.assertTrue(match_property(property_k, {"key": "2022-04-29 00:00:01"}))- self.assertFalse(match_property(property_k, {"key": "2022-04-29 00:00:00"}))-- property_l = Property(key="key", value="02w", operator="is_date_after")- self.assertTrue(match_property(property_l, {"key": "2022-05-01 00:00:00"}))- self.assertFalse(match_property(property_l, {"key": "2022-04-16 00:00:00"}))-- property_m = Property(key="key", value="-1m", operator="is_date_after")- self.assertTrue(match_property(property_m, {"key": "2022-04-01 00:00:01"}))- self.assertFalse(match_property(property_m, {"key": "2022-04-01 00:00:00"}))-- property_n = Property(key="key", value="1y", operator="is_date_after")- self.assertTrue(match_property(property_n, {"key": "2022-05-01 00:00:00"}))- self.assertTrue(match_property(property_n, {"key": "2021-05-01 00:00:01"}))- self.assertFalse(match_property(property_n, {"key": "2021-05-01 00:00:00"}))- self.assertFalse(match_property(property_n, {"key": "2021-04-30 00:00:00"}))- self.assertFalse(match_property(property_n, {"key": "2021-03-01 12:13:00"}))-- def test_none_property_value_with_all_operators(self):- property_a = Property(key="key", value="none", operator="is_not")- self.assertFalse(match_property(property_a, {"key": None}))- self.assertTrue(match_property(property_a, {"key": "non"}))-- property_b = Property(key="key", value=None, operator="is_set")- self.assertTrue(match_property(property_b, {"key": None}))-- property_c = Property(key="key", value="no", operator="icontains")- self.assertTrue(match_property(property_c, {"key": None}))- self.assertFalse(match_property(property_c, {"key": "smh"}))-- property_d = Property(key="key", value="No", operator="regex")- self.assertTrue(match_property(property_d, {"key": None}))-- property_d_lower_case = Property(key="key", value="no", operator="regex")- self.assertTrue(match_property(property_d_lower_case, {"key": None}))-- property_d_non_matching = Property(key="key", value="xyz", operator="regex")- self.assertFalse(match_property(property_d_non_matching, {"key": None}))-- property_e = Property(key="key", value=1, operator="gt")- self.assertTrue(match_property(property_e, {"key": None}))-- property_f = Property(key="key", value=1, operator="lt")- self.assertFalse(match_property(property_f, {"key": None}))-- property_g = Property(key="key", value="xyz", operator="gte")- self.assertFalse(match_property(property_g, {"key": None}))-- property_h = Property(key="key", value="Oo", operator="lte")- self.assertTrue(match_property(property_h, {"key": None}))-- property_i = Property(key="key", value="2022-05-01", operator="is_date_before")- self.assertFalse(match_property(property_i, {"key": None}))-- property_j = Property(key="key", value="2022-05-01", operator="is_date_after")- self.assertFalse(match_property(property_j, {"key": None}))-- property_k = Property(key="key", value="2022-05-01", operator="is_date_before")- self.assertFalse(match_property(property_k, {"key": "random"}))--- "key,expected",- [- ("test_key", "testkey_00942f4668670f3"),- ("test-key", "testkey_3acfb2c2b433c0e"),- ("test-!!key", "testkey_007a0fef83e9d2f"),- ("test-key-1", "testkey1_1af855c78902ffc"),- ("test-key-1-2", "testkey12_2f0c347f439af5c"),- ("test-key-1-2-3-4", "testkey1234_0332a83ad5c75ee"),- ("only_nums!!!;$£hebfjhvd", "onlynumshebfjhvd_5a1514bfab83040"),- (" ", "_b858cb282617fb0"),- ("", "_da39a3ee5e6b4b0"),- ("readme.md", "readmemd_275d783e2982285"),- ("readme≥md", "readmemd_8857015efe59db9"),- (None, "None_6eef6648406c333"),- (12, "12_7b52009b64fd0a2"),- ],-)-def test_sanitize_keys(key, expected):- sanitized_key = sanitize_property_key(key)-- assert sanitized_key == expected-class TestRelativeDateParsing(unittest.TestCase):def test_invalid_input(self):@@ -612,163 +206,3 @@ class TestRelativeDateParsing(unittest.TestCase):assert relative_date_parse_for_feature_flag_matching("8y") == datetime.datetime(2012, 1, 1, 12, 1, 20, 134000, tzinfo=tz.gettz("UTC"))---class TestSanitizeRegexPattern(TestCase):- def test_basic_property_matching(self):- test_cases = [- # Simple key-value matches- ('"key":"value"', "{'key': 'value'}", True),- # Quote style variations- ("'key':'value'", "{'key': 'value'}", True),- (r"\"key\":\"value\"", "{'key': 'value'}", True),- # Whitespace handling- ('"key" : "value"', "{'key':'value'}", True),- ('"key":"value"', "{'key': 'value'}", True),- # Case sensitivity- ('"LANG":"EN"', "{'lang': 'en'}", True),- ('"lang":"en"', "{'LANG': 'EN'}", True),- # Basic non-matching cases- ('"key":"value"', "{'key': 'different'}", False),- ('"key":"value"', "{'different': 'value'}", False),- ]-- for pattern, test_string, should_match in test_cases:- sanitized = sanitize_regex_pattern(pattern)- match = re.search(sanitized, test_string, re.DOTALL | re.IGNORECASE)- self.assertEqual(- bool(match),- should_match,- f"Failed for pattern: {pattern}\nSanitized to: {sanitized}\nTesting against: {test_string}\nExpected match: {should_match}",- )-- def test_property_name_patterns(self):- test_cases = [- # Special characters in property names- ('"user-id":"123"', "{'user-id': '123'}", True),- ('"@timestamp":"2023-01-01"', "{'@timestamp': '2023-01-01'}", True),- ('"$ref":"#/definitions/user"', "{'$ref': '#/definitions/user'}", True),- ('"special.key":"value"', "{'special.key': 'value'}", True),- ('"snake_case_key":"value"', "{'snake_case_key': 'value'}", True),- # Unicode and emoji- ('"über":"value"', "{'über': 'value'}", True),- ('"emoji🔑":"value"', "{'emoji🔑': 'value'}", True),- # Empty or special-only names- ('"-":"value"', "{'-': 'value'}", True),- ('"_":"value"', "{'_': 'value'}", True),- # Multiple special characters- ('"[email protected]":"value"', "{'[email protected]': 'value'}", True),- # Partial matches should not work- ('"user-id":"123"', "{'different-id': '123'}", False),- ('"lang":"en"', "{'language': 'en'}", False),- ]-- for pattern, test_string, should_match in test_cases:- sanitized = sanitize_regex_pattern(pattern)- match = re.search(sanitized, test_string, re.DOTALL | re.IGNORECASE)- self.assertEqual(- bool(match),- should_match,- f"Failed for pattern: {pattern}\nSanitized to: {sanitized}\nTesting against: {test_string}\nExpected match: {should_match}",- )-- def test_nested_structures(self):- test_cases = [- # Simple nested dictionary- ('"key":"value"', "{'parent': {'key': 'value'}}", True),- # Multiple levels of nesting- ('"a":{"b":{"c":"value"}}', '{"a":{"b":{"c":"value"}}}', True),- # Array values- ('"array":["value1","value2"]', '{"array":["value1","value2"]}', True),- # Mixed nesting with arrays and objects- ('"data":{"items":[{"id":"123"}]}', '{"data":{"items":[{"id":"123"}]}}', True),- # Multiple properties with nesting- (- '"lang":"en"[^}]*"slug":"web"',- "{'id': 123, 'data': {'lang': 'en', 'meta': {'slug': 'web'}, 'active': true}}",- True,- ),- # Incorrect nesting level should not match- (- '"lang":"en"[^}]*"slug":"web"',- "{'data': {'lang': 'en'}, 'slug': 'mobile'}",- False,- ),- # Nested structures with whitespace and newlines- (- '"lang":"en"[^}]*"slug":"web"',- """- {- 'data': {- 'lang': 'en',- 'slug': 'web'- }- }- """,- True,- ),- ]-- for pattern, test_string, should_match in test_cases:- sanitized = sanitize_regex_pattern(pattern)- match = re.search(sanitized, test_string, re.DOTALL | re.IGNORECASE)- self.assertEqual(- bool(match),- should_match,- f"Failed for pattern: {pattern}\nSanitized to: {sanitized}\nTesting against: {test_string}\nExpected match: {should_match}",- )-- def test_multiple_properties(self):- test_cases = [- # Multiple properties in any order- ('"lang":"en"[^}]*"slug":"web"', "{'slug': 'web', 'lang': 'en'}", True),- ('"lang":"en"[^}]*"slug":"web"', "{'lang': 'en', 'slug': 'web'}", True),- # Properties with other data in between- ('"lang":"en"[^}]*"slug":"web"', "{'name': 'test', 'lang': 'en', 'other': 123, 'slug': 'web'}", True),- # Missing required property- ('"lang":"en"[^}]*"slug":"web"', "{'lang': 'en', 'url': 'web'}", False),- # Wrong property values- ('"lang":"en"[^}]*"slug":"web"', "{'lang': 'es', 'slug': 'web'}", False),- ('"lang":"en"[^}]*"slug":"web"', "{'lang': 'en', 'slug': 'mobile'}", False),- ]-- for pattern, test_string, should_match in test_cases:- sanitized = sanitize_regex_pattern(pattern)- match = re.search(sanitized, test_string, re.DOTALL | re.IGNORECASE)- self.assertEqual(- bool(match),- should_match,- f"Failed for pattern: {pattern}\nSanitized to: {sanitized}\nTesting against: {test_string}\nExpected match: {should_match}",- )-- def test_simple_regex_patterns(self):- test_cases = [- # Basic regex patterns- (r"^test$", "test", True),- (r"^test$", "test123", False),- (r"test\d+", "test123", True),- (r"test\d+", "test", False),- # Wildcards and character classes- (r".*\.com$", "example.com", True),- (r".*\.com$", "example.org", False),- (r"[a-z]+", "abc", True),- (r"[a-z]+", "123", False),- # Groups and alternation- (r"(foo|bar)", "foo", True),- (r"(foo|bar)", "bar", True),- (r"(foo|bar)", "baz", False),- # Common patterns (email, URL)- (r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", "[email protected]", True),- (r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", "invalid-email", False),- (r"^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", "https://example.com", True),- (r"^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", "not-a-url", False),- ]-- for pattern, test_string, should_match in test_cases:- sanitized = sanitize_regex_pattern(pattern)- match = re.search(sanitized, test_string, re.DOTALL | re.IGNORECASE)- self.assertEqual(- bool(match),- should_match,- f"Failed for pattern: {pattern}\nSanitized to: {sanitized}\nTesting against: {test_string}\nExpected match: {should_match}",- )