Compare commits

...
12 Commits
Author SHA1 Message Date
Eric DuongandGitHub 4aa3499527 version 2.5.0 (#97) 2023-04-10 15:13:25 -04:00
Eric DuongandGitHub de7def97e2 chore: change package to be an instantiable client (#96)
* initial try

* change init file to a class

* remove commas

* format

* sort

* restore original and add renamed client

* format

* move disabled

* format

* handle changing var for global instance

* add test
2023-04-10 14:33:07 -04:00
Neil KakkarandGitHub dfefd0a1b6 Fix analytics package dependencies (#95) 2023-03-30 10:34:59 -04:00
Neil KakkarandGitHub 477a688016 Add CI to ensure no prints (#94) 2023-03-17 15:22:59 +00:00
Neil KakkarandGitHub fa474a0fe6 Release for print fix (#93) 2023-03-17 12:41:16 +00:00
Jann KleenandGitHub f8bc3f17eb Remove print() call (#92) 2023-03-17 12:37:01 +00:00
Neil KakkarandGitHub 07277d35e7 feat(flags): Enable local evaluation for all cohorts (#91) 2023-03-16 10:47:29 +00:00
Eric DuongandGitHub 15d0716744 fix test (#90) 2023-02-14 14:24:10 -05:00
Eric DuongandGitHub b4103b3ae2 fix: add function for active variants (#89)
* add function for active variants

* format
2023-02-14 10:45:14 -05:00
Eric DuongandGitHub 1aeffa990f add changelog entry and update versoin (#87) 2023-02-07 10:47:26 -05:00
Eric DuongandGitHub 5ae7feb4e9 chore: Remove upper bound (#85)
* remove upper bound

* format
2023-02-07 10:36:26 -05:00
6534afd8e3 fix: change api error to log (#83)
* change api error to log

* change implementation

* sort

* format

* raise when debug is true

* Update posthog/test/test_feature_flags.py

* format

---------

Co-authored-by: Neil Kakkar <neilkakkar@gmail.com>
2023-02-07 10:17:56 -05:00
13 changed files with 433 additions and 67 deletions
+4
View File
@@ -33,6 +33,10 @@ jobs:
- name: Check formatting with black
run: |
black --check .
- name: Lint with flake8
run: |
flake8 posthog --ignore E501
- name: Check import order with isort
run: |
+22
View File
@@ -1,3 +1,25 @@
## 2.5.0 - 2023-04-10
1. Add option for instantiating separate client object
## 2.4.2 - 2023-03-30
1. Update backoff dependency for posthoganalytics package to be the same as posthog package
## 2.4.1 - 2023-03-17
1. Removes accidental print call left in for decide response
## 2.4.0 - 2023-03-14
1. Support evaluating all cohorts in feature flags for local evaluation
## 2.3.1 - 2023-02-07
1. Log instead of raise error on posthog personal api key errors
2. Remove upper bound on backoff dependency
## 2.3.0 - 2023-01-31
1. Add support for returning payloads of matched feature flags
+20 -12
View File
@@ -1,4 +1,5 @@
from typing import Callable, Dict, Optional
import datetime # noqa: F401
from typing import Callable, Dict, Optional # noqa: F401
from posthog.client import Client
from posthog.version import VERSION
@@ -98,7 +99,7 @@ def identify(
def set(
distinct_id, # type: str,
distinct_id, # type: str
properties=None, # type: Optional[Dict]
context=None, # type: Optional[Dict]
timestamp=None, # type: Optional[datetime.datetime]
@@ -131,7 +132,7 @@ def set(
def set_once(
distinct_id, # type: str,
distinct_id, # type: str
properties=None, # type: Optional[Dict]
context=None, # type: Optional[Dict]
timestamp=None, # type: Optional[datetime.datetime]
@@ -199,8 +200,8 @@ def group_identify(
def alias(
previous_id, # type: str,
distinct_id, # type: str,
previous_id, # type: str
distinct_id, # type: str
context=None, # type: Optional[Dict]
timestamp=None, # type: Optional[datetime.datetime]
uuid=None, # type: Optional[str]
@@ -233,8 +234,8 @@ def alias(
def feature_enabled(
key, # type: str,
distinct_id, # type: str,
key, # type: str
distinct_id, # type: str
groups={}, # type: dict
person_properties={}, # type: dict
group_properties={}, # type: dict
@@ -268,8 +269,8 @@ def feature_enabled(
def get_feature_flag(
key, # type: str,
distinct_id, # type: str,
key, # type: str
distinct_id, # type: str
groups={}, # type: dict
person_properties={}, # type: dict
group_properties={}, # type: dict
@@ -311,7 +312,7 @@ def get_feature_flag(
def get_all_flags(
distinct_id, # type: str,
distinct_id, # type: str
groups={}, # type: dict
person_properties={}, # type: dict
group_properties={}, # type: dict
@@ -405,8 +406,6 @@ def shutdown():
def _proxy(method, *args, **kwargs):
"""Create an analytics client if one doesn't exist and send to it."""
global default_client
if disabled:
return None
if not default_client:
default_client = Client(
api_key,
@@ -418,7 +417,16 @@ def _proxy(method, *args, **kwargs):
personal_api_key=personal_api_key,
project_api_key=project_api_key,
poll_interval=poll_interval,
disabled=disabled,
)
# always set incase user changes it
default_client.disabled = disabled
default_client.debug = debug
fn = getattr(default_client, method)
return fn(*args, **kwargs)
class Posthog(Client):
pass
+31 -15
View File
@@ -47,8 +47,8 @@ class Client(object):
poll_interval=30,
personal_api_key=None,
project_api_key=None,
disabled=False,
):
self.queue = queue.Queue(max_queue_size)
# api_key: This should be the Team API Key (token), public
@@ -66,9 +66,11 @@ class Client(object):
self.feature_flags = None
self.feature_flags_by_key = None
self.group_type_mapping = None
self.cohorts = None
self.poll_interval = poll_interval
self.poller = None
self.distinct_ids_feature_flags_reported = SizeLimitedDict(MAX_DICT_SIZE, set)
self.disabled = disabled
# personal_api_key: This should be a generated Personal API Key, private
self.personal_api_key = personal_api_key
@@ -131,6 +133,12 @@ class Client(object):
resp_data = self.get_decide(distinct_id, groups, person_properties, group_properties)
return resp_data["featureFlags"]
def _get_active_feature_variants(self, distinct_id, groups=None, person_properties=None, group_properties=None):
feature_variants = self.get_feature_variants(distinct_id, groups, person_properties, group_properties)
return {
k: v for (k, v) in feature_variants.items() if v is not False
} # explicitly test for false to account for values that may seem falsy (ex: 0)
def get_feature_payloads(self, distinct_id, groups=None, person_properties=None, group_properties=None):
resp_data = self.get_decide(distinct_id, groups, person_properties, group_properties)
return resp_data["featureFlagPayloads"]
@@ -150,6 +158,7 @@ class Client(object):
"group_properties": group_properties,
}
resp_data = decide(self.api_key, self.host, timeout=10, **request_data)
return resp_data
def capture(
@@ -184,7 +193,7 @@ class Client(object):
if send_feature_flags:
try:
feature_variants = self.get_feature_variants(distinct_id, groups)
feature_variants = self._get_active_feature_variants(distinct_id, groups)
except Exception as e:
self.log.exception(f"[FEATURE FLAGS] Unable to get feature variants: {e}")
else:
@@ -292,6 +301,10 @@ class Client(object):
def _enqueue(self, msg):
"""Push a new `msg` onto the queue, return `(success, msg)`"""
if self.disabled:
return False, "disabled"
timestamp = msg["timestamp"]
if timestamp is None:
timestamp = datetime.utcnow().replace(tzinfo=tzutc())
@@ -367,10 +380,9 @@ class Client(object):
def _load_feature_flags(self):
try:
response = get(
self.personal_api_key,
f"/api/feature_flag/local_evaluation/?token={self.api_key}",
f"/api/feature_flag/local_evaluation/?token={self.api_key}&send_cohorts",
self.host,
timeout=10,
)
@@ -380,15 +392,20 @@ class Client(object):
flag["key"]: flag for flag in self.feature_flags if flag.get("key") is not None
}
self.group_type_mapping = response["group_type_mapping"] or {}
self.cohorts = response["cohorts"] or {}
except APIError as e:
if e.status == 401:
raise APIError(
status=401,
message="You are using a write-only key with feature flags. "
"To use feature flags, please set a personal_api_key "
"More information: https://posthog.com/docs/api/overview",
self.log.error(
"[FEATURE FLAGS] Error loading feature flags: To use feature flags, please set a valid personal_api_key. More information: https://posthog.com/docs/api/overview"
)
if self.debug:
raise APIError(
status=401,
message="You are using a write-only key with feature flags. "
"To use feature flags, please set a personal_api_key "
"More information: https://posthog.com/docs/api/overview",
)
else:
self.log.error(f"[FEATURE FLAGS] Error loading feature flags: {e}")
except Exception as e:
@@ -412,7 +429,6 @@ class Client(object):
self.poller.start()
def _compute_flag_locally(self, feature_flag, distinct_id, *, groups={}, person_properties={}, group_properties={}):
if feature_flag.get("ensure_experience_continuity", False):
raise InconclusiveMatchError("Flag has experience continuity enabled")
@@ -442,7 +458,7 @@ class Client(object):
focused_group_properties = group_properties[group_name]
return match_feature_flag_properties(feature_flag, groups[group_name], focused_group_properties)
else:
return match_feature_flag_properties(feature_flag, distinct_id, person_properties)
return match_feature_flag_properties(feature_flag, distinct_id, person_properties, self.cohorts)
def feature_enabled(
self,
@@ -484,7 +500,7 @@ class Client(object):
require("distinct_id", distinct_id, ID_TYPES)
require("groups", groups, dict)
if self.feature_flags == None and self.personal_api_key:
if self.feature_flags is None and self.personal_api_key:
self.load_feature_flags()
response = None
@@ -524,7 +540,7 @@ class Client(object):
feature_flag_reported_key = f"{key}_{str(response)}"
if (
feature_flag_reported_key not in self.distinct_ids_feature_flags_reported[distinct_id]
and send_feature_flag_events
and send_feature_flag_events # noqa: W503
):
self.capture(
distinct_id,
@@ -620,7 +636,7 @@ class Client(object):
require("distinct_id", distinct_id, ID_TYPES)
require("groups", groups, dict)
if self.feature_flags == None and self.personal_api_key:
if self.feature_flags is None and self.personal_api_key:
self.load_feature_flags()
flags = {}
@@ -640,7 +656,7 @@ class Client(object):
matched_payload = self._compute_payload_locally(flag["key"], flags[flag["key"]])
if matched_payload:
payloads[flag["key"]] = matched_payload
except InconclusiveMatchError as e:
except InconclusiveMatchError:
# No need to log this, since it's just telling us to fall back to `/decide`
fallback_to_decide = True
except Exception as e:
+102 -6
View File
@@ -1,5 +1,6 @@
import datetime
import hashlib
import logging
import re
from dateutil import parser
@@ -8,6 +9,8 @@ from posthog.utils import convert_to_datetime_aware, is_valid_regex
__LONG_SCALE__ = float(0xFFFFFFFFFFFFFFF)
log = logging.getLogger("posthog")
class InconclusiveMatchError(Exception):
pass
@@ -42,9 +45,10 @@ def variant_lookup_table(feature_flag):
return lookup_table
def match_feature_flag_properties(flag, distinct_id, properties):
def match_feature_flag_properties(flag, distinct_id, properties, cohort_properties=None):
flag_conditions = (flag.get("filters") or {}).get("groups") or []
is_inconclusive = False
cohort_properties = cohort_properties or {}
# Stable sort conditions with variant overrides to the top. This ensures that if overrides are present, they are
# evaluated first, and the variant override is applied to the first matching condition.
@@ -57,7 +61,7 @@ def match_feature_flag_properties(flag, distinct_id, properties):
try:
# if any one condition resolves to True, we can shortcircuit and return
# the matching variant
if is_condition_match(flag, distinct_id, condition, properties):
if is_condition_match(flag, distinct_id, condition, properties, cohort_properties):
variant_override = condition.get("variant")
# Some filters can be explicitly set to null, which require accessing variants like so
flag_variants = ((flag.get("filters") or {}).get("multivariate") or {}).get("variants") or []
@@ -77,12 +81,19 @@ def match_feature_flag_properties(flag, distinct_id, properties):
return False
def is_condition_match(feature_flag, distinct_id, condition, properties):
def is_condition_match(feature_flag, distinct_id, condition, properties, cohort_properties):
rollout_percentage = condition.get("rollout_percentage")
if len(condition.get("properties") or []) > 0:
if not all(match_property(prop, properties) for prop in condition.get("properties")):
return False
elif rollout_percentage is None:
for prop in condition.get("properties"):
property_type = prop.get("type")
if property_type == "cohort":
matches = match_cohort(prop, properties, cohort_properties)
else:
matches = match_property(prop, properties)
if not matches:
return False
if rollout_percentage is None:
return True
if rollout_percentage is not None and _hash(feature_flag["key"], distinct_id) > (rollout_percentage / 100):
@@ -175,3 +186,88 @@ def match_property(property, property_values) -> bool:
raise InconclusiveMatchError("The date provided must be a string or date object")
return False
def match_cohort(property, property_values, cohort_properties) -> bool:
# Cohort properties are in the form of property groups like this:
# {
# "cohort_id": {
# "type": "AND|OR",
# "values": [{
# "key": "property_name", "value": "property_value"
# }]
# }
# }
cohort_id = str(property.get("value"))
if cohort_id not in cohort_properties:
raise InconclusiveMatchError("can't match cohort without a given cohort property value")
property_group = cohort_properties[cohort_id]
return match_property_group(property_group, property_values, cohort_properties)
def match_property_group(property_group, property_values, cohort_properties) -> bool:
if not property_group:
return True
property_group_type = property_group.get("type")
properties = property_group.get("values")
if not properties or len(properties) == 0:
# empty groups are no-ops, always match
return True
error_matching_locally = False
if "values" in properties[0]:
# a nested property group
for prop in properties:
try:
matches = match_property_group(prop, property_values, cohort_properties)
if property_group_type == "AND":
if not matches:
return False
else:
# OR group
if matches:
return True
except InconclusiveMatchError as e:
log.debug(f"Failed to compute property {prop} locally: {e}")
error_matching_locally = True
if error_matching_locally:
raise InconclusiveMatchError("Can't match cohort without a given cohort property value")
# if we get here, all matched in AND case, or none matched in OR case
return property_group_type == "AND"
else:
for prop in properties:
try:
if prop.get("type") == "cohort":
matches = match_cohort(prop, property_values, cohort_properties)
else:
matches = match_property(prop, property_values)
negation = prop.get("negation", False)
if property_group_type == "AND":
# if negated property, do the inverse
if not matches and not negation:
return False
if matches and negation:
return False
else:
# OR group
if matches and not negation:
return True
if not matches and negation:
return True
except InconclusiveMatchError as e:
log.debug(f"Failed to compute property {prop} locally: {e}")
error_matching_locally = True
if error_matching_locally:
raise InconclusiveMatchError("can't match cohort without a given cohort property value")
# if we get here, all matched in AND case, or none matched in OR case
return property_group_type == "AND"
+1 -1
View File
@@ -11,7 +11,7 @@ def get_distinct_id(request):
return None
try:
return GET_DISTINCT_ID(request)
except:
except: # noqa: E722
return None
+2 -3
View File
@@ -1,5 +1,4 @@
from sentry_sdk._types import MYPY
from sentry_sdk.client import Client
from sentry_sdk.hub import Hub
from sentry_sdk.integrations import Integration
from sentry_sdk.scope import add_global_event_processor
@@ -10,9 +9,9 @@ from posthog.request import DEFAULT_HOST
from posthog.sentry import POSTHOG_ID_TAG
if MYPY:
from typing import Any, Dict, Optional
from typing import Optional # noqa: F401
from sentry_sdk._types import Event, Hint
from sentry_sdk._types import Event, Hint # noqa: F401
class PostHogIntegration(Integration):
+62 -4
View File
@@ -1,7 +1,6 @@
import time
import unittest
from datetime import date, datetime
from unittest.mock import MagicMock
from datetime import datetime
from uuid import uuid4
import mock
@@ -28,7 +27,7 @@ class TestClient(unittest.TestCase):
def set_fail(self, e, batch):
"""Mark the failure handler"""
print("FAIL", e, batch)
print("FAIL", e, batch) # noqa: T201
self.failed = True
def setUp(self):
@@ -71,7 +70,6 @@ class TestClient(unittest.TestCase):
self.assertEqual(msg["properties"]["$lib_version"], VERSION)
def test_basic_capture_with_project_api_key(self):
client = Client(project_api_key=FAKE_TEST_API_KEY, on_error=self.set_fail)
success, msg = client.capture("distinct_id", "python test event")
@@ -107,6 +105,40 @@ class TestClient(unittest.TestCase):
self.assertEqual(patch_decide.call_count, 1)
@mock.patch("posthog.client.decide")
def test_get_active_feature_flags(self, patch_decide):
patch_decide.return_value = {
"featureFlags": {"beta-feature": "random-variant", "alpha-feature": True, "off-feature": False}
}
client = Client(FAKE_TEST_API_KEY, on_error=self.set_fail, personal_api_key=FAKE_TEST_API_KEY)
variants = client._get_active_feature_variants("some_id", None, None, None)
self.assertEqual(variants, {"beta-feature": "random-variant", "alpha-feature": True})
@mock.patch("posthog.client.decide")
def test_basic_capture_with_feature_flags_returns_active_only(self, patch_decide):
patch_decide.return_value = {
"featureFlags": {"beta-feature": "random-variant", "alpha-feature": True, "off-feature": False}
}
client = Client(FAKE_TEST_API_KEY, on_error=self.set_fail, personal_api_key=FAKE_TEST_API_KEY)
success, msg = client.capture("distinct_id", "python test event", send_feature_flags=True)
client.flush()
self.assertTrue(success)
self.assertFalse(self.failed)
self.assertEqual(msg["event"], "python test event")
self.assertTrue(isinstance(msg["timestamp"], str))
self.assertIsNone(msg.get("uuid"))
self.assertEqual(msg["distinct_id"], "distinct_id")
self.assertEqual(msg["properties"]["$lib"], "posthog-python")
self.assertEqual(msg["properties"]["$lib_version"], VERSION)
self.assertEqual(msg["properties"]["$feature/beta-feature"], "random-variant")
self.assertEqual(msg["properties"]["$feature/alpha-feature"], True)
self.assertEqual(msg["properties"]["$active_feature_flags"], ["beta-feature", "alpha-feature"])
self.assertEqual(patch_decide.call_count, 1)
@mock.patch("posthog.client.decide")
def test_basic_capture_with_feature_flags_switched_off_doesnt_send_them(self, patch_decide):
patch_decide.return_value = {"featureFlags": {"beta-feature": "random-variant"}}
@@ -436,6 +468,32 @@ class TestClient(unittest.TestCase):
for consumer in client.consumers:
self.assertEqual(consumer.timeout, 15)
def test_disabled(self):
client = Client(FAKE_TEST_API_KEY, on_error=self.set_fail, disabled=True)
success, msg = client.capture("distinct_id", "python test event")
client.flush()
self.assertFalse(success)
self.assertFalse(self.failed)
self.assertEqual(msg, "disabled")
def test_enabled_to_disabled(self):
client = Client(FAKE_TEST_API_KEY, on_error=self.set_fail, disabled=False)
success, msg = client.capture("distinct_id", "python test event")
client.flush()
self.assertTrue(success)
self.assertFalse(self.failed)
self.assertEqual(msg["event"], "python test event")
client.disabled = True
success, msg = client.capture("distinct_id", "python test event")
client.flush()
self.assertFalse(success)
self.assertFalse(self.failed)
self.assertEqual(msg, "disabled")
@mock.patch("posthog.client.Poller")
@mock.patch("posthog.client.get")
def test_call_identify_fails(self, patch_get, patch_poll):
+166 -6
View File
@@ -24,7 +24,7 @@ class TestLocalEvaluation(unittest.TestCase):
def set_fail(self, e, batch):
"""Mark the failure handler"""
print("FAIL", e, batch)
print("FAIL", e, batch) # noqa: T201
self.failed = True
def setUp(self):
@@ -960,6 +960,159 @@ class TestLocalEvaluation(unittest.TestCase):
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_capture.call_count, 0)
@mock.patch("posthog.client.decide")
@mock.patch("posthog.client.get")
def test_feature_flags_local_evaluation_for_cohorts(self, patch_get, patch_decide):
client = Client(FAKE_TEST_API_KEY, personal_api_key=FAKE_TEST_API_KEY)
client.feature_flags = [
{
"id": 2,
"name": "Beta Feature",
"key": "beta-feature",
"is_simple_flag": False,
"active": True,
"filters": {
"groups": [
{
"properties": [
{
"key": "region",
"operator": "exact",
"value": ["USA"],
"type": "person",
},
{"key": "id", "value": 98, "operator": None, "type": "cohort"},
],
"rollout_percentage": 100,
}
],
},
},
]
client.cohorts = {
"98": {
"type": "OR",
"values": [
{"key": "id", "value": 1, "type": "cohort"},
{
"key": "nation",
"operator": "exact",
"value": ["UK"],
"type": "person",
},
],
},
"1": {
"type": "AND",
"values": [{"key": "other", "operator": "exact", "value": ["thing"], "type": "person"}],
},
}
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "UK"}
)
self.assertEqual(feature_flag_match, False)
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_get.call_count, 0)
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "USA", "nation": "UK"}
)
# even though 'other' property is not present, the cohort should still match since it's an OR condition
self.assertEqual(feature_flag_match, True)
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_get.call_count, 0)
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "USA", "other": "thing"}
)
self.assertEqual(feature_flag_match, True)
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_get.call_count, 0)
@mock.patch("posthog.client.decide")
@mock.patch("posthog.client.get")
def test_feature_flags_local_evaluation_for_negated_cohorts(self, patch_get, patch_decide):
client = Client(FAKE_TEST_API_KEY, personal_api_key=FAKE_TEST_API_KEY)
client.feature_flags = [
{
"id": 2,
"name": "Beta Feature",
"key": "beta-feature",
"is_simple_flag": False,
"active": True,
"filters": {
"groups": [
{
"properties": [
{
"key": "region",
"operator": "exact",
"value": ["USA"],
"type": "person",
},
{"key": "id", "value": 98, "operator": None, "type": "cohort"},
],
"rollout_percentage": 100,
}
],
},
},
]
client.cohorts = {
"98": {
"type": "OR",
"values": [
{"key": "id", "value": 1, "type": "cohort"},
{
"key": "nation",
"operator": "exact",
"value": ["UK"],
"type": "person",
},
],
},
"1": {
"type": "AND",
"values": [
{"key": "other", "operator": "exact", "value": ["thing"], "type": "person", "negation": True}
],
},
}
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "UK"}
)
self.assertEqual(feature_flag_match, False)
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_get.call_count, 0)
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "USA", "nation": "UK"}
)
# even though 'other' property is not present, the cohort should still match since it's an OR condition
self.assertEqual(feature_flag_match, True)
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_get.call_count, 0)
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "USA", "other": "thing"}
)
# since 'other' is negated, we return False. Since 'nation' is not present, we can't tell whether the flag should be true or false, so go to decide
self.assertEqual(patch_decide.call_count, 1)
self.assertEqual(patch_get.call_count, 0)
patch_decide.reset_mock()
feature_flag_match = client.get_feature_flag(
"beta-feature", "some-distinct-id", person_properties={"region": "USA", "other": "thing2"}
)
self.assertEqual(feature_flag_match, True)
self.assertEqual(patch_decide.call_count, 0)
self.assertEqual(patch_get.call_count, 0)
@mock.patch("posthog.client.Poller")
@mock.patch("posthog.client.get")
def test_load_feature_flags(self, patch_get, patch_poll):
@@ -981,8 +1134,15 @@ class TestLocalEvaluation(unittest.TestCase):
def test_load_feature_flags_wrong_key(self):
client = Client(FAKE_TEST_API_KEY, personal_api_key=FAKE_TEST_API_KEY)
with freeze_time("2020-01-01T12:01:00.0000Z"):
self.assertRaises(APIError, client.load_feature_flags)
with self.assertLogs("posthog", level="ERROR") as logs:
client.load_feature_flags()
self.assertEqual(
logs.output[0],
"ERROR:posthog:[FEATURE FLAGS] Error loading feature flags: To use feature flags, please set a valid personal_api_key. More information: https://posthog.com/docs/api/overview",
)
client.debug = True
self.assertRaises(APIError, client.load_feature_flags)
@mock.patch("posthog.client.decide")
@mock.patch("posthog.client.get")
@@ -1579,7 +1739,7 @@ class TestMatchProperties(unittest.TestCase):
self.assertFalse(match_property(property_b, {"key": "three"}))
def test_match_properties_regex(self):
property_a = self.property(key="key", value="\.com$", operator="regex")
property_a = self.property(key="key", value="\.com$", operator="regex") # noqa: W605
self.assertTrue(match_property(property_a, {"key": "value.com"}))
self.assertTrue(match_property(property_a, {"key": "value2.com"}))
@@ -1587,7 +1747,7 @@ class TestMatchProperties(unittest.TestCase):
self.assertFalse(match_property(property_a, {"key": "Alakazam"}))
self.assertFalse(match_property(property_a, {"key": 123}))
self.assertFalse(match_property(property_a, {"key": "valuecom"}))
self.assertFalse(match_property(property_a, {"key": "value\com"}))
self.assertFalse(match_property(property_a, {"key": "value\com"})) # noqa: W605
property_b = self.property(key="key", value="3", operator="regex")
self.assertTrue(match_property(property_b, {"key": "3"}))
@@ -1837,7 +1997,7 @@ class TestConsistency(unittest.TestCase):
def set_fail(self, e, batch):
"""Mark the failure handler"""
print("FAIL", e, batch)
print("FAIL", e, batch) # noqa: T201
self.failed = True
def setUp(self):
+17 -16
View File
@@ -1,40 +1,41 @@
import unittest
import posthog
from posthog import Posthog
class TestModule(unittest.TestCase):
posthog = None
def failed(self):
self.failed = True
def setUp(self):
self.failed = False
posthog.api_key = "testsecret"
posthog.on_error = self.failed
self.posthog = Posthog("testsecret", host="http://localhost:8000", on_error=self.failed)
def test_no_api_key(self):
posthog.api_key = None
self.assertRaises(Exception, posthog.capture)
self.posthog.api_key = None
self.assertRaises(Exception, self.posthog.capture)
def test_no_host(self):
posthog.host = None
self.assertRaises(Exception, posthog.capture)
self.posthog.host = None
self.assertRaises(Exception, self.posthog.capture)
def test_track(self):
posthog.capture("distinct_id", "python module event")
posthog.flush()
self.posthog.capture("distinct_id", "python module event")
self.posthog.flush()
def test_identify(self):
posthog.identify("distinct_id", {"email": "user@email.com"})
posthog.flush()
self.posthog.identify("distinct_id", {"email": "user@email.com"})
self.posthog.flush()
def test_alias(self):
posthog.alias("previousId", "distinct_id")
posthog.flush()
self.posthog.alias("previousId", "distinct_id")
self.posthog.flush()
def test_page(self):
posthog.page("distinct_id", "https://posthog.com/contact")
posthog.flush()
self.posthog.page("distinct_id", "https://posthog.com/contact")
self.posthog.flush()
def test_flush(self):
posthog.flush()
self.posthog.flush()
+2 -2
View File
@@ -1,4 +1,4 @@
VERSION = "2.3.0"
VERSION = "2.5.0"
if __name__ == "__main__":
print(VERSION, end="")
print(VERSION, end="") # noqa: T201
+3 -1
View File
@@ -14,12 +14,14 @@ long_description = """
PostHog is developer-friendly, self-hosted product analytics. posthog-python is the python package.
"""
install_requires = ["requests>=2.7,<3.0", "six>=1.5", "monotonic>=1.5", "backoff>=1.10.0,<2.0.0", "python-dateutil>2.1"]
install_requires = ["requests>=2.7,<3.0", "six>=1.5", "monotonic>=1.5", "backoff>=1.10.0", "python-dateutil>2.1"]
extras_require = {
"dev": [
"black",
"isort",
"flake8",
"flake8-print",
"pre-commit",
],
"test": ["mock>=2.0.0", "freezegun==0.3.15", "pylint", "flake8", "coverage", "pytest"],
+1 -1
View File
@@ -14,7 +14,7 @@ long_description = """
PostHog is developer-friendly, self-hosted product analytics. posthog-python is the python package.
"""
install_requires = ["requests>=2.7,<3.0", "six>=1.5", "monotonic>=1.5", "backoff==1.6.0", "python-dateutil>2.1"]
install_requires = ["requests>=2.7,<3.0", "six>=1.5", "monotonic>=1.5", "backoff>=1.10.0", "python-dateutil>2.1"]
tests_require = ["mock>=2.0.0"]