Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/configuration/posthog.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def posthog_error_handler(error, batch):
if not is_production():
posthog_client.disabled = True

# https://github.com/PostHog/posthog-python/issues/353
# without this, a newly-created client will be used for things like catching context exceptions
# Module-level APIs (`posthog.new_context`, `posthog.capture`, …) use this client.
# Without it, contexts fall back to a separately constructed default instance.
posthog.default_client = posthog_client


Expand Down
5 changes: 2 additions & 3 deletions app/routes/dependencies/posthog.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async def inject_posthog_identity(request: Request):
> If two users have the same distinct ID, their data is merged and they are considered one user in PostHog.
"""

with posthog.new_context(capture_exceptions=False):
with posthog.new_context():
# by using clerk_id, we can easily use the same UUID on frontend events
posthog.identify_context(request.state.user.clerk_id)
yield
Expand All @@ -42,8 +42,7 @@ async def inject_posthog_tags(request: Request):
"""

# by default, there is not a context, so we must define one
# `capture_exceptions=False` https://github.com/PostHog/posthog-python/issues/353
with posthog.new_context(capture_exceptions=False):
with posthog.new_context():
# intentionally overwrite any other session or distinct id set previously
# it's up to the user to add dependencies in the correct order
if distinct_id := request.headers.get("X-Posthog-Distinct-Id"):
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/posthog_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import posthog
import pytest

from app.configuration.posthog import posthog_client


def test_default_client_is_the_configured_instance():
assert posthog.default_client is posthog_client
assert posthog_client.enable_exception_autocapture is False


def test_new_context_does_not_capture_exceptions_when_autocapture_is_disabled(mocker):
capture = mocker.patch("posthog.capture_exception")

with pytest.raises(RuntimeError, match="boom"):
with posthog.new_context():

Check failure on line 16 in tests/unit/posthog_test.py

View workflow job for this annotation

GitHub Actions / Backend

ruff (SIM117)

tests/unit/posthog_test.py:15:5: SIM117 Use a single `with` statement with multiple contexts instead of nested `with` statements help: Combine `with` statements
raise RuntimeError("boom")

capture.assert_not_called()
Loading