Skip to content

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

chore(tests): replace freezegun with time-machine (#98019)

Raúl Negrón-Oterof7bc664d1787
diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.md
index 07fea3c611dc..66aac9828fb1 100644
--- a/.agents/skills/fixing-flaky-tests/SKILL.md
+++ b/.agents/skills/fixing-flaky-tests/SKILL.md
@@ -149,14 +149,14 @@ Proceed with a fix grounded in the CI evidence and root-cause analysis, and say
Match the symptom to a cause class; never patch the symptom.
-| Symptom | Likely cause class |
-| ------------------------------------------------------ | ------------------------------------------------------------ |
-| Timeout waiting for promise/listener/element | Unawaited async work, missing mock, hidden pending request |
-| Passes alone, fails with neighbors (or vice versa) | Shared state: module cache, DB rows, global config, ordering |
-| Fails near midnight/UTC boundaries, or on slow runners | Real clock usage — missing `freeze_time` / fake timers |
-| Assertion on list order or generated IDs | Nondeterministic ordering/IDs asserted as deterministic |
-| Query can't see just-written data | Eventual consistency (ClickHouse), missing flush/commit |
-| Only fails under `--maxWorkers=2` / contention | Race condition surfaced by scheduling, too-tight timeout |
+| Symptom | Likely cause class |
+| ------------------------------------------------------ | -------------------------------------------------------------- |
+| Timeout waiting for promise/listener/element | Unawaited async work, missing mock, hidden pending request |
+| Passes alone, fails with neighbors (or vice versa) | Shared state: module cache, DB rows, global config, ordering |
+| Fails near midnight/UTC boundaries, or on slow runners | Real clock usage — missing `time_machine.travel` / fake timers |
+| Assertion on list order or generated IDs | Nondeterministic ordering/IDs asserted as deterministic |
+| Query can't see just-written data | Eventual consistency (ClickHouse), missing flush/commit |
+| Only fails under `--maxWorkers=2` / contention | Race condition surfaced by scheduling, too-tight timeout |
### When the cause isn't obvious, bisect
@@ -192,7 +192,7 @@ PostHog-specific patterns:
### Backend (pytest)
- **DB state leakage**: shared rows across tests without isolation — check fixture scope and whether the test needs `@pytest.mark.django_db(transaction=True)`.
-- **Real time**: use `freeze_time`; never assert on `now()`-derived values.
+- **Real time**: use `time_machine.travel(..., tick=False)`; never assert on `now()`-derived values.
- **ClickHouse eventual consistency**: a query may not see just-inserted data — flush explicitly in the test setup rather than sleeping.
## 5. Decide the outcome — fixing is one of three
diff --git a/.agents/skills/using-redis-token-buckets/SKILL.md b/.agents/skills/using-redis-token-buckets/SKILL.md
index ca4b52259696..e05f05e938d5 100644
--- a/.agents/skills/using-redis-token-buckets/SKILL.md
+++ b/.agents/skills/using-redis-token-buckets/SKILL.md
@@ -68,4 +68,4 @@ The agentic provisioning rate limits (`ee/api/agentic_provisioning/ratelimits.py
## Testing
-Under `settings.TEST`, `posthog.redis.get_client()` returns fakeredis, which executes the Lua scripts (via lupa). Control time with `freeze_time` (the script's clock is passed in from Python), reset between tests with `posthog.redis.TEST_clear_clients()` + `posthog.token_bucket.TEST_reset_scripts()`, and see `posthog/test/test_token_bucket.py` for the pattern.
+Under `settings.TEST`, `posthog.redis.get_client()` returns fakeredis, which executes the Lua scripts (via lupa). Control time with `time_machine.travel(..., tick=False)` (the script's clock is passed in from Python), reset between tests with `posthog.redis.TEST_clear_clients()` + `posthog.token_bucket.TEST_reset_scripts()`, and see `posthog/test/test_token_bucket.py` for the pattern.
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index 7cfdc9930b8d..b88fe94dbe2f 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -164,16 +164,16 @@ Escalating to the next rung is the last resort, not the default.
pending on the next line. Test setup may shorten internal delays without changing
production behavior.
- **No `time.sleep` / arbitrary waits.** A sleep is a flake waiting to happen, and it
- slows every run. Replace it with the matching control above or `freeze_time`.
+ slows every run. Replace it with the matching control above or `time_machine.travel`.
- **An absolute date in a test is a time bomb until you pin the clock.**
A fixture date keeps its meaning only while the real clock stays where you left it.
If anything under test measures that date against `now` — an age, a window, a "recent" flag, an expiry — the assertion holds today and fails some weeks later, on every open branch at once.
Pinning a date into application state is not pinning the clock: a test that sets an "evaluated at" value to a fixed instant, and leaves the wall clock real, still fails when real time drifts past the window, because the code re-reads `now` and the two stop agreeing.
- Pin the process clock to the instant the fixtures speak in — `freeze_time` in Python, `jest.useFakeTimers()` with `jest.setSystemTime()` in Jest, released by `jest.useRealTimers()` in a `finally` — or write the fixture relative to `now` (`now - 2 days`), so the distance is what the test states.
+ Pin the process clock to the instant the fixtures speak in — `time_machine.travel(..., tick=False)` in Python, `jest.useFakeTimers()` with `jest.setSystemTime()` in Jest, released by `jest.useRealTimers()` in a `finally` — or write the fixture relative to `now` (`now - 2 days`), so the distance is what the test states.
Pinning the clock covers only what reads it inside your process; the next rule covers the rest.
- Ask this of every absolute date in a test, not only of an explicit `freeze_time`: _what does this assert when today is a year past it?_ If the answer is not "the same thing", fix it before you commit.
+ Ask this of every absolute date in a test, not only of an explicit frozen clock: _what does this assert when today is a year past it?_ If the answer is not "the same thing", fix it before you commit.
- **A frozen clock doesn't freeze the infrastructure.**
- `freeze_time` patches the clock inside your process; everything outside it still runs on the real one — ClickHouse TTL, Postgres `now()` defaults, S3 lifecycle rules, another service's token-expiry check.
+ `time_machine.travel` patches the clock inside your process; everything outside it still runs on the real one — ClickHouse TTL, Postgres `now()` defaults, S3 lifecycle rules, another service's token-expiry check.
So freezing to an absolute date and then writing rows that something judges by age builds a **time bomb**: green for weeks, then red forever once wall-clock time drifts past the retention window.
It fails on every branch at once, so it reads as though whichever PR is in front of you caused it — and that misattribution, not the fix, is where the time goes.
Most ClickHouse tables are already safe: they build their TTL through `ttl_period()` ([`posthog/clickhouse/kafka_engine.py`](../../../posthog/clickhouse/kafka_engine.py)), which returns `""` under `settings.TEST`, so tests get no TTL at all.
diff --git a/.claude/commands/conventions.md b/.claude/commands/conventions.md
index ad174ed30e7d..c1e7b8c21953 100644
--- a/.claude/commands/conventions.md
+++ b/.claude/commands/conventions.md
@@ -188,7 +188,7 @@ Escalating to the next rung is the last resort, not the default.
- **Use `TestCase`, not `TransactionTestCase`, unless you truly need it.** `TransactionTestCase` flushes the DB between tests instead of rolling back a transaction — dramatically slower, and a common source of cross-test interference. For `transaction.on_commit` side effects use `self.captureOnCommitCallbacks(execute=True)`; reaching ClickHouse is not a reason to switch (`ClickhouseTestMixin` runs on a plain `TestCase`).
- Mock only true boundaries — network, external APIs, the clock, queues. Don't mock your own internal helpers; that's how change-detector tests are born.
- Frontend: prefer a kea logic test (`logic.actions` / `logic.values`) over a full component render whenever the behavior lives in the logic, and don't snapshot large rendered trees — assert specific fields instead.
-- Keep tests deterministic and isolated: no `time.sleep` or arbitrary waits (use `freeze_time` or wait on a real condition), no real network or live external services, and they must pass in any order. Don't leave a `@skip`/`xfail`/`.only` without a one-line reason and a linked issue.
+- Keep tests deterministic and isolated: no `time.sleep` or arbitrary waits (use `time_machine.travel(..., tick=False)` or wait on a real condition), no real network or live external services, and they must pass in any order. Don't leave a `@skip`/`xfail`/`.only` without a one-line reason and a linked issue.
#### Fast developer ("unit") tests
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index bd2194c87d49..5be9a263712b 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -321,7 +321,7 @@ def normalize_pytest_file(file: str) -> str:
"""Keep a pytest JUnit ``file`` attribute only when it stays inside the repo.
pytest reports the decorator's own source file for tests wrapped in ``mock.patch``,
- ``freeze_time``, or ``parameterized``, which arrives as a path into site-packages
+ ``time_machine``, or ``parameterized``, which arrives as a path into site-packages
(``../../../opt/.../unittest/mock.py``). Such a path can never resolve an owner, so it is
discarded here and the caller falls back to inferring the file from the JUnit classname.
"""
diff --git a/.semgrep/rules/security/test-no-datetime-now.py b/.semgrep/rules/security/test-no-datetime-now.py
index 4e23475ab70c..f65c02919d0c 100644
--- a/.semgrep/rules/security/test-no-datetime-now.py
+++ b/.semgrep/rules/security/test-no-datetime-now.py
@@ -8,7 +8,8 @@
import datetime as dt
from datetime import date, datetime
-from freezegun import freeze_time
+import pytest
+import time_machine
from django.utils import (
timezone,
@@ -16,7 +17,7 @@ from django.utils import (
)
# ============================================================
-# Should flag: time-dependent calls in tests without freeze_time
+# Should flag: time-dependent calls in tests without a frozen clock
# ============================================================
@@ -63,33 +64,33 @@ class TestWithoutFreeze:
# ============================================================
-# Should NOT flag: protected by @freeze_time on method
+# Should NOT flag: protected by @time_machine.travel on method
# ============================================================
class TestWithFreezeOnMethod:
- @freeze_time("2024-01-01")
+ @time_machine.travel("2024-01-01", tick=False)
def test_frozen_datetime_now(self):
# ok: test-datetime-now-without-freeze
now = datetime.now()
- @freeze_time("2024-01-01")
+ @time_machine.travel("2024-01-01", tick=False)
def test_frozen_timezone_now(self):
# ok: test-datetime-now-without-freeze
now = timezone.now()
- @freeze_time("2024-01-01")
+ @time_machine.travel("2024-01-01", tick=False)
def test_frozen_dt_datetime_now(self):
# ok: test-datetime-now-without-freeze
now = dt.datetime.now()
# ============================================================
-# Should NOT flag: protected by @freeze_time on class
+# Should NOT flag: protected by @time_machine.travel on class
# ============================================================
-@freeze_time("2024-01-01")
+@time_machine.travel("2024-01-01", tick=False)
class TestWithFreezeOnClass:
def test_class_frozen_datetime_now(self):
# ok: test-datetime-now-without-freeze
@@ -100,7 +101,7 @@ class TestWithFreezeOnClass:
now = timezone.now()
-@freeze_time("2024-01-01")
+@time_machine.travel("2024-01-01", tick=False)
class TestWithFreezeOnClassWithBases:
def test_class_frozen_with_bases(self):
# ok: test-datetime-now-without-freeze
@@ -108,35 +109,70 @@ class TestWithFreezeOnClassWithBases:
# ============================================================
-# Should NOT flag: protected by @freeze_time on stacked decorators
+# Should NOT flag: protected by an autouse fixture that travels
+# ============================================================
+
+
+class TestWithAutouseFixture:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-01-01", tick=False):
+ yield
+
+ def test_fixture_frozen_datetime_now(self):
+ # ok: test-datetime-now-without-freeze
+ now = datetime.now()
+
+ def test_fixture_frozen_date_today(self):
+ # ok: test-datetime-now-without-freeze
+ today = date.today()
+
+
+class ClockMixin:
+ pass
+
+
+class TestWithAutouseFixtureAndBases(ClockMixin):
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-01-01", tick=False):
+ yield
+
+ def test_fixture_frozen_with_bases(self):
+ # ok: test-datetime-now-without-freeze
+ now = datetime.now()
+
+
+# ============================================================
+# Should NOT flag: protected by @time_machine.travel on stacked decorators
# ============================================================
class TestWithStackedDecorators:
- @freeze_time("2024-01-01")
+ @time_machine.travel("2024-01-01", tick=False)
def test_stacked_frozen_datetime_now(self):
# ok: test-datetime-now-without-freeze
now = datetime.now()
# ============================================================
-# Should NOT flag: protected by with freeze_time() context manager
+# Should NOT flag: protected by with time_machine.travel() context manager
# ============================================================
class TestWithFreezeContextManager:
def test_context_manager_datetime_now(self):
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
# ok: test-datetime-now-without-freeze
now = datetime.now()
def test_context_manager_timezone_now(self):
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
# ok: test-datetime-now-without-freeze
now = timezone.now()
def test_context_manager_with_binding(self):
- with freeze_time("2024-01-01") as frozen_time:
+ with time_machine.travel("2024-01-01", tick=False) as frozen_time:
# ok: test-datetime-now-without-freeze
now = datetime.now()
diff --git a/.semgrep/rules/security/test-no-datetime-now.yaml b/.semgrep/rules/security/test-no-datetime-now.yaml
index 4627c1385255..c57bf59c60d6 100644
--- a/.semgrep/rules/security/test-no-datetime-now.yaml
+++ b/.semgrep/rules/security/test-no-datetime-now.yaml
@@ -1,5 +1,5 @@
# Flags datetime.now() and similar time-dependent calls in test methods that lack
-# @freeze_time protection. These cause flaky failures when CI runs near midnight UTC
+# a frozen clock. These cause flaky failures when CI runs near midnight UTC
# because events land in a different day bucket than the assertion expects.
#
# See: https://github.com/PostHog/posthog/pull/48675 for context
@@ -24,27 +24,46 @@ rules:
metavariable: $FUNC
regex: ^test_
- pattern-not-inside: |
- @freeze_time(...)
+ @time_machine.travel(...)
def $F(...):
...
- pattern-not-inside: |
- @freeze_time(...)
+ @time_machine.travel(...)
class $C(...):
...
- pattern-not-inside: |
- @freeze_time(...)
+ @time_machine.travel(...)
class $C:
...
- pattern-not-inside: |
- with freeze_time(...):
+ with time_machine.travel(...):
...
- pattern-not-inside: |
- with freeze_time(...) as $FT:
+ with time_machine.travel(...) as $FT:
+ ...
+ # time_machine.travel only decorates unittest.TestCase subclasses, so a
+ # pytest-style class freezes its clock with an autouse fixture instead.
+ - pattern-not-inside: |
+ class $C(...):
+ @pytest.fixture(autouse=True)
+ def $FIX(...):
+ with time_machine.travel(...):
+ ...
+ ...
+ - pattern-not-inside: |
+ class $C:
+ @pytest.fixture(autouse=True)
+ def $FIX(...):
+ with time_machine.travel(...):
+ ...
...
message: |
- `datetime.now()` (or similar) in a test without `@freeze_time` causes
+ `datetime.now()` (or similar) in a test without a frozen clock causes
flaky failures when CI runs near midnight UTC. Wrap the test method or
- class with `@freeze_time("...")` or use `with freeze_time("..."):`.
+ class with `@time_machine.travel("...", tick=False)`, or use
+ `with time_machine.travel("...", tick=False):`. The class decorator
+ only works on a unittest.TestCase subclass; a pytest-style class needs
+ an autouse fixture that enters the same context manager.
languages: [python]
severity: WARNING
metadata:
diff --git a/conftest.py b/conftest.py
index 43da0f3b3884..0b1d02d1b4d7 100644
--- a/conftest.py
+++ b/conftest.py
@@ -1,8 +1,12 @@
import gc
import warnings
-import importlib
import pytest
+import time_machine
+
+# The default MIXED mode reads naive strings as local time, so a non-UTC machine would
+# freeze at a different instant than CI does.
+time_machine.naive_mode = time_machine.NaiveMode.UTC # ty: ignore[invalid-assignment]
# Test-session boot — plugin imports and importing every collected test module —
# allocates almost exclusively permanent objects, so automatic cyclic GC during that
@@ -204,53 +208,15 @@ def _cache_fixture_parent_nodeids() -> None:
fixtures.FixtureManager._matchfactories = _matchfactories # type: ignore[method-assign]
-def _cheapen_freezegun_module_hash() -> None:
- # Every freeze_time().start() revalidates freezegun's per-module patch cache by
- # hashing each loaded module's attribute list: hash(frozenset(dir(module))) across
- # every module in sys.modules, per freeze. dir() sorts and materializes a list per
- # module, so freeze-heavy suites pay seconds per run for it (2.25M hash calls in a
- # profiled replay-listing run). tuple(module.__dict__) carries the same invalidation
- # signal ~6x cheaper: every module attribute add/delete mutates __dict__ (dir() has
- # no extra visibility for cache purposes — PEP 562 lazy attrs only materialize into
- # __dict__ anyway), and both keys share the same blind spot (rebinding an existing
- # name), so semantics are unchanged. Installed before any freeze so the cache never
- # mixes hash schemes.
- import types # noqa: PLC0415 — deferred until pytest_configure
-
- from freezegun import api # noqa: PLC0415 — deferred until pytest_configure
-
- def _fast_module_attributes_hash(module: types.ModuleType) -> str:
- try:
- keys_hash = hash(tuple(module.__dict__))
- except (ImportError, TypeError, AttributeError):
- keys_hash = 0
- return f"{id(module)}-{keys_hash}"
-
- _fast_module_attributes_hash.__wrapped__ = api._get_module_attributes_hash # type: ignore[attr-defined]
- api._get_module_attributes_hash = _fast_module_attributes_hash # ty: ignore[invalid-assignment]
-
-
-def _warm_urlconf() -> None:
- # The URLconf builds the API router lazily on the first request. Under freeze_time that
- # build fails for any pydantic model whose base was imported before the freeze: the
- # inherited datetime annotation no longer matches the rebound datetime.datetime.
- from django.conf import settings # noqa: PLC0415 — deferred until collection finishes
-
- importlib.import_module(settings.ROOT_URLCONF)
-
-
def pytest_configure(config) -> None:
_cache_reverse_rel_identity()
_cache_select_masks()
_cache_drf_field_info()
_cache_url_resolution()
_cache_fixture_parent_nodeids()
- _cheapen_freezegun_module_hash()
-def pytest_collection_finish(session) -> None:
- if session.items and not session.config.option.collectonly:
- _warm_urlconf()
+def pytest_collection_finish() -> None:
_end_gc_boot_window()
diff --git a/docs/published/handbook/engineering/conventions/backend-coding.md b/docs/published/handbook/engineering/conventions/backend-coding.md
index 7162fb07332e..4ec34546b1ac 100644
--- a/docs/published/handbook/engineering/conventions/backend-coding.md
+++ b/docs/published/handbook/engineering/conventions/backend-coding.md
@@ -119,8 +119,8 @@ Escalating to the next rung is the last resort, not the default.
- **Use `TestCase`, not `TransactionTestCase`, unless you truly need it.** `TransactionTestCase` flushes the DB between tests instead of rolling back a transaction — dramatically slower, and a common source of cross-test interference. For `transaction.on_commit` side effects use `self.captureOnCommitCallbacks(execute=True)`; reaching ClickHouse is not a reason to switch (`ClickhouseTestMixin` runs on a plain `TestCase`).
- Mock only true boundaries — network, external APIs, the clock, queues. Don't mock your own internal helpers; that's how change-detector tests are born.
- Frontend: prefer a kea logic test (`logic.actions` / `logic.values`) over a full component render whenever the behavior lives in the logic, and don't snapshot large rendered trees — assert specific fields instead.
-- Keep tests deterministic and isolated: no `time.sleep` or arbitrary waits (use `freeze_time` or wait on a real condition), no real network or live external services, and they must pass in any order. Don't leave a `@skip`/`xfail`/`.only` without a one-line reason and a linked issue.
-- **An absolute date in a test is a time bomb until you pin the clock.** A fixture date holds its meaning only while the real clock stays where you left it, so a test that measures that date against `now` — an age, a window, a "recent" flag, an expiry — passes today and fails weeks later on every open branch. Pin the process clock to the same instant (`freeze_time`, or `jest.useFakeTimers()` with `jest.setSystemTime()`), or write the fixture relative to `now`. Pinning covers only what reads the clock inside your process: anything outside it, such as a ClickHouse TTL or an S3 lifecycle rule, still runs on the real one.
+- Keep tests deterministic and isolated: no `time.sleep` or arbitrary waits (use `time_machine.travel(..., tick=False)` or wait on a real condition), no real network or live external services, and they must pass in any order. Don't leave a `@skip`/`xfail`/`.only` without a one-line reason and a linked issue.
+- **An absolute date in a test is a time bomb until you pin the clock.** A fixture date holds its meaning only while the real clock stays where you left it, so a test that measures that date against `now` — an age, a window, a "recent" flag, an expiry — passes today and fails weeks later on every open branch. Pin the process clock to the same instant (`time_machine.travel(..., tick=False)`, or `jest.useFakeTimers()` with `jest.setSystemTime()`), or write the fixture relative to `now`. Pinning covers only what reads the clock inside your process: anything outside it, such as a ClickHouse TTL or an S3 lifecycle rule, still runs on the real one.
#### Fast developer ("unit") tests
diff --git a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
index f52aaacd54bb..645e6f5a7d86 100644
--- a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
+++ b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
@@ -1,7 +1,7 @@
from datetime import timedelta
from urllib.parse import urlencode
-from freezegun import freeze_time
+import time_machine
from django.core.cache import cache
from django.utils import timezone
@@ -94,7 +94,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):
assert partner.partner_tier == tier
burst = ACCOUNT_REQUESTS_BURST_BY_TIER[tier]
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
for _ in range(burst):
charge_partner_by_name("account_requests", partner)
@@ -110,7 +110,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):
# to ceil(5 * 3/10) = 2, regardless of the partner's tier.
self.partner_app.update_provisioning_rate_limits(account_requests=3)
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
for _ in range(2):
charge_partner_by_name("account_requests", self.partner_app)
@@ -122,13 +122,13 @@ class TestPartnerRateLimits(ProvisioningTestBase):
def test_zero_override_disables_limiting(self):
self.partner_app.update_provisioning_rate_limits(account_requests=0)
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
for _ in range(100):
charge_partner_by_name("account_requests", self.partner_app)
def test_separate_buckets_per_endpoint(self):
self.partner_app.update_provisioning_rate_limits(account_requests=1, resource_creates=1)
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
charge_partner_by_name("account_requests", self.partner_app)
with self.assertRaises(ProvisioningError):
@@ -140,7 +140,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):
self.partner_app.update_provisioning_rate_limits(account_requests=1)
other_partner.update_provisioning_rate_limits(account_requests=1)
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
charge_partner_by_name("account_requests", self.partner_app)
with self.assertRaises(ProvisioningError):
diff --git a/ee/api/test/test_admin_oauth2_middleware.py b/ee/api/test/test_admin_oauth2_middleware.py
index f7123ae85c31..3287bcd40dc9 100644
--- a/ee/api/test/test_admin_oauth2_middleware.py
+++ b/ee/api/test/test_admin_oauth2_middleware.py
@@ -5,7 +5,7 @@ import secrets
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -99,7 +99,7 @@ class TestGetEmailFromIdToken(BaseTest):
]
)
# Freeze so the token iat and the validation now() share one instant.
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_iat_bounds_checking(self, name, iat_offset, expected_success):
payload = {**self.base_payload, "iat": int(time.time()) + iat_offset}
token = self.jwt_helper.create_id_token(payload)
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index ebbb2375eb12..0b06e5f33a10 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -6,7 +6,7 @@ from typing import Any, cast
from urllib.parse import parse_qs, urlencode, urlparse
import pytest
-from freezegun.api import freeze_time
+import time_machine
from unittest.mock import patch
from django.conf import settings
@@ -712,7 +712,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
# Finish SAML flow (i.e. actual log in)
- @freeze_time("2021-08-25T22:09:14.252Z") # Ensures the SAML timestamp validation passes
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # Ensures the SAML timestamp validation passes
def test_can_login_with_saml(self):
user = User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))
@@ -758,7 +758,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
("url_relay_state", "https://idp.hogflix.io/saml/launch"),
]
)
- @freeze_time("2021-08-25T22:09:14.252Z") # Ensures the SAML timestamp validation passes
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # Ensures the SAML timestamp validation passes
def test_can_login_with_idp_initiated_saml(self, _name: str, relay_state: str | None) -> None:
# IdP-initiated assertions don't carry the OrganizationDomain UUID in RelayState, so we
# route to the tenant via the assertion's <Issuer> instead of rejecting it as "Invalid
@@ -785,7 +785,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
_session = self.client.session
self.assertEqual(_session.get("_auth_user_id"), str(user.pk))
- @freeze_time("2021-08-25T22:09:14.252Z") # Ensures the SAML timestamp validation passes
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # Ensures the SAML timestamp validation passes
def test_saml_login_redirects_to_next_url_from_relay_state(self):
# End-to-end counterpart to test_saml_flow_carries_next_url_in_relay_state: a JSON
# RelayState carrying `next` (as the IdP echoes it back) must land the user on that page
@@ -814,7 +814,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertEqual(response.headers["Location"], "/settings/organization/authentication")
- @freeze_time("2021-08-25T23:37:55.345Z")
+ @time_machine.travel("2021-08-25T23:37:55.345Z", tick=False)
def test_saml_jit_provisioning_and_assertion_with_different_attribute_names(self):
"""
Tests JIT provisioning for creating a user account on the fly.
@@ -866,7 +866,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
_session = self.client.session
self.assertEqual(_session.get("_auth_user_id"), str(user.pk))
- @freeze_time("2021-08-25T23:37:55.345Z")
+ @time_machine.travel("2021-08-25T23:37:55.345Z", tick=False)
def test_saml_jit_provisioning_with_case_insensitive_domain(self):
"""
Tests that JIT provisioning works with case-insensitive domain matching.
@@ -921,7 +921,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
_session = self.client.session
self.assertEqual(_session.get("_auth_user_id"), str(user.pk))
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_login_with_improperly_signed_payload(self):
config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
@@ -978,7 +978,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_signup_with_saml_if_jit_provisioning_is_disabled(self):
self.organization_domain.jit_provisioning_enabled = False
self.organization_domain.save()
@@ -1018,7 +1018,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- @freeze_time("2021-08-25T23:53:51.000Z")
+ @time_machine.travel("2021-08-25T23:53:51.000Z", tick=False)
def test_cannot_create_account_without_first_name_in_payload(self):
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
@@ -1053,7 +1053,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
self.assertEqual(User.objects.count(), user_count)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_login_with_saml_on_unverified_domain(self):
User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))
@@ -1192,7 +1192,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
"Your organization does not have the required license to use SAML.",
)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_saml_login_rejects_email_domain_not_matching_organization_domain(self):
from posthog.models import Organization
@@ -1437,7 +1437,9 @@ class TestSSOEnforcement(APILicensedTest):
except AuthFailed:
self.fail("Google OAuth2 should be allowed when Google OAuth2 is enforced")
- @freeze_time("2021-08-25T22:09:14.252Z") # Same timestamp as other SAML tests using this fixture
+ @time_machine.travel(
+ "2021-08-25T22:09:14.252Z", tick=False
+ ) # Same timestamp as other SAML tests using this fixture
@override_settings(**SAML_MOCK_SETTINGS, **GOOGLE_MOCK_SETTINGS)
def test_saml_auth_flow_blocked_when_google_oauth2_enforced(self):
"""Integration test: Verify SAML auth flow is blocked when Google OAuth2 is enforced"""
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index 02ea3474bd5a..ffec9c5eb97f 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -5,7 +5,7 @@ from typing import Any, cast, get_args
from uuid import uuid4
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_events
from unittest import TestCase
from unittest.mock import MagicMock, PropertyMock, patch
@@ -269,7 +269,7 @@ def create_billing_products_response(**kwargs) -> dict[str, list[CustomerProduct
class TestUnlicensedBillingAPI(APIBaseTest):
@patch("ee.billing.billing_manager.http_session.get")
- @freeze_time("2022-01-01")
+ @time_machine.travel("2022-01-01", tick=False)
def test_billing_calls_the_service_without_token(self, mock_request):
def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
mock = MagicMock()
@@ -319,7 +319,7 @@ class TestBillingAPI(APILicensedTest):
assert res.json()["detail"] == "Billing is not supported for this license type"
@patch("ee.billing.billing_manager.http_session.get")
- @freeze_time("2022-01-01")
+ @time_machine.travel("2022-01-01", tick=False)
def test_billing_calls_the_service_with_appropriate_token(self, mock_request):
def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
mock = MagicMock()
@@ -653,7 +653,7 @@ class TestBillingAPI(APILicensedTest):
"type": "validation_error",
}
- @freeze_time("2022-01-01T12:00:00Z")
+ @time_machine.travel("2022-01-01T12:00:00Z", tick=False)
@patch("ee.billing.billing_manager.http_session.get")
def test_license_is_updated_on_billing_load(self, mock_request):
mock_request.return_value.status_code = 200
@@ -1192,21 +1192,21 @@ class TestBillingUsageRequestSerializer(TestCase):
self.assertEqual(serializer.validated_data["start_date"], "2025-01-01")
self.assertEqual(serializer.validated_data["end_date"], "2025-01-31")
- @freeze_time("2025-02-15")
+ @time_machine.travel("2025-02-15", tick=False)
def test_relative_dates(self):
serializer = BillingUsageRequestSerializer(data={"start_date": "-7d", "end_date": "-1d"})
self.assertTrue(serializer.is_valid(), serializer.errors)
self.assertEqual(serializer.validated_data["start_date"], "2025-02-08")
self.assertEqual(serializer.validated_data["end_date"], "2025-02-14")
- @freeze_time("2025-02-15")
+ @time_machine.travel("2025-02-15", tick=False)
def test_start_date_all_defaults_end_date_to_today(self):
serializer = BillingUsageRequestSerializer(data={"start_date": "all"})
self.assertTrue(serializer.is_valid(), serializer.errors)
self.assertEqual(serializer.validated_data["start_date"], "2020-01-01")
self.assertEqual(serializer.validated_data["end_date"], "2025-02-15")
- @freeze_time("2025-02-15")
+ @time_machine.travel("2025-02-15", tick=False)
def test_start_date_without_end_date_defaults_end_date_to_today(self):
serializer = BillingUsageRequestSerializer(data={"start_date": "2025-01-01"})
self.assertTrue(serializer.is_valid(), serializer.errors)
diff --git a/ee/api/test/test_event_definition.py b/ee/api/test/test_event_definition.py
index 3ca32ed99aed..4568c13343ee 100644
--- a/ee/api/test/test_event_definition.py
+++ b/ee/api/test/test_event_definition.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import Any, Optional, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -23,7 +23,7 @@ from ee.models.event_definition import EnterpriseEventDefinition
from ee.models.license import License, LicenseManager
-@freeze_time("2020-01-02")
+@time_machine.travel("2020-01-02", tick=False)
class TestEventDefinitionEnterpriseAPI(APIBaseTest):
demo_team: Team = None # type: ignore
user: User = None # type: ignore
@@ -542,7 +542,7 @@ class TestEventDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["verified_at"] == "2020-01-02T00:00:00Z"
assert response.json()["updated_at"] == "2020-01-02T00:00:00Z"
- with freeze_time("2020-01-02T00:01:00Z"):
+ with time_machine.travel("2020-01-02T00:01:00Z", tick=False):
self.client.patch(
f"/api/projects/@current/event_definitions/{event.id}",
{"verified": True},
@@ -568,7 +568,7 @@ class TestEventDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["verified_by"] is None
assert response.json()["verified_at"] is None
- with freeze_time("2020-01-02T00:01:00Z"):
+ with time_machine.travel("2020-01-02T00:01:00Z", tick=False):
self.client.patch(
f"/api/projects/@current/event_definitions/{event.id}",
{
diff --git a/ee/api/test/test_insight.py b/ee/api/test/test_insight.py
index 586553bc18c3..ab785afcda60 100644
--- a/ee/api/test/test_insight.py
+++ b/ee/api/test/test_insight.py
@@ -2,7 +2,7 @@ import datetime
from datetime import timedelta
from typing import Optional, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import FuzzyInt, snapshot_postgres_queries
from django.test import override_settings
@@ -46,12 +46,12 @@ class TestInsightEnterpriseAPI(APILicensedTest):
@override_settings(IN_UNIT_TESTING=True)
def test_can_add_and_remove_tags(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
insight_id, response_data = self.dashboard_api.create_insight({"name": "a created dashboard"})
insight_short_id = response_data["short_id"]
self.assertEqual(response_data["tags"], [])
- with freeze_time("2012-01-14T03:21:35.000Z"):
+ with time_machine.travel("2012-01-14T03:21:35.000Z", tick=False):
add_tags_response = self.client.patch(
# tags are displayed in order of insertion
f"/api/projects/{self.team.id}/insights/{insight_id}",
@@ -60,7 +60,7 @@ class TestInsightEnterpriseAPI(APILicensedTest):
self.assertEqual(sorted(add_tags_response.json()["tags"]), ["1", "2", "3"])
- with freeze_time("2012-01-14T03:21:36.000Z"):
+ with time_machine.travel("2012-01-14T03:21:36.000Z", tick=False):
remove_tags_response = self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}", {"tags": ["3"]}
)
@@ -132,11 +132,11 @@ class TestInsightEnterpriseAPI(APILicensedTest):
)
def test_update_insight_can_include_tags_when_licensed(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z") as frozen_time:
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False) as frozen_time:
insight_id, insight = self.dashboard_api.create_insight({"name": "insight name"})
short_id = insight["short_id"]
- frozen_time.tick(delta=timedelta(minutes=10))
+ frozen_time.shift(timedelta(minutes=10))
response = self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}",
diff --git a/ee/api/test/test_license.py b/ee/api/test/test_license.py
index 81f13d57b6b9..550e9b373807 100644
--- a/ee/api/test/test_license.py
+++ b/ee/api/test/test_license.py
@@ -2,7 +2,7 @@ import datetime
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import Mock, patch
from django.utils import timezone
@@ -116,20 +116,20 @@ class TestLicenseAPI(APILicensedTest):
@pytest.mark.skip_on_multitenancy
def test_highest_activated_license_is_used_after_upgrade(self):
- with freeze_time("2022-06-01T12:00:00.000Z"):
+ with time_machine.travel("2022-06-01T12:00:00.000Z", tick=False):
License.objects.create(
key="old",
plan="scale",
valid_until=datetime.datetime.now() + datetime.timedelta(days=30),
)
- with freeze_time("2022-06-03T12:00:00.000Z"):
+ with time_machine.travel("2022-06-03T12:00:00.000Z", tick=False):
License.objects.create(
key="new",
plan="enterprise",
valid_until=datetime.datetime.now() + datetime.timedelta(days=30),
)
- with freeze_time("2022-06-03T13:00:00.000Z"):
+ with time_machine.travel("2022-06-03T13:00:00.000Z", tick=False):
first_valid = License.objects.first_valid()
self.assertIsInstance(first_valid, License)
@@ -137,20 +137,20 @@ class TestLicenseAPI(APILicensedTest):
@pytest.mark.skip_on_multitenancy
def test_highest_activated_license_is_used_after_renewal_to_lower(self):
- with freeze_time("2022-06-01T12:00:00.000Z"):
+ with time_machine.travel("2022-06-01T12:00:00.000Z", tick=False):
License.objects.create(
key="new",
plan="enterprise",
valid_until=datetime.datetime.now() + datetime.timedelta(days=30),
)
- with freeze_time("2022-06-27T12:00:00.000Z"):
+ with time_machine.travel("2022-06-27T12:00:00.000Z", tick=False):
License.objects.create(
key="old",
plan="scale",
valid_until=datetime.datetime.now() + datetime.timedelta(days=30),
)
- with freeze_time("2022-06-27T13:00:00.000Z"):
+ with time_machine.travel("2022-06-27T13:00:00.000Z", tick=False):
first_valid = License.objects.first_valid()
self.assertIsInstance(first_valid, License)
diff --git a/ee/api/test/test_organization.py b/ee/api/test/test_organization.py
index e7febad04ae2..5ab5bfcb139c 100644
--- a/ee/api/test/test_organization.py
+++ b/ee/api/test/test_organization.py
@@ -1,6 +1,6 @@
import datetime as dt
-from freezegun.api import freeze_time
+import time_machine
from unittest import mock
from unittest.mock import ANY, call, patch
@@ -291,7 +291,9 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):
current_plans = License.PLANS
License.PLANS = {"enterprise": ["whatever"]} # type: ignore
- with freeze_time("2070-01-01T12:00:00.000Z"): # LicensedTestMixin enterprise license expires in 2038
+ with time_machine.travel(
+ "2070-01-01T12:00:00.000Z", tick=False
+ ): # LicensedTestMixin enterprise license expires in 2038
sync_all_organization_available_product_features() # This is normally ran every hour
self.organization.refresh_from_db()
self.assertIsNone(self.organization.get_available_feature("whatever"))
diff --git a/ee/api/test/test_property_definition.py b/ee/api/test/test_property_definition.py
index 1e7d971d5b99..218c93637265 100644
--- a/ee/api/test/test_property_definition.py
+++ b/ee/api/test/test_property_definition.py
@@ -2,7 +2,7 @@ import datetime
from typing import Any, Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.db.utils import IntegrityError
@@ -309,7 +309,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
self.assertListEqual(sorted(response.json()["tags"]), ["a", "b"])
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_can_get_property_verification_data(self):
super(LicenseManager, cast(LicenseManager, License.objects)).create(
plan="enterprise", valid_until=datetime.datetime(2500, 1, 19, 3, 14, 7)
@@ -328,7 +328,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
matches = [p["name"] for p in query_list_response.json()["results"] if p["name"] == "enterprise property"]
assert len(matches) == 1
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_verify_then_unverify(self):
super(LicenseManager, cast(LicenseManager, License.objects)).create(
plan="enterprise", valid_until=datetime.datetime(2500, 1, 19, 3, 14, 7)
@@ -366,7 +366,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["verified_by"] is None
assert response.json()["verified_at"] is None
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_hidden_property_behavior(self):
super(LicenseManager, cast(LicenseManager, License.objects)).create(
plan="enterprise", valid_until=datetime.datetime(2500, 1, 19, 3, 14, 7)
@@ -409,7 +409,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["hidden"] is False
assert response.json()["verified"] is False
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_marking_hidden_removes_verified_status(self):
super(LicenseManager, cast(LicenseManager, License.objects)).create(
plan="enterprise", valid_until=datetime.datetime(2500, 1, 19, 3, 14, 7)
@@ -433,7 +433,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
assert property.hidden is True
assert property.verified is False
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_verify_then_verify_again_no_change(self):
super(LicenseManager, cast(LicenseManager, License.objects)).create(
plan="enterprise", valid_until=datetime.datetime(2500, 1, 19, 3, 14, 7)
@@ -446,7 +446,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["verified_by"] is None
assert response.json()["verified_at"] is None
- with freeze_time("2021-08-25T22:09:14.252Z"):
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False):
self.client.patch(
f"/api/projects/@current/property_definitions/{event.id}",
{"verified": True},
@@ -459,7 +459,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["verified_at"] == "2021-08-25T22:09:14.252000Z"
assert response.json()["updated_at"] == "2021-08-25T22:09:14.252000Z"
- with freeze_time("2021-10-26T22:09:14.252Z"):
+ with time_machine.travel("2021-10-26T22:09:14.252Z", tick=False):
self.client.patch(
f"/api/projects/@current/property_definitions/{event.id}",
{"verified": True},
@@ -473,7 +473,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
# updated_at automatically updates on every patch request
assert response.json()["updated_at"] == "2021-10-26T22:09:14.252000Z"
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_update_verified_meta_properties_directly(self):
super(LicenseManager, cast(LicenseManager, License.objects)).create(
plan="enterprise", valid_until=datetime.datetime(2500, 1, 19, 3, 14, 7)
@@ -487,7 +487,7 @@ class TestPropertyDefinitionEnterpriseAPI(APIBaseTest):
assert response.json()["verified_by"] is None
assert response.json()["verified_at"] is None
- with freeze_time("2021-08-25T22:09:14.252Z"):
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False):
self.client.patch(
f"/api/projects/@current/property_definitions/{event.id}",
{
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 4a44a940ed3c..eb1f8e72a86a 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -5,7 +5,7 @@ from typing import Optional
from uuid import uuid4
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import AsyncMock, MagicMock, patch
from django.core.cache import cache
@@ -428,7 +428,7 @@ class TestSubscriptionTemporal(APILicensedTest):
else:
self.mock_temporal_client.start_workflow.assert_not_called()
- @freeze_time("2026-06-15T10:00:00Z") # Monday — weekly (Sat) is 5 days away, daily is 1 day
+ @time_machine.travel("2026-06-15T10:00:00Z", tick=False) # Monday — weekly (Sat) is 5 days away, daily is 1 day
def test_schedule_only_update_still_recomputes_next_delivery_date(self):
# A schedule edit must not fire a delivery but MUST still reschedule — the model
# save() recomputes next_delivery_date; this guards that the no-fire short-circuit
diff --git a/ee/api/test/test_team.py b/ee/api/test/test_team.py
index f4e0f9414b76..c62e6a9bb44b 100644
--- a/ee/api/test/test_team.py
+++ b/ee/api/test/test_team.py
@@ -1,7 +1,7 @@
import uuid
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import FuzzyInt
from unittest.mock import patch
@@ -180,7 +180,7 @@ def team_enterprise_api_test_factory():
self.assertEqual(response.status_code, HTTP_404_NOT_FOUND)
self.assertEqual(self.not_found_response(), response_data)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_team_update_is_in_activity_log(self):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 3a278542e7d6..e5c0c829f535 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -6,7 +6,7 @@ import datetime
from types import SimpleNamespace
from typing import Any, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -942,7 +942,7 @@ class TestBillingManager(BaseTest):
},
}
}
- with freeze_time("2026-08-13"):
+ with time_machine.travel("2026-08-13", tick=False):
BillingManager(license=None).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.has_active_subscription is expected
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 59b01df2d3dc..f5c064ea3c22 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -2,7 +2,7 @@ import datetime
from typing import Any, cast
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, FuzzyInt, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -77,7 +77,7 @@ class TestQuotaLimiting(BaseTest):
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=True)
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
def test_quota_limiting_feature_flag_enabled(self, patch_feature_enabled, patch_capture) -> None:
with self.settings(USE_TZ=False):
self.organization.usage = {
@@ -318,7 +318,7 @@ class TestQuotaLimiting(BaseTest):
assert self.redis_client.zrange(f"@posthog/quota-limits/{resource.value}", 0, -1) == []
assert self.redis_client.zrange(f"@posthog/quota-limiting-suspended/{resource.value}", 0, -1) == []
- with self.settings(USE_TZ=False), freeze_time("2021-01-25T00:00:00Z"):
+ with self.settings(USE_TZ=False), time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.usage = create_usage_summary(
events={"usage": 99, "limit": 100},
)
@@ -421,7 +421,7 @@ class TestQuotaLimiting(BaseTest):
assert_other_resources_not_limited(result.quota_limited_orgs, result.quota_limiting_suspended_orgs)
# Check that limiting still suspended 23 hrs later
- with freeze_time("2021-01-25T23:00:00Z"):
+ with time_machine.travel("2021-01-25T23:00:00Z", tick=False):
result = update_all_orgs_billing_quotas()
assert result.quota_limited_orgs["events"] == {}
@@ -438,7 +438,7 @@ class TestQuotaLimiting(BaseTest):
)
# Check that org is being limited after suspension expired
- with freeze_time("2021-01-27T03:00:00Z"):
+ with time_machine.travel("2021-01-27T03:00:00Z", tick=False):
self.organization.usage = create_usage_summary(
events={"usage": 109, "limit": 100, "quota_limiting_suspended_until": 1611705600},
)
@@ -460,7 +460,7 @@ class TestQuotaLimiting(BaseTest):
]
# Increase trust score. Their quota limiting suspension expiration should not update.
- with freeze_time("2021-01-25T00:00:00Z"):
+ with time_machine.travel("2021-01-25T00:00:00Z", tick=False):
assert self.redis_client.delete(f"@posthog/quota-limits/events")
self.organization.customer_trust_scores = {
@@ -523,7 +523,7 @@ class TestQuotaLimiting(BaseTest):
self.team.api_token.encode("UTF-8")
]
- with freeze_time("2021-01-28T00:00:00Z"):
+ with time_machine.travel("2021-01-28T00:00:00Z", tick=False):
self.redis_client.delete(f"@posthog/quota-limits/events")
# Quota limiting suspension date set in previous billing period, update to new suspension expiration
@@ -827,7 +827,7 @@ class TestQuotaLimiting(BaseTest):
"quota_limited_until": 1612137599,
"quota_limiting_suspended_until": None,
}
- with freeze_time("2021-01-25T00:00:00Z"):
+ with time_machine.travel("2021-01-25T00:00:00Z", tick=False):
# Different trust scores so different grace periods
self.organization.customer_trust_scores = {
QuotaResource.EVENTS.value: 7,
@@ -1006,7 +1006,7 @@ class TestQuotaLimiting(BaseTest):
self.redis_client.delete(billing_key)
def test_update_org_billing_quotas(self):
- with freeze_time("2021-01-01T12:59:59Z"):
+ with time_machine.travel("2021-01-01T12:59:59Z", tick=False):
other_team = create_team(organization=self.organization)
now = timezone.now().timestamp()
@@ -1193,7 +1193,7 @@ class TestQuotaLimiting(BaseTest):
self.assertEqual(call_args[0][1], {"organization_id": self.organization.id})
def test_feature_flags_quota_limiting(self):
- with self.settings(USE_TZ=False), freeze_time("2021-01-25T00:00:00Z"):
+ with self.settings(USE_TZ=False), time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.usage = {
"events": {"usage": 10, "limit": 100},
"exceptions": {"usage": 10, "limit": 100},
@@ -1234,7 +1234,7 @@ class TestQuotaLimiting(BaseTest):
)
# Test suspension expiry leads to limiting after 2 days
- with freeze_time("2021-01-28T00:00:00Z"): # 3 days later
+ with time_machine.travel("2021-01-28T00:00:00Z", tick=False): # 3 days later
result = update_all_orgs_billing_quotas()
assert result.quota_limited_orgs["feature_flag_requests"] == {org_id: 1612137599}
assert result.quota_limiting_suspended_orgs["feature_flag_requests"] == {}
@@ -1243,7 +1243,7 @@ class TestQuotaLimiting(BaseTest):
)
# Test medium-high trust score (10) - should get 3 day suspension
- with freeze_time("2021-01-25T00:00:00Z"):
+ with time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.customer_trust_scores["feature_flag_requests"] = 10
self.organization.usage["feature_flag_requests"] = {"usage": 110, "limit": 100}
self.organization.save()
@@ -1270,7 +1270,7 @@ class TestQuotaLimiting(BaseTest):
def test_feature_flags_always_get_2_day_grace_period(self):
"""Test that feature flags always get at least a 2-day grace period, or their trust score grace period if higher"""
- with self.settings(USE_TZ=False), freeze_time("2021-01-25T00:00:00Z"):
+ with self.settings(USE_TZ=False), time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.usage = {
"events": {"usage": 10, "limit": 100},
"exceptions": {"usage": 10, "limit": 100},
@@ -1314,7 +1314,7 @@ class TestQuotaLimiting(BaseTest):
)
def test_api_queries_quota_limiting(self):
- with self.settings(USE_TZ=False), freeze_time("2021-01-25T00:00:00Z"):
+ with self.settings(USE_TZ=False), time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.usage = {
"events": {"usage": 10, "limit": 100},
"recordings": {"usage": 10, "limit": 100},
@@ -1358,7 +1358,7 @@ class TestQuotaLimiting(BaseTest):
)
# Test suspension expiry leads to limiting
- with freeze_time("2021-01-27T00:00:00Z"): # 2 days later
+ with time_machine.travel("2021-01-27T00:00:00Z", tick=False): # 2 days later
result = update_all_orgs_billing_quotas()
assert result.quota_limited_orgs["api_queries_read_bytes"] == {org_id: 1612137599}
assert result.quota_limiting_suspended_orgs["api_queries_read_bytes"] == {}
@@ -1367,7 +1367,7 @@ class TestQuotaLimiting(BaseTest):
)
# Test medium-high trust score (10) - should get 3 day suspension
- with freeze_time("2021-01-25T00:00:00Z"):
+ with time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.customer_trust_scores[trust_key] = 10
self.organization.usage["api_queries_read_bytes"] = {"usage": 110, "limit": 100}
self.organization.save()
@@ -1383,7 +1383,7 @@ class TestQuotaLimiting(BaseTest):
)
# Test high trust score (15) - should get 5 day suspension
- with freeze_time("2021-01-25T00:00:00Z"):
+ with time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.customer_trust_scores[trust_key] = 15
self.organization.usage["api_queries_read_bytes"] = {"usage": 110, "limit": 100}
self.organization.save()
@@ -1409,7 +1409,7 @@ class TestQuotaLimiting(BaseTest):
def test_ai_credits_quota_limiting(self):
"""Test that AI credits have no grace period and immediately limit regardless of trust score."""
- with self.settings(USE_TZ=False), freeze_time("2021-01-25T00:00:00Z"):
+ with self.settings(USE_TZ=False), time_machine.travel("2021-01-25T00:00:00Z", tick=False):
self.organization.usage = {
"events": {"usage": 10, "limit": 100},
"recordings": {"usage": 10, "limit": 100},
@@ -1491,7 +1491,7 @@ class TestQuotaLimiting(BaseTest):
)
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T00:00:00Z")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
def test_quota_limited_until_but_not_over_limit(self, mock_capture) -> None:
"""Test that when a customer is not over the limit but has quota_limited_until set, the suspension is removed."""
with self.settings(USE_TZ=False):
@@ -1542,7 +1542,7 @@ class TestQuotaLimiting(BaseTest):
assert event[1]["groups"]["organization"] == str(self.organization.id)
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
def test_quota_limiting_surveys(self, mock_capture) -> None:
"""Test that surveys quota limiting works correctly"""
with self.settings(USE_TZ=False):
@@ -1582,7 +1582,7 @@ class TestQuotaLimiting(BaseTest):
assert org_action_call[1]["properties"]["current_usage"] == 105
assert org_action_call[1]["properties"]["event"] == "suspended"
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
def test_quota_limiting_surveys_under_limit(self) -> None:
"""Test that surveys under quota limit are not restricted"""
with self.settings(USE_TZ=False):
@@ -1606,7 +1606,7 @@ class TestQuotaLimiting(BaseTest):
self.organization.refresh_from_db()
assert self.organization.usage["survey_responses"].get("quota_limited_until") is None
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
@patch("posthoganalytics.capture")
def test_quota_limiting_ai_events(self, mock_capture) -> None:
"""Test that AI events are properly limited when quota exceeded"""
@@ -1646,7 +1646,7 @@ class TestQuotaLimiting(BaseTest):
assert org_action_call[1]["properties"]["current_usage"] == 105
assert org_action_call[1]["properties"]["event"] == "suspended"
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
def test_quota_limiting_ai_events_under_limit(self) -> None:
"""Test that AI events under quota limit are not restricted"""
with self.settings(USE_TZ=False):
@@ -1670,7 +1670,7 @@ class TestQuotaLimiting(BaseTest):
self.organization.refresh_from_db()
assert self.organization.usage["llm_events"].get("quota_limited_until") is None
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
def test_ai_events_trust_score_tracking(self) -> None:
"""Test trust score updates for AI event limiting"""
with self.settings(USE_TZ=False):
@@ -1725,7 +1725,7 @@ class TestQuotaLimiting(BaseTest):
)
assert self.team.api_token in suspended_tokens
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
def test_ai_events_quota_with_overage_buffer(self) -> None:
"""Test overage buffer behavior for AI events"""
with self.settings(USE_TZ=False):
@@ -1756,7 +1756,7 @@ class TestQuotaLimiting(BaseTest):
)
assert self.team.api_token not in limited_tokens
- @freeze_time("2021-01-25T23:59:59Z")
+ @time_machine.travel("2021-01-25T23:59:59Z", tick=False)
@patch("posthoganalytics.capture")
def test_ai_events_quota_suspension_and_resume(self, mock_capture) -> None:
"""Test suspension and resume mechanics for AI quotas"""
@@ -1834,7 +1834,7 @@ class TestQuotaLimiting(BaseTest):
assert not extra_in_counters, f"UsageCounters has extra keys not in OrganizationUsageInfo: {extra_in_counters}"
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T12:00:00Z")
+ @time_machine.travel("2021-01-25T12:00:00Z", tick=False)
def test_update_all_orgs_billing_quotas_refreshes_candidate_orgs_before_decision(self, patch_capture) -> None:
"""
End-to-end: an over-limit-looking org is identified as a refresh candidate, so a
@@ -1920,7 +1920,7 @@ class TestQuotaLimiting(BaseTest):
], "Fresh `period` from the webhook must survive the targeted patch."
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T12:00:00Z")
+ @time_machine.travel("2021-01-25T12:00:00Z", tick=False)
def test_update_all_orgs_billing_quotas_targeted_patch_preserves_concurrent_billing_writes(
self, patch_capture
) -> None:
@@ -1993,7 +1993,7 @@ class TestQuotaLimiting(BaseTest):
)
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T12:00:00Z")
+ @time_machine.travel("2021-01-25T12:00:00Z", tick=False)
def test_candidate_refresh_changes_quota_decision(self, patch_capture) -> None:
"""
End-to-end: the per-iteration refresh must actually change the decision when
@@ -2053,7 +2053,7 @@ class TestQuotaLimiting(BaseTest):
assert self.redis_client.zrange("@posthog/quota-limits/events", 0, -1) == []
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T12:00:00Z")
+ @time_machine.travel("2021-01-25T12:00:00Z", tick=False)
def test_limit_decrease_for_non_candidate_uses_stale_snapshot(self, patch_capture) -> None:
"""
Documents the residual race window the targeted refresh does NOT close: a
@@ -2157,7 +2157,7 @@ class TestQuotaLimiting(BaseTest):
),
]
)
- @freeze_time("2021-01-25T00:00:00Z")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
@patch("posthog.tasks.remote_config.update_team_remote_config")
def test_update_org_billing_quotas_recordings_remote_config_dispatch(
self,
@@ -2192,7 +2192,7 @@ class TestQuotaLimiting(BaseTest):
countdown=35,
)
- @freeze_time("2021-01-25T00:00:00Z")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
@patch("posthog.tasks.remote_config.update_team_remote_config")
def test_update_org_billing_quotas_no_teams_no_dispatch(self, mock_update_remote_config) -> None:
"""An org with no teams (or only teams with empty api_tokens) takes the observe-only
@@ -2221,7 +2221,7 @@ class TestQuotaLimiting(BaseTest):
)
@patch("posthog.tasks.remote_config.update_team_remote_config")
@patch("posthoganalytics.capture")
- @freeze_time("2021-01-25T00:00:00Z")
+ @time_machine.travel("2021-01-25T00:00:00Z", tick=False)
def test_update_all_orgs_billing_quotas_recordings_remote_config_dispatch(
self,
_name,
@@ -2935,7 +2935,7 @@ class TestSignalsRefundQuotaOffset(BaseTest):
)
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=False)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_credited_refund_offsets_quota_decision(
self, _name, pr_run_created_at, expect_limited, _feature_enabled, _capture
) -> None:
@@ -2959,7 +2959,7 @@ class TestSignalsRefundQuotaOffset(BaseTest):
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=False)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_refund_lookup_skipped_when_under_limit(self, _feature_enabled, _capture) -> None:
# The offset query must not run once per org in the all-orgs cron — only for orgs that
# would otherwise be limited.
@@ -2971,7 +2971,7 @@ class TestSignalsRefundQuotaOffset(BaseTest):
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=False)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_offset_ignores_other_resources(self, _feature_enabled, _capture) -> None:
# An over-limit events org must never trigger the signals refund lookup.
self.organization.usage = {
@@ -2996,7 +2996,7 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=False)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_refresh_patches_todays_usage_and_flips_the_limiter(self, _feature_enabled, _capture) -> None:
# The event-driven path exists because the cron-patched todays_usage predates the PR that
# just landed: a stale value here means the flag doesn't flip until the next cron tick.
@@ -3017,7 +3017,7 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=False)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_stale_concurrent_refresh_cannot_lower_usage_or_unpause(self, _feature_enabled, _capture) -> None:
# Two refreshes can overlap when two PRs land close together; the one that counted usage
# before the newer PR can finish last. Its stale, lower count must not overwrite the
@@ -3040,7 +3040,7 @@ class TestRefreshOrgSelfDrivingQuota(BaseTest):
@patch("posthoganalytics.capture")
@patch("posthoganalytics.feature_enabled", return_value=False)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_quota_cron_recounts_live_instead_of_writing_its_stale_snapshot(self, _feature_enabled, _capture) -> None:
# The cron snapshots fleet usage before its org loop, so a push-refresh that fires while
# the loop runs (a PR landing) writes a fresher, higher todays_usage than the snapshot.
diff --git a/ee/billing/test/test_salesforce_enrichment.py b/ee/billing/test/test_salesforce_enrichment.py
index 9b7cebeaa0b4..c49edf781f57 100644
--- a/ee/billing/test/test_salesforce_enrichment.py
+++ b/ee/billing/test/test_salesforce_enrichment.py
@@ -4,7 +4,7 @@ from contextlib import contextmanager
from pathlib import Path
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, patch
@@ -145,7 +145,7 @@ class TestYCCompanyDetection(BaseTest):
class TestHarmonicDataTransformation(BaseTest):
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_with_fixture(self):
"""Test transform_harmonic_data output structure and field mapping with real fixture."""
harmonic_response = load_harmonic_fixture()
@@ -208,7 +208,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert isinstance(tags_v2, list)
assert len(tags_v2) == 3
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_data_with_fixture(self):
"""Test complete pipeline: fixture → transform → Salesforce field mapping."""
# Load and transform fixture data
@@ -264,7 +264,7 @@ class TestHarmonicDataTransformation(BaseTest):
for key, value in salesforce_data.items():
assert value is not None, f"Field {key} should not be None"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_missing_funding(self):
"""Test transform_harmonic_data handles missing funding section."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -276,7 +276,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result["funding"] == {}
assert result["company_info"]["name"] == "Example Corp" # Other data preserved
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_missing_company_fields(self):
"""Test transform_harmonic_data handles missing company info fields."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -293,7 +293,7 @@ class TestHarmonicDataTransformation(BaseTest):
# Other fields should still work
assert result["company_info"]["website"] == "https://example.com"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_malformed_website(self):
"""Test transform_harmonic_data handles malformed website data."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -304,7 +304,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result is not None
assert result["company_info"]["website"] is None # Safely handles type mismatch
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_malformed_founding_date(self):
"""Test transform_harmonic_data handles malformed founding date."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -315,7 +315,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result is not None
assert result["company_info"]["founding_date"] is None # Safely handles type mismatch
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_missing_traction_metrics(self):
"""Test transform_harmonic_data handles missing tractionMetrics."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -328,7 +328,7 @@ class TestHarmonicDataTransformation(BaseTest):
# Other sections should still work
assert result["company_info"]["name"] == "Example Corp"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_metric_missing_latest_value(self):
"""Test transform_harmonic_data handles metrics without latestMetricValue."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -343,7 +343,7 @@ class TestHarmonicDataTransformation(BaseTest):
# Other metrics should still be present
assert "webTraffic" in result["metrics"]
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_metric_with_null_latest_value(self):
"""Test transform_harmonic_data handles metrics with null latestMetricValue."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -357,7 +357,7 @@ class TestHarmonicDataTransformation(BaseTest):
# Other metrics should still be present
assert "webTraffic" in result["metrics"]
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_empty_historical_metrics(self):
"""Test transform_harmonic_data handles empty historical data."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -370,7 +370,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result["metrics"]["headcount"]["current_value"] == 5015
assert result["metrics"]["headcount"]["historical"] == {}
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_missing_tags(self):
"""Test transform_harmonic_data handles missing tags."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -383,7 +383,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result["tags"] == []
assert result["tagsV2"] == []
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_no_primary_tag_uses_first(self):
"""Test Salesforce update falls back to first tag when there's no primary tag."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -399,7 +399,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert salesforce_data is not None
assert salesforce_data["harmonic_industry__c"] == "Enterprise Software"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_empty_tags(self):
"""Test Salesforce update when both tags and tagsV2 arrays are empty."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -414,7 +414,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert salesforce_data is not None
assert "harmonic_industry__c" not in salesforce_data
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_with_primary_tag(self):
"""Test Salesforce update correctly extracts primary tag."""
harmonic_data = load_harmonic_fixture()
@@ -426,7 +426,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert salesforce_data is not None
assert salesforce_data["harmonic_industry__c"] == "Enterprise Software"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_fallback_to_tagsv2_market_vertical(self):
"""Test Salesforce update falls back to tagsV2 MARKET_VERTICAL when tags is empty."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -440,7 +440,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert salesforce_data is not None
assert salesforce_data["harmonic_industry__c"] == "Business Intelligence"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_fallback_to_tagsv2_first_tag(self):
"""Test Salesforce update falls back to first tagsV2 tag when no MARKET_VERTICAL."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -459,7 +459,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert salesforce_data is not None
assert salesforce_data["harmonic_industry__c"] == "Software"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_skips_empty_displayvalue(self):
"""Test Salesforce update skips tags with empty displayValue."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -476,7 +476,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert salesforce_data is not None
assert salesforce_data["harmonic_industry__c"] == "Fallback"
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_includes_is_yc_company_field(self):
"""Test transform_harmonic_data includes is_yc_company field."""
harmonic_data = load_harmonic_fixture()
@@ -489,7 +489,7 @@ class TestHarmonicDataTransformation(BaseTest):
# The fixture has investors but not YC, so this should be False
assert result["is_yc_company"] is False
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_includes_is_yc_company_with_yc_investor(self):
"""Test transform_harmonic_data sets is_yc_company=True when YC is an investor."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -504,7 +504,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result is not None
assert result["is_yc_company"] is True
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_is_yc_company_false_missing_funding(self):
"""Test transform_harmonic_data sets is_yc_company=False when no funding section."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -515,7 +515,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert result is not None
assert result["is_yc_company"] is False
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_includes_yc_company_flag(self):
"""Test Salesforce update includes harmonic_is_yc_company__c field."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -529,7 +529,7 @@ class TestHarmonicDataTransformation(BaseTest):
assert "harmonic_is_yc_company__c" in salesforce_data
assert salesforce_data["harmonic_is_yc_company__c"] is True
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_prepare_salesforce_update_yc_company_false(self):
"""Test Salesforce update includes harmonic_is_yc_company__c=False when not YC funded."""
harmonic_data = copy.deepcopy(load_harmonic_fixture())
@@ -631,7 +631,7 @@ class TestSalesforceAccountQuery(BaseTest):
class TestSpecificDomainEnrichment(BaseTest):
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_enrichment_success(self):
"""Test enriching a specific domain returns Harmonic data and updates Salesforce."""
harmonic_response = load_harmonic_fixture()
@@ -680,7 +680,7 @@ class TestSpecificDomainEnrichment(BaseTest):
assert len(update_records) == 2
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_enrichment_with_full_url(self):
"""Test enriching a specific domain from a full URL."""
harmonic_response = load_harmonic_fixture()
@@ -715,7 +715,7 @@ class TestSpecificDomainEnrichment(BaseTest):
assert "excluded" in result["error"]
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_enrichment_no_harmonic_data(self):
"""Test handling when Harmonic returns no data for domain."""
mock_accounts = [
@@ -738,7 +738,7 @@ class TestSpecificDomainEnrichment(BaseTest):
assert "No Harmonic data found" in result["error"]
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_no_salesforce_accounts(self):
"""Test handling when no Salesforce accounts match the domain."""
with patch("ee.billing.salesforce_enrichment.enrichment.get_salesforce_accounts_by_domain", return_value=[]):
@@ -752,7 +752,7 @@ class TestSpecificDomainEnrichment(BaseTest):
assert "No Salesforce accounts found" in result["error"]
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_calls_salesforce_and_updates(self):
"""Test that specific_domain queries Salesforce and updates matching accounts."""
harmonic_response = load_harmonic_fixture()
@@ -783,7 +783,7 @@ class TestSpecificDomainEnrichment(BaseTest):
assert result["summary"]["salesforce_update_succeeded"] is True
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_multiple_accounts_all_updated(self):
"""Test that when multiple Salesforce accounts match a domain, all are updated."""
harmonic_response = load_harmonic_fixture()
@@ -833,7 +833,7 @@ class TestSpecificDomainEnrichment(BaseTest):
assert updated_ids == {"001ACCOUNT1", "001ACCOUNT2", "001ACCOUNT3"}
@pytest.mark.asyncio
- @freeze_time("2025-07-29T12:00:00Z")
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
async def test_specific_domain_enrichment_returns_updated_account_data(self):
"""Test that updated_salesforce_accounts contains the refreshed SF data after update."""
harmonic_response = load_harmonic_fixture()
diff --git a/ee/clickhouse/materialized_columns/test/test_columns.py b/ee/clickhouse/materialized_columns/test/test_columns.py
index 15e2735a22de..cdf45cb6dd07 100644
--- a/ee/clickhouse/materialized_columns/test/test_columns.py
+++ b/ee/clickhouse/materialized_columns/test/test_columns.py
@@ -4,7 +4,7 @@ from datetime import timedelta
from time import sleep
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, get_index_from_explain
from unittest import TestCase
from unittest.mock import patch
@@ -111,7 +111,7 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):
def test_caching_and_materializing(self):
base_time = datetime.datetime.fromisoformat("2020-01-04T13:01:01Z")
- with freeze_time(base_time):
+ with time_machine.travel(base_time, tick=False):
materialize("events", "$foo", create_minmax_index=True)
materialize("events", "$bar", create_minmax_index=True)
materialize("person", "$zeta", create_minmax_index=True)
@@ -146,7 +146,7 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):
]
) == sorted(["$foo", "$bar", "abc", *EVENTS_TABLE_DEFAULT_MATERIALIZED_COLUMNS])
- with freeze_time(base_time + timedelta(minutes=59)):
+ with time_machine.travel(base_time + timedelta(minutes=59), tick=False):
check_cache_updated()
@patch("secrets.choice", return_value="X")
@@ -219,7 +219,7 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):
assert self._count_materialized_rows("mat_prop") == 0
assert self._count_materialized_rows("mat_another") == 0
- with freeze_time("2021-05-10T14:00:01Z"):
+ with time_machine.travel("2021-05-10T14:00:01Z", tick=False):
backfill_materialized_columns(
"events",
columns,
diff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.py
index 46b1e4932305..2c77e2d82351 100644
--- a/ee/clickhouse/models/test/test_cohort.py
+++ b/ee/clickhouse/models/test/test_cohort.py
@@ -3,7 +3,7 @@ import uuid
from datetime import datetime, timedelta
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
BaseTest,
ClickhouseTestMixin,
@@ -370,7 +370,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
self.calculate_cohort_hogql_test_harness(cohort1, 0)
def test_cohortpeople_prop_changed(self):
- with freeze_time((datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")):
+ with time_machine.travel((datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d"), tick=False):
p1 = create_person(
team_id=self.team.pk,
distinct_ids=["1"],
@@ -405,7 +405,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
self.calculate_cohort_hogql_test_harness(cohort1, 0)
- with freeze_time((datetime.now() - timedelta(days=2)).strftime("%Y-%m-%d")):
+ with time_machine.travel((datetime.now() - timedelta(days=2)).strftime("%Y-%m-%d"), tick=False):
p2.version = 1
p2.properties = {"$some_prop": "another", "$another_prop": "another"}
update_person(p2)
diff --git a/ee/clickhouse/queries/test/test_cohort_query.py b/ee/clickhouse/queries/test/test_cohort_query.py
index 25d1eaa0ec70..7a6afb574cbf 100644
--- a/ee/clickhouse/queries/test/test_cohort_query.py
+++ b/ee/clickhouse/queries/test/test_cohort_query.py
@@ -3,7 +3,7 @@ from typing import Any
import pytest
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
BaseTest,
ClickhouseTestMixin,
@@ -322,7 +322,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
assert [p1.uuid] == [r[0] for r in res]
def test_performed_event_with_event_filters_and_explicit_date(self):
- with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), tick=False):
p1 = _create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
@@ -388,7 +388,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
def test_performed_event_with_explicit_date_range(self):
"""Upper bound (`explicit_datetime_to`) is inclusive of the full to-date in both engines."""
- with freeze_time(datetime.now().replace(hour=12, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(datetime.now().replace(hour=12, minute=0, second=0, microsecond=0), tick=False):
# p1 is inside the window: [-14d, -7d inclusive]
p1 = _create_person(
team_id=self.team.pk,
@@ -1010,7 +1010,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
def test_performed_event_first_time_with_explicit_date_range(self):
"""First occurrence (not just any occurrence) must fall inside the explicit window."""
- with freeze_time(datetime.now().replace(hour=12, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(datetime.now().replace(hour=12, minute=0, second=0, microsecond=0), tick=False):
# p1's first event is inside the window [-14d, -7d inclusive]
p1 = _create_person(
team_id=self.team.pk,
@@ -1166,7 +1166,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
)
def test_performed_event_regularly_not_in_total(self):
now = datetime.now()
- with freeze_time(now.replace(hour=0, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(now.replace(hour=0, minute=0, second=0, microsecond=0), tick=False):
p1 = _create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
@@ -1221,7 +1221,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
def test_performed_event_regularly_with_variable_event_counts_in_each_period(self):
# Pin to midnight so events at now-12h stay on yesterday: the cohort date range ends
# at "-1d", so when CI runs after noon UTC those events land on today and get excluded
- with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), tick=False):
self._assert_performed_event_regularly_with_variable_event_counts()
def _assert_performed_event_regularly_with_variable_event_counts(self):
@@ -2629,7 +2629,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
assert [p1.uuid] == [r[0] for r in res]
def test_performed_event_sequence_with_person_properties(self):
- with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), tick=False):
p1 = _create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
@@ -2822,7 +2822,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
assert [p1.uuid] == [r[0] for r in res]
def test_performed_event_sequence_and_clause_with_additional_event(self):
- with freeze_time(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)):
+ with time_machine.travel(datetime.now().replace(hour=0, minute=0, second=0, microsecond=0), tick=False):
p1 = _create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
diff --git a/ee/clickhouse/queries/test/test_related_actors_query.py b/ee/clickhouse/queries/test/test_related_actors_query.py
index f4c777f5becc..5f1e018fdb49 100644
--- a/ee/clickhouse/queries/test/test_related_actors_query.py
+++ b/ee/clickhouse/queries/test/test_related_actors_query.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from typing import cast
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -91,7 +91,7 @@ class BaseRelatedActorsTest(ABC, ClickhouseTestMixin, APIBaseTest):
raise NotImplementedError()
-@freeze_time("2025-03-01T12:00:00Z")
+@time_machine.travel("2025-03-01T12:00:00Z", tick=False)
class TestRelatedPersonsQuery(BaseRelatedActorsTest):
def run_query(self) -> list:
return RelatedActorsQuery(team=self.team, group_type_index=0, id="org:1").run()
@@ -144,7 +144,7 @@ class TestRelatedPersonsQuery(BaseRelatedActorsTest):
assert len(ids) == 1
-@freeze_time("2025-03-01T12:00:00Z")
+@time_machine.travel("2025-03-01T12:00:00Z", tick=False)
class TestRelatedGroupsQuery(BaseRelatedActorsTest):
def run_query(self) -> list:
return RelatedActorsQuery(team=self.team, group_type_index=None, id=str(self.person.uuid)).run()
diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.py
index 8665e956e851..03667ed909c4 100644
--- a/ee/clickhouse/views/test/test_clickhouse_groups.py
+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py
@@ -4,7 +4,7 @@ from typing import Any, cast
from uuid import UUID
import pytest
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, snapshot_clickhouse_queries
from unittest import mock
from unittest.mock import patch
@@ -52,16 +52,16 @@ def typed_group_type_index(value: int) -> GroupTypeIndex:
class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
maxDiff = None
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_groups_list(self):
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(
team_id=self.team.pk,
group_type_index=0,
group_key="org:5",
properties={"industry": "finance", "name": "Mr. Krabs"},
)
- with freeze_time("2021-05-02"):
+ with time_machine.travel("2021-05-02", tick=False):
create_group(
team_id=self.team.pk,
group_type_index=0,
@@ -140,7 +140,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
},
)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_groups_list_no_group_type(self):
response_data = self.client.get(f"/api/projects/{self.team.id}/groups/").json()
self.assertEqual(
@@ -185,7 +185,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/groups/find?group_type_index=0")
self.assertEqual(response.status_code, 400)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch(f"{PATH}.feature_enabled_or_false", return_value=False)
def test_retrieve_group_crm_disabled(self, _):
index: GroupTypeIndex = 0
@@ -213,7 +213,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(ResourceNotebook.objects.filter(group=group.id).exists())
self.assertEqual(0, Notebook.objects.filter(team=self.team).count())
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch(f"{PATH}.feature_enabled_or_false", return_value=True)
def test_retrieve_group_crm_enabled(self, _):
index: GroupTypeIndex = 0
@@ -252,7 +252,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(notebook.content[0]["content"][0]["text"], "Mr. Krabs Notes")
self.assertEqual(notebook.content[1]["type"], "text")
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch(f"{PATH}.feature_enabled_or_false", return_value=True)
def test_find_with_skip_create_notebook_does_not_create_notebook(self, _):
index: GroupTypeIndex = 0
@@ -273,7 +273,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(ResourceNotebook.objects.filter(group=group.id).exists())
self.assertEqual(0, Notebook.objects.filter(team=self.team).count())
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_retrieve_group_with_notebook(self):
index: GroupTypeIndex = 0
key = "key"
@@ -300,7 +300,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
},
)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch("products.notebooks.backend.logic.ResourceNotebook.objects.create", side_effect=IntegrityError)
@patch(f"{PATH}.feature_enabled_or_false", return_value=True)
def test_retrieve_group_notebook_transaction_rollback(self, _, mock_relationship_create):
@@ -334,7 +334,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(message["team_id"], self.team.pk)
self.assertEqual(message["event"], "Group notebook creation failed")
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@mock.patch("ee.clickhouse.views.groups.capture_internal")
def test_create_group_missing_group_properties(self, mock_capture):
group_type_mapping = create_group_type_mapping_without_created_at(
@@ -366,7 +366,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_called_once()
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@mock.patch("ee.clickhouse.views.groups.capture_internal")
@pytest.mark.flaky(reruns=2)
def test_create_group(self, mock_capture):
@@ -581,7 +581,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
mock_capture.assert_not_called()
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@mock.patch("ee.clickhouse.views.groups.capture_internal")
@pytest.mark.flaky(reruns=2)
def test_group_property_crud_add_success(self, mock_capture):
@@ -666,7 +666,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["before"], None)
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], "technology")
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@mock.patch("ee.clickhouse.views.groups.capture_internal")
@pytest.mark.flaky(reruns=2)
def test_group_property_crud_update_success(self, mock_capture):
@@ -748,7 +748,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["before"], "finance")
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], "technology")
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_group_property_crud_update_missing_key(self):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -769,7 +769,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_group_property_crud_update_invalid_group_key(self):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -790,7 +790,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 404)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@mock.patch("ee.clickhouse.views.groups.capture_internal")
@pytest.mark.flaky(reruns=2)
def test_group_property_crud_delete_success(self, mock_capture):
@@ -869,7 +869,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["before"], "finance")
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["after"], None)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_group_property_crud_delete_missing_key(self):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -890,7 +890,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_group_property_crud_delete_invalid_group_key(self):
group_type_mapping = create_group_type_mapping_without_created_at(
team=self.team,
@@ -925,7 +925,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch("ee.clickhouse.views.groups.capture_internal")
def test_delete_property_nonexistent_property(self, mock_capture):
mock_capture.return_value = mock.MagicMock(status_code=200)
@@ -948,7 +948,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_delete_property_non_string_unset(self):
create_group_type_mapping_without_created_at(
team=self.team,
@@ -970,7 +970,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, 400)
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch("ee.clickhouse.views.groups.capture_internal")
def test_get_group_activities_success(self, mock_capture):
# Mock the response to return a 200 OK
@@ -1010,7 +1010,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["type"], "Group")
self.assertEqual(response.json()["results"][0]["detail"]["changes"][0]["action"], "changed")
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch("ee.clickhouse.views.groups.capture_internal")
def test_get_group_activities_invalid_group(self, mock_capture):
# Mock the response to return a 200 OK
@@ -1043,7 +1043,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, 404)
- @freeze_time("2021-05-10")
+ @time_machine.travel("2021-05-10", tick=False)
@snapshot_clickhouse_queries
def test_related_groups(self):
self._create_related_groups_data()
@@ -1090,7 +1090,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):
],
)
- @freeze_time("2021-05-10")
+ @time_machine.travel("2021-05-10", tick=False)
@snapshot_clickhouse_queries
def test_related_groups_person(self):
uuid = self._create_related_groups_data()
@@ -2380,11 +2380,11 @@ class GroupPropertyDefinitionsTestCase(ClickhouseTestMixin, APIBaseTest):
class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_returns_groups_ordered_by_created_at_desc(self):
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})
- with freeze_time("2021-05-02"):
+ with time_machine.travel("2021-05-02", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={})
result = list_groups(team_id=self.team.pk, group_type_index=0)
@@ -2394,13 +2394,13 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert result.groups[1].group_key == "org:1"
assert result.has_more is False
- @freeze_time("2021-05-04")
+ @time_machine.travel("2021-05-04", tick=False)
def test_pagination_with_limit(self):
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})
- with freeze_time("2021-05-02"):
+ with time_machine.travel("2021-05-02", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={})
- with freeze_time("2021-05-03"):
+ with time_machine.travel("2021-05-03", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:3", properties={})
result = list_groups(team_id=self.team.pk, group_type_index=0, limit=2)
@@ -2410,13 +2410,13 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert result.groups[1].group_key == "org:2"
assert result.has_more is True
- @freeze_time("2021-05-04")
+ @time_machine.travel("2021-05-04", tick=False)
def test_pagination_cursor_returns_next_page(self):
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})
- with freeze_time("2021-05-02"):
+ with time_machine.travel("2021-05-02", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={})
- with freeze_time("2021-05-03"):
+ with time_machine.travel("2021-05-03", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:3", properties={})
page1 = list_groups(team_id=self.team.pk, group_type_index=0, limit=2)
@@ -2434,11 +2434,11 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert page2.groups[0].group_key == "org:1"
assert page2.has_more is False
- @freeze_time("2021-05-04")
+ @time_machine.travel("2021-05-04", tick=False)
def test_pagination_cursor_breaks_created_at_ties_on_group_key(self):
# Three groups created at the same instant: keyset pagination must fall back to the
# group_key tiebreaker (descending) and neither skip nor duplicate a row across pages.
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:a", properties={})
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:b", properties={})
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:c", properties={})
@@ -2458,7 +2458,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert [g.group_key for g in page2.groups] == ["org:a"]
assert page2.has_more is False
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_search_escapes_like_wildcards(self):
# A literal "%" in the search term must match literally, not act as a wildcard.
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "50% off"})
@@ -2472,7 +2472,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
literal = list_groups(team_id=self.team.pk, group_type_index=0, search="%")
assert [g.group_key for g in literal.groups] == ["org:1"]
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_search_filters_by_properties(self):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Acme Corp"})
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={"name": "Beta Inc"})
@@ -2482,7 +2482,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert len(result.groups) == 1
assert result.groups[0].group_key == "org:1"
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_search_matches_group_key_exact(self):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:alpha", properties={"name": "Alpha"})
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:beta", properties={"name": "Beta"})
@@ -2492,7 +2492,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert len(result.groups) == 1
assert result.groups[0].group_key == "org:alpha"
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_group_key_contains_filter(self):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:alpha", properties={})
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:beta", properties={})
@@ -2502,7 +2502,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert len(result.groups) == 1
assert result.groups[0].group_key == "org:alpha"
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_filters_by_group_type_index(self):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})
create_group(team_id=self.team.pk, group_type_index=1, group_key="company:1", properties={})
@@ -2512,14 +2512,14 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert len(result.groups) == 1
assert result.groups[0].group_key == "org:1"
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_empty_result(self):
result = list_groups(team_id=self.team.pk, group_type_index=0)
assert len(result.groups) == 0
assert result.has_more is False
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_scopes_results_to_team(self):
# An identically-keyed group under a different team must never surface — the query is
# team-scoped by HogQL, so this guards against a cross-team leak.
@@ -2541,9 +2541,9 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
def test_returns_latest_properties_after_update(self):
# The groups table dedups by argMax(_timestamp); a newer write for the same (index, key)
# must win and produce a single row — guards the choice of `groups` over `raw_groups`.
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Old"})
- with freeze_time("2021-05-02"):
+ with time_machine.travel("2021-05-02", tick=False):
raw_create_group_ch(
team_id=self.team.pk,
group_type_index=0,
@@ -2557,7 +2557,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert len(result.groups) == 1
assert result.groups[0].group_properties == {"name": "New"}
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_preserves_complex_property_values(self):
# Properties survive the ClickHouse string -> json.loads -> dict round-trip with types intact.
props = {"count": 5, "active": True, "ratio": 1.5, "tags": ["a", "b"], "nested": {"x": 1}, "missing": None}
@@ -2568,7 +2568,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert len(result.groups) == 1
assert result.groups[0].group_properties == props
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_search_is_case_insensitive(self):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:alpha", properties={"name": "Acme Corp"})
@@ -2579,7 +2579,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert [g.group_key for g in by_props.groups] == ["org:alpha"]
assert [g.group_key for g in by_key.groups] == ["org:alpha"]
- @freeze_time("2021-05-03")
+ @time_machine.travel("2021-05-03", tick=False)
def test_search_no_match_returns_empty(self):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={"name": "Acme"})
@@ -2588,11 +2588,11 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
assert result.groups == []
assert result.has_more is False
- @freeze_time("2021-05-04")
+ @time_machine.travel("2021-05-04", tick=False)
def test_has_more_false_when_result_count_equals_limit(self):
- with freeze_time("2021-05-01"):
+ with time_machine.travel("2021-05-01", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:1", properties={})
- with freeze_time("2021-05-02"):
+ with time_machine.travel("2021-05-02", tick=False):
create_group(team_id=self.team.pk, group_type_index=0, group_key="org:2", properties={})
result = list_groups(team_id=self.team.pk, group_type_index=0, limit=2)
@@ -2602,7 +2602,7 @@ class TestListGroupsFunction(ClickhouseTestMixin, APIBaseTest):
class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_response_format_matches_contract(self):
create_group(
team_id=self.team.pk,
@@ -2625,15 +2625,15 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert result["group_properties"] == {"name": "Test"}
assert "created_at" in result
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_invalid_group_type_index_returns_400(self):
response = self.client.get(f"/api/projects/{self.team.id}/groups?group_type_index=abc")
assert response.status_code == 400
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_cursor_pagination_via_api(self):
for i in range(3):
- with freeze_time(f"2021-05-0{i + 1}"):
+ with time_machine.travel(f"2021-05-0{i + 1}", tick=False):
create_group(
team_id=self.team.pk,
group_type_index=0,
@@ -2648,7 +2648,7 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert page1["results"][0]["group_key"] == "org:2"
assert page1["results"][-1]["group_key"] == "org:0"
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_cursor_roundtrip(self):
cursor = _encode_groups_cursor(1620000000000_000, "org:42")
created_at_us, group_key = _decode_groups_cursor(cursor)
@@ -2656,7 +2656,7 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert created_at_us == 1620000000000_000
assert group_key == "org:42"
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_cursor_backward_compat_ms(self):
cursor = _encode_groups_cursor(1620000000000, "org:42")
created_at_us, group_key = _decode_groups_cursor(cursor)
@@ -2664,7 +2664,7 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert created_at_us == 1620000000000_000
assert group_key == "org:42"
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_old_format_cursor_is_treated_as_no_cursor(self):
# Pre-deploy cursors encoded the tiebreaker as "i" (PG id) with no "k". The new keyset can't
# honor that boundary, so the decoder degrades it to no cursor (restart from the first page).
@@ -2675,7 +2675,7 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert created_at_us == 0
assert group_key == ""
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_invalid_cursor_is_ignored(self):
create_group(
team_id=self.team.pk,
@@ -2690,7 +2690,7 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert len(response_data["results"]) == 1
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_find_uses_personhog_routed_lookup(self):
create_group(
team_id=self.team.pk,
@@ -2706,12 +2706,12 @@ class TestGroupsListAPIContract(ClickhouseTestMixin, APIBaseTest):
assert data["group_key"] == "org:1"
assert data["group_properties"] == {"name": "Test"}
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
def test_find_nonexistent_returns_404(self):
response = self.client.get(f"/api/projects/{self.team.id}/groups/find?group_type_index=0&group_key=nonexistent")
assert response.status_code == 404
- @freeze_time("2021-05-02")
+ @time_machine.travel("2021-05-02", tick=False)
@patch("ee.clickhouse.views.groups.list_groups")
def test_list_api_has_more_produces_next_url(self, mock_list_groups):
# The viewset turns a has_more result into a forward cursor in the `next` URL.
diff --git a/ee/clickhouse/views/test/test_clickhouse_trends.py b/ee/clickhouse/views/test/test_clickhouse_trends.py
index 03c21848db44..e35d6748c980 100644
--- a/ee/clickhouse/views/test/test_clickhouse_trends.py
+++ b/ee/clickhouse/views/test/test_clickhouse_trends.py
@@ -4,7 +4,7 @@ from datetime import datetime
from typing import Any, Optional, Union
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -55,7 +55,7 @@ def test_includes_only_intervals_within_range(client: Client):
#  simplest way to reproduce
# "2021-09-19" is a sunday, i.e. beginning of week
- with freeze_time("2021-09-20T16:00:00"):
+ with time_machine.travel("2021-09-20T16:00:00", tick=False):
#  First identify as a member of the cohort
distinct_id = "abc"
update_or_create_person(
@@ -142,7 +142,7 @@ def test_can_specify_number_of_smoothing_intervals(client: Client):
client.force_login(user)
- with freeze_time("2021-09-20T16:00:00"):
+ with time_machine.travel("2021-09-20T16:00:00", tick=False):
journeys_for(
events_by_person={
"abc": [
@@ -310,7 +310,7 @@ def test_smoothing_intervals_copes_with_null_values(client: Client):
client.force_login(user)
cache.clear()
- with freeze_time("2021-09-20T16:00:00"):
+ with time_machine.travel("2021-09-20T16:00:00", tick=False):
journeys_for(
events_by_person={
"abc": [
@@ -513,7 +513,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraph",
@@ -551,7 +551,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraph",
@@ -594,7 +594,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsPie",
@@ -653,7 +653,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
journeys_for(events_by_person, self.team, create_people=False)
# Total Volume
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraphCumulative",
@@ -679,7 +679,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
# DAU
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraphCumulative",
@@ -704,7 +704,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
assert data_response["$pageview"]["2012-01-14"].label == "14-Jan-2012"
# breakdown
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraphCumulative",
@@ -731,7 +731,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
assert data_response["val"]["2012-01-14"].label == "14-Jan-2012"
# breakdown wau
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraphCumulative",
@@ -759,7 +759,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
assert data_response["val"]["2012-01-14"].label == "14-Jan-2012"
# breakdown dau
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraphCumulative",
@@ -805,7 +805,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
params = TrendsRequestBreakdown(
date_from="-14d",
breakdown="key",
@@ -817,7 +817,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
assert data_response["val"]["2012-01-13"].value == 1
assert data_response["val"]["2012-01-13"].breakdown_value == "val"
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
params = TrendsRequestBreakdown(
date_from="-14d",
breakdown="key",
@@ -857,7 +857,7 @@ class ClickhouseTestTrends(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest):
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-7d",
compare=True,
@@ -1021,7 +1021,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraph",
@@ -1047,7 +1047,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
events_by_person = {"1": [{"event": "$pageview", "timestamp": datetime(2012, 1, 15, 3)}]}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraph",
@@ -1098,7 +1098,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraph",
@@ -1144,7 +1144,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraph",
@@ -1210,7 +1210,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraph",
@@ -1275,7 +1275,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
request = TrendsRequestBreakdown(
date_from="-14d",
display="ActionsLineGraph",
@@ -1329,7 +1329,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-14T04:01:34.000Z"):
+ with time_machine.travel("2012-01-14T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraph",
@@ -1357,7 +1357,7 @@ class ClickhouseTestTrendsCaching(ClickhouseTestMixin, LicensedTestMixin, APIBas
}
journeys_for(events_by_person, self.team)
- with freeze_time("2012-01-16T04:01:34.000Z"):
+ with time_machine.travel("2012-01-16T04:01:34.000Z", tick=False):
request = TrendsRequest(
date_from="-14d",
display="ActionsLineGraph",
diff --git a/ee/hogai/chat_agent/memory/test/test_nodes.py b/ee/hogai/chat_agent/memory/test/test_nodes.py
index 3fc9f1f7b52c..87b1c1a2a5c8 100644
--- a/ee/hogai/chat_agent/memory/test/test_nodes.py
+++ b/ee/hogai/chat_agent/memory/test/test_nodes.py
@@ -1,6 +1,6 @@
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
BaseTest,
ClickhouseTestMixin,
@@ -643,7 +643,7 @@ class TestMemoryCollectorNode(ClickhouseTestMixin, NonAtomicBaseTest):
self.assertEqual(history[1].content, "Memory 1")
self.assertEqual(history[2].content, "Tool response")
- @freeze_time("2024-01-01")
+ @time_machine.travel("2024-01-01", tick=False)
async def test_prompt_substitutions(self):
with patch.object(MemoryCollectorNode, "_model") as model_mock:
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
index 38725e8c36c0..b23e7adef099 100644
--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from textwrap import dedent
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -215,13 +215,13 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
base_time = datetime.now(UTC)
for i in range(25):
id = f"person{i}"
- with freeze_time(base_time - timedelta(minutes=25 - i)):
+ with time_machine.travel(base_time - timedelta(minutes=25 - i), tick=False):
_create_person(
distinct_ids=[id],
properties={"taxonomy_email": f"{id}@example.com", "id": i},
team=self.team,
)
- with freeze_time(base_time):
+ with time_machine.travel(base_time, tick=False):
_create_person(
distinct_ids=["person25"],
properties={"taxonomy_email": "[email protected]", "id": 25},
@@ -253,14 +253,14 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
for i in range(7):
id = f"group{i}"
- with freeze_time(f"2024-01-01T{i}:00:00Z"):
+ with time_machine.travel(f"2024-01-01T{i}:00:00Z", tick=False):
create_group(
group_type_index=0,
group_key=id,
properties={"test": i},
team_id=self.team.pk,
)
- with freeze_time(f"2024-01-02T00:00:00Z"):
+ with time_machine.travel(f"2024-01-02T00:00:00Z", tick=False):
create_group(
group_type_index=1,
group_key="org",
diff --git a/ee/hogai/context/activity_log/test/test_context.py b/ee/hogai/context/activity_log/test/test_context.py
index ea7b3c3080a6..fa588e6e6b10 100644
--- a/ee/hogai/context/activity_log/test/test_context.py
+++ b/ee/hogai/context/activity_log/test/test_context.py
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -50,7 +50,7 @@ class ActivityLogTestBase(BaseTest):
)
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContext(ActivityLogTestBase):
def _create_context(self) -> ActivityLogContext:
return ActivityLogContext(team=self.team, user=self.user)
@@ -355,7 +355,7 @@ class TestActivityLogContext(ActivityLogTestBase):
assert "name: a -> b" in result
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContextPagination(ActivityLogTestBase):
def _create_context(self) -> ActivityLogContext:
return ActivityLogContext(team=self.team, user=self.user)
@@ -412,7 +412,7 @@ class TestActivityLogContextPagination(ActivityLogTestBase):
assert "end of results" in result
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContextDatetimeFilter(ActivityLogTestBase):
def _create_context(self) -> ActivityLogContext:
return ActivityLogContext(team=self.team, user=self.user)
@@ -491,7 +491,7 @@ class TestActivityLogContextDatetimeFilter(ActivityLogTestBase):
assert "'before' filter 'also-invalid' is not a valid ISO 8601 datetime and was ignored" in result
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContextTruncation(ActivityLogTestBase):
def _create_context(self) -> ActivityLogContext:
return ActivityLogContext(team=self.team, user=self.user)
@@ -549,7 +549,7 @@ class TestActivityLogContextTruncation(ActivityLogTestBase):
assert "..." in result
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContextVisibility(ActivityLogTestBase):
def _create_context(self, user=None) -> ActivityLogContext:
return ActivityLogContext(team=self.team, user=user or self.user)
@@ -713,7 +713,7 @@ class TestActivityLogContextVisibility(ActivityLogTestBase):
assert result == ACTIVITY_LOG_NO_RESULTS
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContextHumanization(ActivityLogTestBase):
def _create_context(self) -> ActivityLogContext:
return ActivityLogContext(team=self.team, user=self.user)
@@ -782,7 +782,7 @@ class TestActivityLogContextHumanization(ActivityLogTestBase):
assert "active: True -> False" in result
-@freeze_time("2025-06-15T12:00:00Z")
+@time_machine.travel("2025-06-15T12:00:00Z", tick=False)
class TestActivityLogContextFormatting(ActivityLogTestBase):
async def test_timestamp_format(self):
await self._create_log(
diff --git a/ee/hogai/context/error_tracking/test/test_context.py b/ee/hogai/context/error_tracking/test/test_context.py
index e79a6df60fbd..10fa7c99c36b 100644
--- a/ee/hogai/context/error_tracking/test/test_context.py
+++ b/ee/hogai/context/error_tracking/test/test_context.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
@@ -16,7 +16,7 @@ ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
-@freeze_time("2025-01-15T12:00:00Z")
+@time_machine.travel("2025-01-15T12:00:00Z", tick=False)
class TestErrorTrackingIssueContext(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -89,7 +89,7 @@ class TestErrorTrackingIssueContext(ClickhouseTestMixin, APIBaseTest):
exception_list=None,
):
if timestamp:
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
self.create_issue(issue_id, fingerprint, name=issue_name, status=status)
else:
self.create_issue(issue_id, fingerprint, name=issue_name, status=status)
diff --git a/ee/hogai/context/insight/format/test/test_funnel.py b/ee/hogai/context/insight/format/test/test_funnel.py
index ca9969f2c1f5..3be13e25dc60 100644
--- a/ee/hogai/context/insight/format/test/test_funnel.py
+++ b/ee/hogai/context/insight/format/test/test_funnel.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -208,7 +208,7 @@ class TestFunnelResultsFormatter(BaseTest):
],
]
- with freeze_time("2025-02-07T15:00:00"):
+ with time_machine.travel("2025-02-07T15:00:00", tick=False):
self.assertEqual(
FunnelResultsFormatter(
AssistantFunnelsQuery(series=[]),
diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.py
index abc866dbf664..d801c601ef53 100644
--- a/ee/hogai/context/insight/test/test_query_executor.py
+++ b/ee/hogai/context/insight/test/test_query_executor.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import NonAtomicBaseTest
from unittest.mock import Mock, patch
@@ -56,7 +56,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):
def setUp(self):
super().setUp()
- with freeze_time("2025-01-20T12:00:00Z"):
+ with time_machine.travel("2025-01-20T12:00:00Z", tick=False):
self.query_runner = AssistantQueryExecutor(self.team, datetime.now(), user=self.user)
@patch("ee.hogai.context.insight.query_executor.process_query_dict")
@@ -648,7 +648,7 @@ class TestAssistantQueryExecutorAsync(NonAtomicBaseTest):
def setUp(self):
super().setUp()
- with freeze_time("2025-01-20T12:00:00Z"):
+ with time_machine.travel("2025-01-20T12:00:00Z", tick=False):
self.query_runner = AssistantQueryExecutor(self.team, datetime.now(), user=self.user)
async def test_runs_in_async_context(self):
@@ -674,7 +674,7 @@ class TestExecuteAndFormatQuery(NonAtomicBaseTest):
def setUp(self):
super().setUp()
- with freeze_time("2025-01-20T12:00:00Z"):
+ with time_machine.travel("2025-01-20T12:00:00Z", tick=False):
self.query_runner = AssistantQueryExecutor(self.team, datetime.now(), user=self.user)
@patch("ee.hogai.context.insight.query_executor.process_query_dict")
diff --git a/ee/hogai/tools/replay/test/test_filter_session_recordings.py b/ee/hogai/tools/replay/test/test_filter_session_recordings.py
index e3d9653bc0dd..a188741c9b92 100644
--- a/ee/hogai/tools/replay/test/test_filter_session_recordings.py
+++ b/ee/hogai/tools/replay/test/test_filter_session_recordings.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event, flush_persons_and_events
from langchain_core.runnables import RunnableConfig
@@ -26,7 +26,7 @@ from ee.hogai.utils.types import AssistantState
from ee.hogai.utils.types.base import NodePath
-@freeze_time("2025-01-15T12:00:00Z")
+@time_machine.travel("2025-01-15T12:00:00Z", tick=False)
class TestFilterSessionRecordingsTool(ClickhouseTestMixin, NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
diff --git a/ee/models/test/test_assistant.py b/ee/models/test/test_assistant.py
index d921be5fe7bb..6db324876793 100644
--- a/ee/models/test/test_assistant.py
+++ b/ee/models/test/test_assistant.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from django.utils import timezone
@@ -42,22 +42,22 @@ class TestCoreMemory(BaseTest):
await self.core_memory.asave()
self.assertTrue(self.core_memory.is_scraping_finished)
- @freeze_time("2023-01-01 12:00:00")
+ @time_machine.travel("2023-01-01 12:00:00", tick=False)
async def test_is_scraping_pending_timing(self):
# Set initial pending status
await self.core_memory.achange_status_to_pending()
initial_time = timezone.now()
# Test 3 minutes after (should be true)
- with freeze_time(initial_time + timedelta(minutes=3)):
+ with time_machine.travel(initial_time + timedelta(minutes=3), tick=False):
self.assertTrue(self.core_memory.is_scraping_pending)
# Test exactly 5 minutes after (should be false)
- with freeze_time(initial_time + timedelta(minutes=10)):
+ with time_machine.travel(initial_time + timedelta(minutes=10), tick=False):
self.assertFalse(self.core_memory.is_scraping_pending)
# Test 6 minutes after (should be false)
- with freeze_time(initial_time + timedelta(minutes=11)):
+ with time_machine.travel(initial_time + timedelta(minutes=11), tick=False):
self.assertFalse(self.core_memory.is_scraping_pending)
async def test_core_memory_operations(self):
diff --git a/ee/tasks/subscriptions/test_auto_disable.py b/ee/tasks/subscriptions/test_auto_disable.py
index bbef7894c4e9..a3f0f106232e 100644
--- a/ee/tasks/subscriptions/test_auto_disable.py
+++ b/ee/tasks/subscriptions/test_auto_disable.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -226,7 +226,7 @@ class TestDisableInvalidSubscription(APIBaseTest):
capture_mock.assert_called_once()
-@freeze_time("2026-08-01T12:00:00Z")
+@time_machine.travel("2026-08-01T12:00:00Z", tick=False)
class TestSubscriptionDeliveryFailureNotification(APIBaseTest):
def test_sends_email_to_the_subscription_creator(self):
subscription = Subscription.objects.create(
diff --git a/ee/tasks/test/subscriptions/test_email_subscriptions.py b/ee/tasks/test/subscriptions/test_email_subscriptions.py
index 28ec77309826..2b1a7f3c35fd 100644
--- a/ee/tasks/test/subscriptions/test_email_subscriptions.py
+++ b/ee/tasks/test/subscriptions/test_email_subscriptions.py
@@ -1,7 +1,7 @@
import uuid
import smtplib
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -24,7 +24,7 @@ def mock_ee_email_messages(MockEmailMessage: MagicMock):
@patch("ee.tasks.subscriptions.email_subscriptions.EmailMessage")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
class TestEmailSubscriptionsTasks(APIBaseTest):
subscription: Subscription
dashboard: Dashboard
@@ -219,7 +219,7 @@ class TestEmailSubscriptionsTasks(APIBaseTest):
assert str(delivery_id) in mocked_email_messages[0].campaign_key
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
class TestEmailSubscriptionDeliveryDetection(APIBaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.py
index 3a8f904414c9..0e5dc7619f40 100644
--- a/ee/tasks/test/subscriptions/test_slack_subscriptions.py
+++ b/ee/tasks/test/subscriptions/test_slack_subscriptions.py
@@ -2,7 +2,7 @@ import asyncio
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, MagicMock, call, patch
@@ -44,7 +44,7 @@ def _make_slack_api_error(error_code: str, **extra_data) -> SlackApiError:
@patch("ee.tasks.subscriptions.slack_subscriptions.SlackIntegration")
-@freeze_time("2022-02-02T08:30:00.000Z")
+@time_machine.travel("2022-02-02T08:30:00.000Z", tick=False)
class TestSlackSubscriptionsTasks(APIBaseTest):
subscription: Subscription
dashboard: Dashboard
@@ -286,7 +286,7 @@ class TestSlackSubscriptionsTasks(APIBaseTest):
@patch("ee.tasks.subscriptions.slack_subscriptions.SlackIntegration")
-@freeze_time("2025-01-01T08:30:00.000Z")
+@time_machine.travel("2025-01-01T08:30:00.000Z", tick=False)
class TestSlackSubscriptionsAsyncTasks(APIBaseTest):
TOTAL_ASSET_COUNT = 10
diff --git a/ee/tasks/test/test_send_license_usage.py b/ee/tasks/test/test_send_license_usage.py
index 06f8fd8066c2..b3cc41eb218d 100644
--- a/ee/tasks/test/test_send_license_usage.py
+++ b/ee/tasks/test/test_send_license_usage.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from unittest.mock import ANY, Mock, patch
@@ -10,7 +10,7 @@ from ee.tasks.send_license_usage import send_license_usage
class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest):
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthoganalytics.capture")
@patch("ee.tasks.send_license_usage.requests.post")
def test_send_license_usage(self, mock_post, mock_capture):
@@ -77,7 +77,7 @@ class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIB
)
self.assertEqual(License.objects.get().valid_until.isoformat(), "2021-11-10T23:01:00+00:00")
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthoganalytics.capture")
@patch("ee.tasks.send_license_usage.sync_execute", side_effect=Exception())
def test_send_license_error(self, mock_post, mock_capture):
@@ -135,7 +135,7 @@ class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIB
groups={"instance": ANY, "organization": str(self.organization.id)},
)
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthoganalytics.capture")
@patch("ee.tasks.send_license_usage.requests.post")
def test_send_license_usage_already_sent(self, mock_post, mock_capture):
@@ -191,7 +191,7 @@ class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIB
send_license_usage()
mock_capture.assert_not_called()
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthoganalytics.capture")
@patch("ee.tasks.send_license_usage.requests.post")
def test_send_license_not_found(self, mock_post, mock_capture):
@@ -261,7 +261,7 @@ class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIB
)
self.assertEqual(License.objects.get().valid_until.isoformat(), "2021-10-10T22:01:00+00:00")
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthoganalytics.capture")
@patch("ee.tasks.send_license_usage.requests.post")
def test_send_license_not_triggered_for_v2_licenses(self, mock_post, mock_capture):
@@ -274,7 +274,7 @@ class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIB
class SendLicenseUsageNoLicenseTest(APIBaseTest):
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("ee.tasks.send_license_usage.requests.post")
def test_no_license(self, mock_post):
# Same test, we just don't include the LicensedTestMixin so no license
diff --git a/ee/tasks/test/test_slack.py b/ee/tasks/test/test_slack.py
index fc105ce9e0c7..55904fb1096c 100644
--- a/ee/tasks/test/test_slack.py
+++ b/ee/tasks/test/test_slack.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -39,7 +39,7 @@ def create_mock_unfurl_event(team_id: str, links: list[str]):
@patch("ee.tasks.slack.generate_assets")
@patch("ee.tasks.slack.SlackIntegration")
-@freeze_time("2022-01-01T12:00:00.000Z")
+@time_machine.travel("2022-01-01T12:00:00.000Z", tick=False)
class TestSlackSubscriptionsTasks(APIBaseTest):
subscription: Subscription
dashboard: Dashboard
diff --git a/posthog/admin/test_data_deletion_request_admin.py b/posthog/admin/test_data_deletion_request_admin.py
index 501bc399c530..6da3a900b27a 100644
--- a/posthog/admin/test_data_deletion_request_admin.py
+++ b/posthog/admin/test_data_deletion_request_admin.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -417,7 +417,7 @@ class TestDataDeletionRequestAdminSubmitView(BaseTest):
self.assertFalse(self._call_submit(property_removal, method="GET").context_data["auto_approve_candidate"])
-@freeze_time("2025-01-15 12:00:00")
+@time_machine.travel("2025-01-15 12:00:00", tick=False)
@override_settings(STORAGES={"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}})
class TestDataDeletionRequestAdminSaveModel(BaseTest):
def setUp(self):
@@ -517,7 +517,7 @@ class TestDataDeletionRequestAdminSaveModel(BaseTest):
self.assertIsNone(obj.property_removal_marker)
-@freeze_time("2025-01-15 12:00:00")
+@time_machine.travel("2025-01-15 12:00:00", tick=False)
class TestDataDeletionRequestModelValidation(BaseTest):
def test_person_removal_rejects_person_properties_field(self):
from django.core.exceptions import ValidationError
@@ -917,7 +917,7 @@ class TestDataDeletionRequestAdminDuplicate(BaseTest):
("without_notes", ""),
]
)
- @freeze_time("2026-01-15")
+ @time_machine.travel("2026-01-15", tick=False)
def test_duplicate_copies_criteria_into_a_fresh_draft_with_link_note(self, _name, original_notes):
original = DataDeletionRequest.objects.create(
team_id=self.team.id,
diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.py
index d53a416b0140..51d0ac17ac33 100644
--- a/posthog/admin/test_oauth_admin.py
+++ b/posthog/admin/test_oauth_admin.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -139,7 +139,7 @@ class TestOAuthApplicationAdmin(BaseTest):
plaintext = message.rsplit(": ", 1)[1]
assert check_password(plaintext, app.client_secret)
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_revoke_all_sessions_action_force_invalidates_tokens(self):
app = OAuthApplication.objects.create(
name="Revoke Action App",
@@ -166,7 +166,7 @@ class TestOAuthApplicationAdmin(BaseTest):
self.assertEqual(OAuthRefreshToken.objects.filter(application=app, revoked__isnull=True).count(), 0)
message_user.assert_called_once()
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_revoke_all_sessions_without_confirm_renders_page_and_keeps_tokens(self):
app = OAuthApplication.objects.create(
name="Revoke Confirm App",
diff --git a/posthog/admin/test_send_ai_observability_usage_report_admin.py b/posthog/admin/test_send_ai_observability_usage_report_admin.py
index 1257ce3ef0d4..9318529487d5 100644
--- a/posthog/admin/test_send_ai_observability_usage_report_admin.py
+++ b/posthog/admin/test_send_ai_observability_usage_report_admin.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -7,7 +7,6 @@ from django.contrib.admin.sites import AdminSite
from django.contrib.messages.storage.fallback import FallbackStorage
from django.core.management.base import CommandError
from django.test import RequestFactory
-from django.urls import reverse
from posthog.admin.admins.organization_admin import OrganizationAdmin
from posthog.models import Organization
@@ -29,9 +28,6 @@ class TestSendAIObservabilityUsageReportAdmin(BaseTest):
self.user.save()
self.factory = RequestFactory()
self.admin = OrganizationAdmin(Organization, AdminSite())
- reverse(
- "admin:index"
- ) # warm posthog.urls import outside freeze_time: the first reverse() lazily imports pydantic v1, which breaks under a frozen datetime.date
def _post(self, report_date: str, call_command_side_effect=None):
http_request = self.factory.post(
@@ -48,7 +44,7 @@ class TestSendAIObservabilityUsageReportAdmin(BaseTest):
response = self.admin.send_ai_observability_usage_report_view(http_request)
return response, mock_call_command, http_request
- @freeze_time("2026-07-22T12:00:00Z")
+ @time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_valid_post_dispatches_async_command_for_date(self):
response, mock_call_command, http_request = self._post("2026-07-15")
@@ -56,14 +52,14 @@ class TestSendAIObservabilityUsageReportAdmin(BaseTest):
mock_call_command.assert_called_once_with("send_ai_observability_usage_report", "--date=2026-07-15", "--async")
self.assertEqual([m.level for m in http_request._messages], [messages.SUCCESS])
- @freeze_time("2026-07-22T12:00:00Z")
+ @time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_far_future_date_is_rejected_and_not_dispatched(self):
response, mock_call_command, _ = self._post("2026-07-30")
self.assertEqual(response.status_code, 200)
mock_call_command.assert_not_called()
- @freeze_time("2026-07-22T12:00:00Z")
+ @time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_refused_dispatch_is_reported_as_an_error_not_a_success(self):
response, _, http_request = self._post(
"2026-07-15", call_command_side_effect=CommandError("A usage report run for 2026-07-15 was already sent.")
diff --git a/posthog/admin/test_team_admin.py b/posthog/admin/test_team_admin.py
index 34bf1cb28cb3..3ed3761b7881 100644
--- a/posthog/admin/test_team_admin.py
+++ b/posthog/admin/test_team_admin.py
@@ -2,7 +2,7 @@ import hashlib
from datetime import UTC, datetime, timedelta
from decimal import Decimal
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -128,7 +128,7 @@ class TestTeamAdminSetApiTokenView(BaseTest):
assert self.team.api_token == "phc_admin_test_old"
-@freeze_time("2026-01-01T00:00:00Z")
+@time_machine.travel("2026-01-01T00:00:00Z", tick=False)
class TestTeamAdminLLMGateway(BaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/api/advanced_activity_logs/test_pagination_ordering.py b/posthog/api/advanced_activity_logs/test_pagination_ordering.py
index 9f4efcff5194..fad5ef41723e 100644
--- a/posthog/api/advanced_activity_logs/test_pagination_ordering.py
+++ b/posthog/api/advanced_activity_logs/test_pagination_ordering.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.utils import timezone
@@ -13,7 +13,7 @@ from posthog.api.advanced_activity_logs.viewset import activity_log_ordering
from posthog.models.activity_logging.activity_log import ActivityLog
-@freeze_time("2024-01-01T12:00:00Z")
+@time_machine.travel("2024-01-01T12:00:00Z", tick=False)
class TestActivityLogCursorOrdering(APIBaseTest):
def _create_logs(self, count: int, same_timestamp: bool = False) -> None:
stamp = timezone.now()
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index 4b3a39ae6287..3d3a5b2fd008 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -3,7 +3,7 @@ from datetime import UTC
from typing import Any, TypedDict, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -849,11 +849,11 @@ class TestFileSystemAPI(APIBaseTest):
def test_list_order_by_created_at(self):
# Create items in chronological order
- with freeze_time("2020-01-01 10:00:00"):
+ with time_machine.travel("2020-01-01 10:00:00", tick=False):
file_1 = FileSystem.objects.create(team=self.team, path="File_1", type="feature_flag", created_by=self.user)
- with freeze_time("2020-01-02 10:00:00"):
+ with time_machine.travel("2020-01-02 10:00:00", tick=False):
file_2 = FileSystem.objects.create(team=self.team, path="File_2", type="feature_flag", created_by=self.user)
- with freeze_time("2020-01-03 10:00:00"):
+ with time_machine.travel("2020-01-03 10:00:00", tick=False):
file_3 = FileSystem.objects.create(team=self.team, path="File_3", type="feature_flag", created_by=self.user)
# Query with descending order
@@ -1033,12 +1033,10 @@ class TestFileSystemAPI(APIBaseTest):
`created_at` and `created_by` into both the FileSystem columns and the
`meta` dict.
"""
- from freezegun import freeze_time
-
from django.utils import timezone
# Create a FeatureFlag at a known moment in time
- with freeze_time("2023-02-10 15:00:00"):
+ with time_machine.travel("2023-02-10 15:00:00", tick=False):
flag = FeatureFlag.objects.create(team=self.team, key="Synced-Flag", created_by=self.user)
FileSystem.objects.all().delete()
@@ -1703,11 +1701,11 @@ class TestFileSystemAPIAdvancedPermissions(APIBaseTest):
Verify we can filter by created_at greater-than and less-than.
"""
# Create 3 files with different timestamps.
- with freeze_time("2020-01-01T10:00:00Z"):
+ with time_machine.travel("2020-01-01T10:00:00Z", tick=False):
FileSystem.objects.create(team=self.team, path="OldFile", type="feature_flag", created_by=self.user)
- with freeze_time("2020-01-02T10:00:00Z"):
+ with time_machine.travel("2020-01-02T10:00:00Z", tick=False):
FileSystem.objects.create(team=self.team, path="MidFile", type="feature_flag", created_by=self.user)
- with freeze_time("2020-01-03T10:00:00Z"):
+ with time_machine.travel("2020-01-03T10:00:00Z", tick=False):
FileSystem.objects.create(team=self.team, path="NewFile", type="feature_flag", created_by=self.user)
# 1) Filter with ?created_at__gt=2020-01-01T12:00:00Z
diff --git a/posthog/api/oauth/test_connected_apps.py b/posthog/api/oauth/test_connected_apps.py
index 55582deef9c0..ce7a2320e1c0 100644
--- a/posthog/api/oauth/test_connected_apps.py
+++ b/posthog/api/oauth/test_connected_apps.py
@@ -1,7 +1,7 @@
import uuid
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.utils import timezone
@@ -14,7 +14,7 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant,
from posthog.models.user import User
-@freeze_time("2024-06-15T12:00:00Z")
+@time_machine.travel("2024-06-15T12:00:00Z", tick=False)
class TestConnectedAppsViewSet(APIBaseTest):
def _create_app(self, name: str = "Test App", **kwargs) -> OAuthApplication:
return OAuthApplication.objects.create(
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 8229586ddb2b..0e91e3b995d2 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -9,7 +9,7 @@ from typing import Optional, cast
from urllib.parse import parse_qs, quote, urlencode, urlparse, urlunparse
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, FuzzyInt
from unittest.mock import patch
@@ -369,7 +369,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_authorize_post_authorization_granted(self):
response = self.client.post(
"/oauth/authorize/",
@@ -467,7 +467,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["error"], "invalid_grant")
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_cannot_get_token_with_expired_code(self):
expired_grant = OAuthGrant.objects.create(
application=self.confidential_application,
@@ -717,7 +717,7 @@ class TestOAuthAPI(APIBaseTest):
},
)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(SITE_URL="https://us.posthog.com")
def test_private_key_jwt_cimd_client_completes_token_exchange(self):
# A private_key_jwt CIMD client is confidential but holds no secret, so the secret
@@ -740,7 +740,7 @@ class TestOAuthAPI(APIBaseTest):
# assertion path has to be what keeps its CIMD registration fresh.
refresh.assert_called_once_with(app.client_id)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(SITE_URL="https://us.posthog.com")
def test_private_key_jwt_exchange_survives_refresh_enqueue_failure(self):
# Metadata freshness is best-effort: a broker outage must not fail a valid exchange.
@@ -761,7 +761,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(SITE_URL="https://us.posthog.com")
def test_private_key_jwt_exchange_maps_redis_failure_to_retryable(self):
# The assertion path reads Redis for the JWKS and jti caches, so an outage must
@@ -847,7 +847,7 @@ class TestOAuthAPI(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(SITE_URL="https://us.posthog.com")
def test_public_cimd_client_with_stored_jwks_completes_assertion_exchange(self):
# A public CIMD client (never partner-registered) can start signing at any time — a
@@ -865,7 +865,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
self.assertIn("access_token", response.json())
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(SITE_URL="https://us.posthog.com")
def test_public_cimd_client_with_forged_assertion_is_rejected(self):
# The menu-semantics widening must not weaken verification: a public client's forged
@@ -902,7 +902,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
self.assertIn("access_token", response.json())
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(SITE_URL="https://us.posthog.com")
def test_invalid_assertion_is_not_downgraded_to_the_credentialless_fallback(self):
# A presented assertion must be verified, never ignored: an assertion signed by a
@@ -962,7 +962,7 @@ class TestOAuthAPI(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.content)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_token_endpoint_invalid_client_credentials(self):
grant = OAuthGrant.objects.create(
application=self.confidential_application,
@@ -1363,7 +1363,7 @@ class TestOAuthAPI(APIBaseTest):
# Revoking tokens
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_revoke_refresh_token_for_application(self):
token_value = f"test_refresh_token_to_revoke"
@@ -1411,7 +1411,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertIsNone(refresh_token.revoked)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_revoke_refresh_token_for_public_application_without_client_secret(self):
token_value = f"test_refresh_token_to_revoke_without_client_secret"
@@ -1747,7 +1747,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["error"], "invalid_grant")
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_refresh_racing_app_revoke_is_rejected(self):
# A refresh validates its token in autocommit, before save_bearer_token takes the row
# lock, so revoke_application_sessions can commit in between and the refresh would mint
@@ -1756,7 +1756,7 @@ class TestOAuthAPI(APIBaseTest):
# valid through validate_refresh_token.
refresh_token = self._create_refreshable_token_pair("openid")
- with freeze_time("2026-01-01 00:00:05"):
+ with time_machine.travel("2026-01-01 00:00:05", tick=False):
revoke_application_sessions(self.confidential_application)
response = self.post(
@@ -1776,7 +1776,7 @@ class TestOAuthAPI(APIBaseTest):
OAuthRefreshToken.objects.filter(application=self.confidential_application, revoked__isnull=True).exists()
)
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_refresh_racing_user_session_revoke_is_rejected(self):
# Same race as the app-wide case, on the per-connection revoke behind the connected-apps
# UI and RFC 7009. revoke_oauth_session deletes the pair's refresh tokens, so a refresh
@@ -1786,7 +1786,7 @@ class TestOAuthAPI(APIBaseTest):
# already-revoked row, so DOT went on to mint a fresh access and refresh token.
refresh_token = self._create_refreshable_token_pair("openid")
- with freeze_time("2026-01-01 00:00:05"):
+ with time_machine.travel("2026-01-01 00:00:05", tick=False):
revoke_oauth_session(refresh_token=refresh_token)
response = self.post(
@@ -1803,7 +1803,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.json()["error"], "invalid_grant")
self._assert_no_live_tokens()
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_refresh_whose_token_is_deleted_while_waiting_for_the_lock_is_rejected(self):
# The reverse interleaving: the request passes validate_refresh_token in autocommit, then a
# revoke commits while it waits for the connection lock. Deleting the row from inside the
@@ -1828,13 +1828,13 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["error"], "invalid_grant")
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_refresh_succeeds_for_token_issued_after_revoke(self):
# A token minted after the revoke stamp (i.e. the client re-authorized) refreshes normally.
self.confidential_application.sessions_revoked_at = timezone.now()
self.confidential_application.save()
- with freeze_time("2026-01-01 00:00:05"):
+ with time_machine.travel("2026-01-01 00:00:05", tick=False):
refresh_token = self._create_refreshable_token_pair("openid")
data = self._refresh(refresh_token.token)
@@ -1854,14 +1854,14 @@ class TestOAuthAPI(APIBaseTest):
OAuthRefreshToken.objects.filter(application=self.confidential_application, revoked__isnull=True).exists()
)
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_code_exchange_racing_app_revoke_is_rejected(self):
# The race leaves this committed state at mint time: sessions_revoked_at stamped, grant
# predating it. Stamping without the full revoke (which also deletes the grant — covered
# by the validate-then-revoke test below) exercises the timestamp branch.
code = self._authorize_and_get_code()
- with freeze_time("2026-01-01 00:00:05"):
+ with time_machine.travel("2026-01-01 00:00:05", tick=False):
self.confidential_application.sessions_revoked_at = timezone.now()
self.confidential_application.save()
@@ -1872,7 +1872,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response["Content-Type"], "application/json")
self._assert_no_live_tokens()
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_code_exchange_validated_before_app_revoke_is_rejected(self):
# oauthlib validates the grant in autocommit, before save_bearer_token's transaction, so
# revoke_application_sessions can commit (deleting the grant and stamping) after
@@ -1887,7 +1887,7 @@ class TestOAuthAPI(APIBaseTest):
return real_save_bearer_token(validator, token, oauth_request, *args, **kwargs)
with (
- freeze_time("2026-01-01 00:00:05"),
+ time_machine.travel("2026-01-01 00:00:05", tick=False),
patch.object(OAuthValidator, "save_bearer_token", revoke_then_save),
):
response = self._exchange_code(code)
@@ -1896,13 +1896,13 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.json()["error"], "invalid_grant")
self._assert_no_live_tokens()
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_code_exchange_succeeds_for_grant_issued_after_revoke(self):
# A grant created after the revoke stamp (i.e. the user re-authorized) exchanges normally.
self.confidential_application.sessions_revoked_at = timezone.now()
self.confidential_application.save()
- with freeze_time("2026-01-01 00:00:05"):
+ with time_machine.travel("2026-01-01 00:00:05", tick=False):
code = self._authorize_and_get_code()
response = self._exchange_code(code)
@@ -1962,7 +1962,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(set(result), {"openid", "experiment:read"})
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_narrowed_scopes_persist_across_multiple_refreshes(self):
# After a narrowed refresh, the rotated token already carries the narrowed
# set, so a second refresh must hold steady rather than re-broaden.
@@ -1979,7 +1979,7 @@ class TestOAuthAPI(APIBaseTest):
second_scopes = set(OAuthAccessToken.objects.get(token=second["access_token"]).scope.split())
self.assertEqual(second_scopes, {"openid", "experiment:read"})
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_refresh_rejected_outside_ceiling_does_not_revoke_token(self):
# The zero-overlap rejection bounces the single request without revoking the
# token: re-widening the ceiling lets the very same refresh token work again.
@@ -2047,7 +2047,7 @@ class TestOAuthAPI(APIBaseTest):
db_token = OAuthAccessToken.objects.get(token=new_access_token)
self.assertEqual(db_token.scoped_teams, [self.team.id])
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_refresh_succeeds_when_only_scoped_teams_is_set(self):
"""scoped_teams and scoped_organizations are both nullable ArrayFields. Historically
they could be set independently — a token scoped to a team often had
@@ -2162,7 +2162,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["error"], "invalid_grant")
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_refresh_token_rotation_invalidates_old_token(self):
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
@@ -2189,7 +2189,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(retry_old_token_within_grace.json()["refresh_token"], new_refresh_token)
# After grace period, old token should be invalid
- with freeze_time("2025-01-01 00:03:00"): # 3 minutes later, beyond grace period
+ with time_machine.travel("2025-01-01 00:03:00", tick=False): # 3 minutes later, beyond grace period
retry_old_token_after_grace = self.post("/oauth/token/", refresh_data)
self.assertEqual(retry_old_token_after_grace.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(retry_old_token_after_grace.json()["error"], "invalid_grant")
@@ -2224,11 +2224,11 @@ class TestOAuthAPI(APIBaseTest):
self.assertNotEqual(grant.user, self.user)
def test_authorization_code_expires_correctly(self):
- with freeze_time("2025-01-01 00:00:00") as frozen_time:
+ with time_machine.travel("2025-01-01 00:00:00", tick=False) as frozen_time:
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
token_data = {**self.base_token_body, "code": code}
response = self.post("/oauth/token/", token_data)
@@ -2270,7 +2270,7 @@ class TestOAuthAPI(APIBaseTest):
response = self.client.get("/oauth/userinfo/", headers={"Authorization": "Bearer invalid_token"})
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_userinfo_endpoint_with_expired_token(self):
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
@@ -2879,7 +2879,7 @@ class TestOAuthAPI(APIBaseTest):
response_text = response.content.decode()
self.assertNotIn(access_token, response_text)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_refresh_token_reuse_within_grace_period(self):
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
@@ -2900,14 +2900,14 @@ class TestOAuthAPI(APIBaseTest):
new_access_token = first_refresh_response.json()["access_token"]
# Reuse old refresh token within grace period (2 minutes by default)
- with freeze_time("2025-01-01 00:01:00"):
+ with time_machine.travel("2025-01-01 00:01:00", tick=False):
reuse_response = self.post("/oauth/token/", refresh_data)
self.assertEqual(reuse_response.status_code, status.HTTP_200_OK)
self.assertEqual(reuse_response.json()["refresh_token"], new_refresh_token)
self.assertEqual(reuse_response.json()["access_token"], new_access_token)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_refresh_token_reuse_after_grace_period_revokes_token_family(self):
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
code = response.json()["redirect_to"].split("code=")[1].split("&")[0]
@@ -2928,7 +2928,7 @@ class TestOAuthAPI(APIBaseTest):
new_refresh_token = first_refresh_response.json()["refresh_token"]
# Try to reuse old refresh token after grace period (2 minutes by default)
- with freeze_time("2025-01-01 00:03:00"):
+ with time_machine.travel("2025-01-01 00:03:00", tick=False):
reuse_response = self.post("/oauth/token/", refresh_data)
self.assertEqual(reuse_response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(reuse_response.json()["error"], "invalid_grant")
@@ -2945,7 +2945,7 @@ class TestOAuthAPI(APIBaseTest):
# Some implementations may immediately revoke all tokens in the family,
# while others may only mark them as suspicious for future use
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_refresh_token_reuse_detection_query_count_is_constant_in_family_size(self):
# A rotating client grows its token family by one row per refresh, so a long-lived
# session can sit on a family of hundreds. Detecting reuse of a stale token must
@@ -2979,7 +2979,7 @@ class TestOAuthAPI(APIBaseTest):
# Present the stale token after the grace period: reuse detection fires and
# the whole family is revoked. The query count must not scale with family size.
- with freeze_time("2025-01-01 00:10:00"):
+ with time_machine.travel("2025-01-01 00:10:00", tick=False):
with self.assertNumQueries(FuzzyInt(12, 16)):
reuse_response = self.post("/oauth/token/", {**refresh_data, "refresh_token": stale_refresh_token})
self.assertEqual(reuse_response.status_code, status.HTTP_400_BAD_REQUEST)
@@ -2988,7 +2988,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(OAuthRefreshToken.objects.filter(token_family=family, revoked__isnull=True).count(), 0)
self.assertFalse(OAuthAccessToken.objects.filter(token=live_access_token).exists())
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_multiple_refresh_token_rotations_preserve_token_family(self):
# Get initial tokens
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
@@ -3022,7 +3022,7 @@ class TestOAuthAPI(APIBaseTest):
new_token_db = OAuthRefreshToken.objects.get(token=new_refresh_token)
self.assertEqual(new_token_db.token_family, token_family)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_concurrent_refresh_token_requests_within_grace_period(self):
# Get initial tokens
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
@@ -3044,7 +3044,7 @@ class TestOAuthAPI(APIBaseTest):
first_new_tokens = first_refresh_response.json()
# Simulate concurrent request with the same old refresh token within grace period
- with freeze_time("2025-01-01 00:00:30"): # 30 seconds later
+ with time_machine.travel("2025-01-01 00:00:30", tick=False): # 30 seconds later
concurrent_response = self.post("/oauth/token/", refresh_data)
self.assertEqual(concurrent_response.status_code, status.HTTP_200_OK)
@@ -3052,7 +3052,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(concurrent_response.json()["refresh_token"], first_new_tokens["refresh_token"])
self.assertEqual(concurrent_response.json()["access_token"], first_new_tokens["access_token"])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_refresh_token_reuse_with_different_client_fails(self):
# Get initial tokens for first application
response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)
@@ -3492,7 +3492,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(body["error"], "invalid_scope")
self.assertIn("experiment:read", body["error_description"])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_auto_approval_skipped_when_request_omits_required_scope(self):
# An existing token covering the (optional-only) request must not auto-approve
# below the required floor; the consent screen handles granting the full set.
@@ -3535,7 +3535,7 @@ class TestOAuthAPI(APIBaseTest):
rejected = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_authorization_rejected"]
self.assertEqual(rejected, [])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_token_endpoint_with_json_payload(self):
grant = OAuthGrant.objects.create(
application=self.confidential_application,
@@ -4001,7 +4001,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_introspection_with_expired_token(self):
access_token, _ = self._create_access_and_refresh_tokens()
@@ -4115,7 +4115,7 @@ class TestOAuthAPI(APIBaseTest):
data = response.json()
self.assertTrue(data["active"])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_self_introspection_with_expired_token_returns_inactive(self):
"""An expired token can self-introspect and gets active: false per RFC 7662."""
access_token, _ = self._create_access_and_refresh_tokens(scopes="openid")
@@ -4210,7 +4210,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertTrue(data["active"])
self.assertEqual(data["scope"], "openid user:read")
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_dcr_client_gets_extended_token_expiry(self):
self.public_application.is_dcr_client = True
self.public_application.save()
@@ -4286,7 +4286,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["expires_in"], 60 * 60)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_dcr_client_refresh_token_is_not_rotated(self):
self.public_application.is_dcr_client = True
self.public_application.save()
@@ -4342,7 +4342,7 @@ class TestOAuthAPI(APIBaseTest):
db_refresh_token = OAuthRefreshToken.objects.get(token=original_refresh_token)
self.assertIsNone(db_refresh_token.revoked)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_dcr_refresh_does_not_invalidate_previously_issued_access_tokens(self):
# Each refresh on a non-rotating client must issue a NEW OAuthAccessToken row, not
# overwrite the existing one. Overwriting causes a body/DB token mismatch under
@@ -4438,7 +4438,7 @@ class TestOAuthAPI(APIBaseTest):
("with_wrong_access_token_hint", "access_token"),
]
)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_dcr_refresh_token_revoke_sweeps_all_refresh_issued_access_tokens(self, _name, hint):
# Revoking a non-rotating refresh token via /oauth/revoke/ must invalidate every
# access_token issued from it, not just the original authorization_code-issued
@@ -4509,7 +4509,7 @@ class TestOAuthAPI(APIBaseTest):
"swept when their refresh token is revoked",
)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_dcr_refresh_token_revoke_from_other_client_does_not_sweep_session(self):
# RFC 7009 §2.1: the server verifies the token was issued to the requesting
# client. A different dynamic client presenting app A's refresh token must not
@@ -4584,7 +4584,7 @@ class TestOAuthAPI(APIBaseTest):
"that app's (user, application) access-token family",
)
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_dcr_non_rotating_refresh_racing_app_revoke_is_rejected(self):
# The non-rotating (DCR) refresh path passes the presented token via
# scope_source_refresh_token with source_refresh_token=None, so the mint-time revoke
@@ -4621,7 +4621,7 @@ class TestOAuthAPI(APIBaseTest):
},
).json()["refresh_token"]
- with freeze_time("2026-01-01 00:00:05"):
+ with time_machine.travel("2026-01-01 00:00:05", tick=False):
revoke_application_sessions(self.public_application)
refresh_response = self.post(
"/oauth/token/",
@@ -4638,7 +4638,7 @@ class TestOAuthAPI(APIBaseTest):
OAuthRefreshToken.objects.filter(application=self.public_application, revoked__isnull=True).exists()
)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_non_dcr_client_refresh_token_is_rotated(self):
self.public_application.is_dcr_client = False
self.public_application.save()
@@ -4719,7 +4719,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertTrue(response["Location"].startswith(f"{scheme}://posthog/callback"))
self.assertIn("error=unsupported_response_type", response["Location"])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(CLOUD_DEPLOYMENT="US", SITE_URL="https://us.posthog.com")
def test_token_response_includes_region_for_us_cloud(self):
grant = OAuthGrant.objects.create(
@@ -4741,7 +4741,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["posthog_region"], "us")
self.assertEqual(data["posthog_base_url"], "https://us.posthog.com")
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(CLOUD_DEPLOYMENT="EU", SITE_URL="https://eu.posthog.com")
def test_token_response_includes_region_for_eu_cloud(self):
grant = OAuthGrant.objects.create(
@@ -4763,7 +4763,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["posthog_region"], "eu")
self.assertEqual(data["posthog_base_url"], "https://eu.posthog.com")
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@override_settings(CLOUD_DEPLOYMENT=None)
def test_token_response_excludes_region_for_self_hosted(self):
grant = OAuthGrant.objects.create(
@@ -4799,7 +4799,7 @@ class TestOAuthAPI(APIBaseTest):
is_first_party=is_first_party,
)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_token_response_derives_scoped_teams_for_first_party_app(self):
app = self._create_first_party_app(slug="first-party-derive")
grant = OAuthGrant.objects.create(
@@ -4832,7 +4832,7 @@ class TestOAuthAPI(APIBaseTest):
access_token = OAuthAccessToken.objects.get(token=data["access_token"])
self.assertEqual(access_token.scoped_teams, [])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_token_response_does_not_derive_scoped_teams_for_third_party_app(self):
app = self._create_first_party_app(slug="third-party-no-derive", is_first_party=False)
grant = OAuthGrant.objects.create(
@@ -4862,7 +4862,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])
self.assertEqual(data["scoped_teams"], [])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_token_response_preserves_stored_scoped_teams_for_first_party_app(self):
app = self._create_first_party_app(slug="first-party-preserve")
grant = OAuthGrant.objects.create(
@@ -4892,7 +4892,7 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])
self.assertEqual(data["scoped_teams"], [self.team.pk])
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_first_party_app_gets_extended_token_expiry(self):
app = self._create_first_party_app(slug="first-party-ttl")
grant = OAuthGrant.objects.create(
@@ -4925,7 +4925,7 @@ class TestOAuthAPI(APIBaseTest):
expected_expiry = timezone.now() + timedelta(days=7)
self.assertLess(abs((access_token.expires - expected_expiry).total_seconds()), 60)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
def test_first_party_app_refreshed_token_keeps_extended_expiry_and_rotates(self):
app = self._create_first_party_app(slug="first-party-refresh-ttl")
client_secret = "first_party_first-party-refresh-ttl_client_secret"
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 5b2842fccf06..f06b15adb7b7 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -1,7 +1,7 @@
import json
import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, FuzzyInt, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
from unittest.mock import ANY, MagicMock, patch
@@ -435,7 +435,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
other_team = Team.objects.create(organization=self.organization)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
FileSystemViewLog.objects.create(
team=self.team,
user=self.user,
@@ -443,7 +443,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
ref=str(dashboard_recent_id),
)
- with freeze_time("2024-02-01T12:00:00Z"):
+ with time_machine.travel("2024-02-01T12:00:00Z", tick=False):
FileSystemViewLog.objects.create(
team=other_team,
user=self.user,
@@ -1113,7 +1113,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
"properties": [{"key": "$browser", "value": "Mac OS X"}],
}
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
# Pretend we cached something a while ago, but we won't have anything in the redis cache
insight = Insight.objects.create(
filters=Filter(data=filter_dict).to_dict(),
@@ -1122,7 +1122,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
)
DashboardTile.objects.create(dashboard=dashboard, insight=insight)
- with freeze_time("2020-01-20T13:00:01Z"):
+ with time_machine.travel("2020-01-20T13:00:01Z", tick=False):
response = self.dashboard_api.get_dashboard(dashboard.pk)
self.assertEqual(response["tiles"][0]["insight"]["result"], None)
@@ -1131,7 +1131,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
def test_refresh_cache(self):
dashboard = Dashboard.objects.create(team=self.team, name="dashboard")
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
# Pretend we cached something a while ago, but we won't have anything in the redis cache
item_default: Insight = Insight.objects.create(
query=browser_filtered_pageview_query(),
@@ -1153,7 +1153,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
)
DashboardTile.objects.create(dashboard=dashboard, insight=item_trends)
- with freeze_time("2020-01-20T13:00:01Z"):
+ with time_machine.travel("2020-01-20T13:00:01Z", tick=False):
response_data = self.dashboard_api.get_dashboard(dashboard.pk, query_params={"refresh": True})
self.assertEqual(response_data["tiles"][0]["is_cached"], False)
diff --git a/posthog/api/test/dashboards/test_dashboard_button_tiles.py b/posthog/api/test/dashboards/test_dashboard_button_tiles.py
index aaadce291be4..c7daf5e25cf5 100644
--- a/posthog/api/test/dashboards/test_dashboard_button_tiles.py
+++ b/posthog/api/test/dashboards/test_dashboard_button_tiles.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.test import override_settings
@@ -14,7 +14,7 @@ class TestDashboardButtonTiles(APIBaseTest):
super().setUp()
self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_can_create_button_tile(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
@@ -31,7 +31,7 @@ class TestDashboardButtonTiles(APIBaseTest):
assert tile["button_tile"]["style"] == "primary"
assert tile["button_tile"]["created_by"]["id"] == self.user.id
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_can_create_button_tile_with_pathname(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
@@ -43,7 +43,7 @@ class TestDashboardButtonTiles(APIBaseTest):
assert len(dashboard_json["tiles"]) == 1
assert dashboard_json["tiles"][0]["button_tile"]["url"] == "/dashboards"
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_can_create_button_tile_with_custom_placement_and_style(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
diff --git a/posthog/api/test/dashboards/test_dashboard_text_tiles.py b/posthog/api/test/dashboards/test_dashboard_text_tiles.py
index d65535c4af63..f7816357603d 100644
--- a/posthog/api/test/dashboards/test_dashboard_text_tiles.py
+++ b/posthog/api/test/dashboards/test_dashboard_text_tiles.py
@@ -1,7 +1,7 @@
import datetime
from typing import Any, Optional, Union
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest import mock
@@ -120,7 +120,7 @@ class TestDashboardTiles(APIBaseTest, QueryMatchingTest):
"xxs": {"x": "0", "y": "0", "w": "2", "h": "5"},
}
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_can_create_a_single_text_tile(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
@@ -135,7 +135,7 @@ class TestDashboardTiles(APIBaseTest, QueryMatchingTest):
@override_settings(IN_UNIT_TESTING=True)
def test_can_update_a_single_text_tile(self) -> None:
- with freeze_time("2022-04-01 12:45") as frozen_time:
+ with time_machine.travel("2022-04-01 12:45", tick=False) as frozen_time:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
dashboard_id, dashboard_json = self.dashboard_api.create_text_tile(dashboard_id, text="hello world")
@@ -144,7 +144,7 @@ class TestDashboardTiles(APIBaseTest, QueryMatchingTest):
assert len(dashboard_json["tiles"]) == 2
tile_ids = sorted([tile["id"] for tile in dashboard_json["tiles"]])
- frozen_time.tick(delta=datetime.timedelta(hours=10))
+ frozen_time.shift(datetime.timedelta(hours=10))
other_user = User.objects.create_and_join(organization=self.organization, email="", password="")
self.client.force_login(other_user)
updated_tile = {**dashboard_json["tiles"][0]}
@@ -306,7 +306,7 @@ class TestDashboardTiles(APIBaseTest, QueryMatchingTest):
assert dashboard_json["tiles"][0]["transparent_background"] is True
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_created_by_cannot_be_set_to_user_outside_organization(self) -> None:
other_org = Organization.objects.create(name="other org")
diff --git a/posthog/api/test/notebooks/test_notebook.py b/posthog/api/test/notebooks/test_notebook.py
index f15e88b74ddc..8946d055eec1 100644
--- a/posthog/api/test/notebooks/test_notebook.py
+++ b/posthog/api/test/notebooks/test_notebook.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
@@ -167,7 +167,7 @@ class TestNotebooks(APIBaseTest, QueryMatchingTest):
assert "short_id" in response_json
short_id = response_json["short_id"]
- with freeze_time("2022-01-02"):
+ with time_machine.travel("2022-01-02", tick=False):
response = self.client.patch(
f"/api/projects/{self.team.id}/notebooks/{short_id}",
{
diff --git a/posthog/api/test/test_activity_log.py b/posthog/api/test/test_activity_log.py
index 447422670209..299659aaf6c1 100644
--- a/posthog/api/test/test_activity_log.py
+++ b/posthog/api/test/test_activity_log.py
@@ -2,8 +2,7 @@ from datetime import timedelta
from typing import Any, Optional
from uuid import uuid4
-from freezegun import freeze_time
-from freezegun.api import FrozenDateTimeFactory, StepTickTimeFactory, TickingDateTimeFactory
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest.mock import patch
@@ -82,27 +81,27 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):
return response_json.get("id", None), response_json
def _create_and_edit_things(self):
- with freeze_time("2023-08-17") as frozen_time:
+ with time_machine.travel("2023-08-17", tick=False) as frozen_time:
# almost every change below will be more than 5 minutes apart
created_insights = []
for _ in range(0, 11):
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
insight_id, _ = self._create_insight({})
created_insights.append(insight_id)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
flag_one = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
_feature_flag_json_payload("one"),
).json()["id"]
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
flag_two = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
_feature_flag_json_payload("two"),
).json()["id"]
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
notebook_json = self.client.post(
f"/api/projects/{self.team.id}/notebooks/",
@@ -138,18 +137,18 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):
notebook_short_id: str,
notebook_version: int,
the_user: User,
- frozen_time: FrozenDateTimeFactory | StepTickTimeFactory | TickingDateTimeFactory,
+ frozen_time: time_machine.Traveller,
) -> int:
self.client.force_login(the_user)
for created_insight_id in created_insights[:7]:
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
update_response = self.client.patch(
f"/api/projects/{self.team.id}/insights/{created_insight_id}",
{"name": f"{created_insight_id}-insight-changed-by-{the_user.id}"},
)
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
assert (
self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_one}",
@@ -158,7 +157,7 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):
== status.HTTP_200_OK
)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
assert (
self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_two}",
@@ -167,7 +166,7 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):
== status.HTTP_200_OK
)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
# notebooks save while you're typing so, we get multiple activities per edit
for typed_text in [
"print",
@@ -176,7 +175,7 @@ class TestActivityLog(APIBaseTest, QueryMatchingTest):
"print('hello world again from ",
f"print('hello world again from {the_user.id}')",
]:
- frozen_time.tick(delta=timedelta(seconds=5))
+ frozen_time.shift(timedelta(seconds=5))
assert (
self.client.patch(
f"/api/projects/{self.team.id}/notebooks/{notebook_short_id}",
diff --git a/posthog/api/test/test_alert_15_minute_interval.py b/posthog/api/test/test_alert_15_minute_interval.py
index 3696372ddd5e..a2675404ea57 100644
--- a/posthog/api/test/test_alert_15_minute_interval.py
+++ b/posthog/api/test/test_alert_15_minute_interval.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock
@@ -109,7 +109,7 @@ class TestAlert15MinuteScheduling:
alert.schedule_restriction = None
alert.skip_weekend = False
- with freeze_time("2026-04-06T14:00:00Z"):
+ with time_machine.travel("2026-04-06T14:00:00Z", tick=False):
assert next_check_time(alert) == datetime(2026, 4, 6, 14, 15, 0, tzinfo=UTC)
def test_calculation_interval_to_order_raises_for_none(self) -> None:
diff --git a/posthog/api/test/test_alert_real_time_interval.py b/posthog/api/test/test_alert_real_time_interval.py
index 0a6ece20926e..20f25685ffde 100644
--- a/posthog/api/test/test_alert_real_time_interval.py
+++ b/posthog/api/test/test_alert_real_time_interval.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock
@@ -180,5 +180,5 @@ class TestAlertRealTimeScheduling:
alert.schedule_restriction = None
alert.skip_weekend = False
- with freeze_time("2026-04-06T14:00:00Z"):
+ with time_machine.travel("2026-04-06T14:00:00Z", tick=False):
assert next_check_time(alert) == datetime(2026, 4, 6, 14, 2, 0, tzinfo=UTC)
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 1c46b6922f69..c448526a7703 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime, timedelta
from typing import cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, MagicMock, patch
@@ -858,7 +858,7 @@ class TestTwoFactorAPI(APIBaseTest):
def test_2fa_expired(self):
self.user.totpdevice_set.create(name="default", key=random_hex(), digits=6) # type: ignore
- with freeze_time("2023-01-01T10:00:00"):
+ with time_machine.travel("2023-01-01T10:00:00", tick=False):
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
@@ -874,7 +874,7 @@ class TestTwoFactorAPI(APIBaseTest):
},
)
- with freeze_time("2023-01-01T10:30:00"):
+ with time_machine.travel("2023-01-01T10:30:00", tick=False):
response = self.client.post("/api/login/token", {"token": "abcdefg"})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
@@ -1550,7 +1550,7 @@ class TestPasswordResetAPI(APIBaseTest):
# Password reset request
- @freeze_time("2021-10-05T12:00:00")
+ @time_machine.travel("2021-10-05T12:00:00", tick=False)
@patch("posthoganalytics.capture")
def test_anonymous_user_can_request_password_reset(self, mock_capture):
set_instance_setting("EMAIL_HOST", "localhost")
@@ -1734,7 +1734,7 @@ class TestPasswordResetAPI(APIBaseTest):
def test_invalid_token_returns_error(self):
valid_token = password_reset_token_generator.make_token(self.user)
- with freeze_time(timezone.now() - timedelta(seconds=86_401)):
+ with time_machine.travel(timezone.now() - timedelta(seconds=86_401), tick=False):
# tokens expire after one day
expired_token = password_reset_token_generator.make_token(self.user)
@@ -1858,7 +1858,7 @@ class TestPasswordResetAPI(APIBaseTest):
def test_cant_reset_password_with_invalid_token(self):
valid_token = password_reset_token_generator.make_token(self.user)
- with freeze_time(timezone.now() - timedelta(seconds=86_401)):
+ with time_machine.travel(timezone.now() - timedelta(seconds=86_401), tick=False):
# tokens expire after one day
expired_token = password_reset_token_generator.make_token(self.user)
@@ -2029,7 +2029,7 @@ class TestPersonalAPIKeyAuthentication(APIBaseTest):
scopes=["*"],
)
- with freeze_time("2021-08-25T22:10:14.252"):
+ with time_machine.travel("2021-08-25T22:10:14.252", tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/", headers={"authorization": f"Bearer {personal_api_key}"}
)
@@ -2052,7 +2052,7 @@ class TestPersonalAPIKeyAuthentication(APIBaseTest):
scopes=["*"],
)
- with freeze_time("2022-08-25T22:00:14.252"):
+ with time_machine.travel("2022-08-25T22:00:14.252", tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/", headers={"authorization": f"Bearer {personal_api_key}"}
)
@@ -2075,7 +2075,7 @@ class TestPersonalAPIKeyAuthentication(APIBaseTest):
scopes=["*"],
)
- with freeze_time("2021-08-26T22:00:14.252"):
+ with time_machine.travel("2021-08-26T22:00:14.252", tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/", headers={"authorization": f"Bearer {personal_api_key}"}
)
@@ -2094,7 +2094,7 @@ class TestPersonalAPIKeyAuthentication(APIBaseTest):
label="X", user=self.user, secure_value=hash_key_value(personal_api_key), scopes=["*"]
)
- with freeze_time("2022-08-25T22:00:14.252"):
+ with time_machine.travel("2022-08-25T22:00:14.252", tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/", headers={"authorization": f"Bearer {personal_api_key}"}
)
@@ -2117,7 +2117,7 @@ class TestPersonalAPIKeyAuthentication(APIBaseTest):
scopes=["*"],
)
- with freeze_time("2021-08-25T21:14:14.252"):
+ with time_machine.travel("2021-08-25T21:14:14.252", tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/", headers={"authorization": f"Bearer {personal_api_key}"}
)
@@ -2139,7 +2139,7 @@ class TestPersonalAPIKeyAuthentication(APIBaseTest):
scopes=["*"],
)
- with freeze_time("2021-08-24T21:14:14.252"):
+ with time_machine.travel("2021-08-24T21:14:14.252", tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags/", headers={"authorization": f"Bearer {personal_api_key}"}
)
@@ -2155,15 +2155,15 @@ class TestTimeSensitivePermissions(APIBaseTest):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.patch("/api/organizations/@current", {"name": "new name"})
assert res.status_code == 200
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE - 100)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE - 100), tick=False):
res = self.client.patch("/api/organizations/@current", {"name": "new name"})
assert res.status_code == 200
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch("/api/organizations/@current", {"name": "new name"})
assert res.status_code == 403
assert res.json() == {
@@ -2178,15 +2178,15 @@ class TestTimeSensitivePermissions(APIBaseTest):
def test_user_after_timeout_modifications_require_reauthentication(self):
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.patch("/api/users/@me", {"first_name": "new name"})
assert res.status_code == 200
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE - 100)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE - 100), tick=False):
res = self.client.patch("/api/users/@me", {"first_name": "new name"})
assert res.status_code == 200
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch("/api/users/@me", {"first_name": "new name"})
assert res.status_code == 403
assert res.json() == {
@@ -2201,11 +2201,11 @@ class TestTimeSensitivePermissions(APIBaseTest):
def test_user_can_update_theme_without_recent_authentication(self):
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.patch("/api/users/@me", {"theme_mode": "dark"})
assert res.status_code == 200
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch("/api/users/@me", {"theme_mode": "light"})
assert res.status_code == 200
@@ -2221,14 +2221,14 @@ class TestTimeSensitivePermissions(APIBaseTest):
OrganizationMembership.objects.create(organization=new_org, user=self.user)
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.patch(
"/api/users/@me",
{"set_current_organization": str(new_org.id)},
)
assert res.status_code == 200
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch(
"/api/users/@me",
{"set_current_organization": str(self.organization.id)},
@@ -2244,13 +2244,13 @@ class TestTimeSensitivePermissions(APIBaseTest):
)
def test_user_can_update_non_sensitive_fields_without_recent_authentication(self, _name, payload):
now = datetime.now()
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch("/api/users/@me", payload, format="json")
assert res.status_code != 403, f"Field update should not require re-authentication, got: {res.json()}"
def test_user_can_update_hedgehog_config_without_recent_authentication(self):
now = datetime.now()
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch(
"/api/users/@me/hedgehog_config",
{"enabled": True, "color": "red"},
@@ -2263,7 +2263,7 @@ class TestTimeSensitivePermissions(APIBaseTest):
dashboard = Dashboard.objects.create(team=self.team, name="Test")
now = datetime.now()
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.post(
"/api/users/@me/scene_personalisation",
{"scene": "Person", "dashboard": dashboard.id},
@@ -2273,7 +2273,7 @@ class TestTimeSensitivePermissions(APIBaseTest):
def test_user_can_mark_a_product_intro_seen_without_recent_authentication(self):
now = datetime.now()
- with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
res = self.client.patch(
"/api/users/@me/product_intro_seen",
{"product_key": "posthog_ai_onboarding"},
diff --git a/posthog/api/test/test_cli_auth.py b/posthog/api/test/test_cli_auth.py
index 682389672160..938b0a61f93d 100644
--- a/posthog/api/test/test_cli_auth.py
+++ b/posthog/api/test/test_cli_auth.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -215,7 +215,7 @@ class TestCLIAuthAuthorizeEndpoint(APIBaseTest):
def test_authorization_rejects_expired_user_code(self):
"""Test that authorization fails with expired user code"""
# Wait for the code to expire
- with freeze_time(timezone.now() + timedelta(seconds=DEVICE_CODE_EXPIRY_SECONDS + 1)):
+ with time_machine.travel(timezone.now() + timedelta(seconds=DEVICE_CODE_EXPIRY_SECONDS + 1), tick=False):
response = self.client.post(
"/api/cli-auth/authorize/",
{"user_code": self.user_code, "project_id": self.team.id},
@@ -377,7 +377,7 @@ class TestCLIAuthPollEndpoint(APIBaseTest):
def test_poll_returns_expired_for_old_code(self):
"""Test that polling returns expired for old device codes"""
- with freeze_time(timezone.now() + timedelta(seconds=DEVICE_CODE_EXPIRY_SECONDS + 1)):
+ with time_machine.travel(timezone.now() + timedelta(seconds=DEVICE_CODE_EXPIRY_SECONDS + 1), tick=False):
response = self.client.post("/api/cli-auth/poll/", {"device_code": self.device_code})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/api/test/test_code_based_verification.py b/posthog/api/test/test_code_based_verification.py
index cb45b22dd99c..a338a4047a54 100644
--- a/posthog/api/test/test_code_based_verification.py
+++ b/posthog/api/test/test_code_based_verification.py
@@ -1,7 +1,7 @@
from contextlib import contextmanager
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -111,7 +111,7 @@ class TestCodeBasedVerificationAPI(APIBaseTest):
@pytest.mark.disable_mock_code_based_verifier
def test_expired_code_is_rejected(self):
- with freeze_time("2024-01-01T10:00:00") as frozen, enable_code_sending() as mock_send:
+ with time_machine.travel("2024-01-01T10:00:00", tick=False) as frozen, enable_code_sending() as mock_send:
code = self._trigger(mock_send)
frozen.move_to("2024-01-01T10:30:01") # > 30 minute TTL
response = self.client.post(VERIFY_URL, {"code": code})
@@ -135,7 +135,7 @@ class TestCodeBasedVerificationAPI(APIBaseTest):
@pytest.mark.disable_mock_code_based_verifier
def test_resend_issues_a_fresh_code_and_invalidates_the_previous_one(self):
- with freeze_time("2024-01-01T10:00:00") as frozen, enable_code_sending() as mock_send:
+ with time_machine.travel("2024-01-01T10:00:00", tick=False) as frozen, enable_code_sending() as mock_send:
first_code = self._trigger(mock_send)
frozen.move_to("2024-01-01T10:01:01") # past the 1/min resend throttle
self.assertEqual(self.client.post(RESEND_URL).status_code, status.HTTP_200_OK)
@@ -150,7 +150,7 @@ class TestCodeBasedVerificationAPI(APIBaseTest):
@pytest.mark.disable_mock_code_based_verifier
def test_resend_does_not_reset_the_failed_attempt_cap(self):
- with freeze_time("2024-01-01T10:00:00") as frozen, enable_code_sending() as mock_send:
+ with time_machine.travel("2024-01-01T10:00:00", tick=False) as frozen, enable_code_sending() as mock_send:
code = self._trigger(mock_send)
wrong = "000000" if code != "000000" else "111111"
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 97c574cb7da4..982c4bc0454d 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -2,7 +2,7 @@ import json
from datetime import datetime, timedelta
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -2736,7 +2736,7 @@ [email protected],
created_at_by_label = {"a": "2021-01-02", "b": "2021-01-04", "c": "2021-01-01", "d": "2021-01-03"}
uuid_by_label = {}
for label in ["a", "b", "c", "d"]: # insertion order → ascending id
- with freeze_time(created_at_by_label[label]):
+ with time_machine.travel(created_at_by_label[label], tick=False):
person = create_person(team=self.team, distinct_ids=[label], properties={"$os": "Chrome"})
uuid_by_label[label] = str(person.uuid)
diff --git a/posthog/api/test/test_csp.py b/posthog/api/test/test_csp.py
index 83332af52c75..337c64bebf54 100644
--- a/posthog/api/test/test_csp.py
+++ b/posthog/api/test/test_csp.py
@@ -2,7 +2,7 @@ import json
from datetime import datetime
from html import escape
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.test import TestCase
@@ -273,7 +273,7 @@ class TestCSPModule(TestCase):
assert event["properties"]["$session_id"] == "test-session"
assert event["properties"]["$csp_version"] == "1"
- @freeze_time("2023-01-01 12:00:00")
+ @time_machine.travel("2023-01-01 12:00:00", tick=False)
def test_sample_csp_report(self):
trunc_date_iso_format = datetime(2023, 1, 1, 12, 0, 0).isoformat()
@@ -581,13 +581,13 @@ class TestCSPModule(TestCase):
}
# First minute
- with freeze_time("2023-01-01 12:00:00"):
+ with time_machine.travel("2023-01-01 12:00:00", tick=False):
properties_copy1 = properties.copy()
sample_csp_report(properties_copy1, 0.5, add_metadata=True)
sampling_key1 = properties_copy1.get("csp_sampling_key")
# Second minute
- with freeze_time("2023-01-01 12:01:00"):
+ with time_machine.travel("2023-01-01 12:01:00", tick=False):
properties_copy2 = properties.copy()
sample_csp_report(properties_copy2, 0.5, add_metadata=True)
sampling_key2 = properties_copy2.get("csp_sampling_key")
@@ -601,7 +601,7 @@ class TestCSPModule(TestCase):
assert sampling_key1 is not None and "https://example.com/page" in sampling_key1
assert sampling_key2 is not None and "https://example.com/page" in sampling_key2
- @freeze_time("2023-01-01 12:00:00")
+ @time_machine.travel("2023-01-01 12:00:00", tick=False)
def test_sampling_consistency_within_same_minute(self):
properties1 = {
"document_url": "https://example.com/page",
@@ -642,7 +642,7 @@ class TestCSPModule(TestCase):
]
for url, time_string, expected_result, expected_hash_mod in deterministic_test_cases:
- with freeze_time(time_string):
+ with time_machine.travel(time_string, tick=False):
properties = {"document_url": url, "effective_directive": "script-src"}
result = sample_csp_report(properties, 0.5)
assert result == expected_result, (
@@ -661,7 +661,7 @@ class TestCSPModule(TestCase):
sampled_out_results = []
for time_string, expected_result in time_sampling_pairs:
- with freeze_time(time_string):
+ with time_machine.travel(time_string, tick=False):
properties = {"document_url": url, "effective_directive": "script-src"}
result = sample_csp_report(properties, 0.5)
assert result == expected_result, f"Failed deterministic test for {url} at {time_string}"
@@ -676,7 +676,7 @@ class TestCSPModule(TestCase):
assert len(sampled_out_results) > 0, f"URL {url} should be sampled OUT at least once"
# Verify consistency within the same minute (time component doesn't change within a minute)
- with freeze_time("2023-01-01 12:00:00"):
+ with time_machine.travel("2023-01-01 12:00:00", tick=False):
properties1 = {"document_url": "https://example.com/test", "effective_directive": "script-src"}
result1 = sample_csp_report(properties1.copy(), 0.5)
result2 = sample_csp_report(properties1.copy(), 0.5)
diff --git a/posthog/api/test/test_element.py b/posthog/api/test/test_element.py
index 5ed058114a8d..4141529bc22e 100644
--- a/posthog/api/test/test_element.py
+++ b/posthog/api/test/test_element.py
@@ -1,7 +1,7 @@
import json
-from datetime import timedelta
+from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -242,7 +242,7 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
event_start = "2012-01-14T03:21:34.000Z"
query_time = "2012-01-14T08:21:34.000Z"
- with freeze_time(event_start) as frozen_time:
+ with time_machine.travel(event_start, tick=False) as frozen_time:
elements = [
Element(
tag_name="a",
@@ -259,7 +259,7 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
]
_create_event( # 3 am but included because date_from is set to start of day
- timestamp=frozen_time(),
+ timestamp=datetime.now(),
team=self.team,
elements=elements,
event="$autocapture",
@@ -267,10 +267,10 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties={"$current_url": "http://example.com/demo"},
)
- frozen_time.tick(delta=timedelta(hours=10))
+ frozen_time.shift(timedelta(hours=10))
_create_event( # included
- timestamp=frozen_time(),
+ timestamp=datetime.now(),
team=self.team,
elements=elements,
event="$autocapture",
@@ -278,7 +278,7 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties={"$current_url": "http://example.com/demo"},
)
- with freeze_time(query_time):
+ with time_machine.travel(query_time, tick=False):
# the UI doesn't allow you to choose time, so query should always be from start of day
response = self.client.get(f"/api/element/stats/?paginate_response=true&date_from={query_time}")
self.assertEqual(response.status_code, status.HTTP_200_OK)
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.py
index a1b04bac4dde..c33dbf81f651 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -3,7 +3,7 @@ from datetime import datetime
from urllib.parse import unquote, urlencode
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -217,7 +217,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
cohort1.calculate_people_ch(pending_version=0)
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True): # Normally this is False in tests
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self.client.get(
f"/api/projects/{self.team.id}/events/?properties=%s"
% (json.dumps([{"key": "id", "value": cohort1.id, "type": "cohort"}]))
@@ -277,7 +277,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert nonexistent_uuid.status_code == 200
assert len(nonexistent_uuid.json()["results"]) == 0
- @freeze_time("2020-01-10")
+ @time_machine.travel("2020-01-10", tick=False)
def test_event_column_values(self):
person1 = _create_person(
properties={"email": "[email protected]"},
@@ -362,7 +362,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["random_prop"])
@snapshot_clickhouse_queries
def test_event_property_values(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_event(
distinct_id="bla",
event="random event",
@@ -373,7 +373,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2020-01-20 20:00:00"):
+ with time_machine.travel("2020-01-20 20:00:00", tick=False):
_create_event(
distinct_id="bla",
event="random event",
@@ -490,7 +490,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
("refresh_async", "refresh=async", "RECENT_CACHE_CALCULATE_ASYNC_IF_STALE"),
]
)
- @freeze_time("2020-01-10")
+ @time_machine.travel("2020-01-10", tick=False)
def test_event_property_values_refresh(self, _name, param, expected_mode_name):
from posthog.hogql_queries.property_values_query_runner import PropertyValuesQueryResponse
from posthog.hogql_queries.query_runner import ExecutionMode
@@ -513,7 +513,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert "analytics_props" in kwargs
@also_test_with_materialized_columns(["test_prop"])
- @freeze_time("2020-01-20 20:00:00")
+ @time_machine.travel("2020-01-20 20:00:00", tick=False)
@snapshot_clickhouse_queries
def test_event_property_values_without_hidden_properties(self):
# Create events with properties first
@@ -546,7 +546,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert len(response["results"]) == 3
@also_test_with_materialized_columns(["hidden_prop", "visible_prop"])
- @freeze_time("2020-01-20 20:00:00")
+ @time_machine.travel("2020-01-20 20:00:00", tick=False)
@snapshot_clickhouse_queries
def test_event_property_values_with_hidden_properties(self):
# Create events with both hidden and visible properties
@@ -587,7 +587,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert "also_visible" in visible_keys
def test_property_values_with_property_filters(self):
- with freeze_time("2020-01-20 20:00:00"):
+ with time_machine.travel("2020-01-20 20:00:00", tick=False):
_create_event(
distinct_id="bla",
event="random event",
@@ -633,7 +633,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert response["results"][0]["name"] == "both filters"
def test_property_values_with_property_filters_error_handling(self):
- with freeze_time("2020-01-20 20:00:00"):
+ with time_machine.travel("2020-01-20 20:00:00", tick=False):
_create_event(
distinct_id="bla",
event="random event",
@@ -693,15 +693,15 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["2", "some-random-uid"],
)
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
event1_uuid = _create_event(team=self.team, event="sign up", distinct_id="2")
- with freeze_time("2020-01-8"):
+ with time_machine.travel("2020-01-8", tick=False):
event2_uuid = _create_event(team=self.team, event="sign up", distinct_id="2")
- with freeze_time("2020-01-7"):
+ with time_machine.travel("2020-01-7", tick=False):
event3_uuid = _create_event(team=self.team, event="random other event", distinct_id="2")
# with relative values
- with freeze_time("2020-01-11T12:03:03.829294Z"):
+ with time_machine.travel("2020-01-11T12:03:03.829294Z", tick=False):
response = self.client.get(f"/api/projects/{self.team.id}/events/?after=4d&before=1d").json()
assert len(response["results"]) == 2
@@ -736,7 +736,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert response["results"][1]["id"] == event3_uuid
def test_pagination(self):
- with freeze_time("2021-10-10T12:03:03.829294Z"):
+ with time_machine.travel("2021-10-10T12:03:03.829294Z", tick=False):
_create_person(team=self.team, distinct_ids=["1"])
for idx in range(0, 250):
_create_event(
@@ -779,7 +779,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert page3["next"] is None
def test_pagination_bounded_date_range(self):
- with freeze_time("2021-10-10T12:03:03.829294Z"):
+ with time_machine.travel("2021-10-10T12:03:03.829294Z", tick=False):
_create_person(team=self.team, distinct_ids=["1"])
now = timezone.now() - relativedelta(months=11)
after = (now).astimezone(ZoneInfo("UTC")).isoformat()
@@ -890,7 +890,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
def test_list_events_returns_utc_timestamp_when_project_timezone_is_not_utc(self):
self.team.timezone = "Africa/Algiers"
self.team.save()
- with freeze_time("2026-06-30T20:45:00Z"):
+ with time_machine.travel("2026-06-30T20:45:00Z", tick=False):
_create_event(
team=self.team,
event="watched movie",
@@ -923,7 +923,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert response.json()["properties"] == {"key": "test_val"}
def test_events_in_future(self):
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_event(
team=self.team,
event="5th action",
@@ -931,14 +931,14 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
properties={"$os": "Windows 95"},
)
# Don't show events more than 5 seconds in the future
- with freeze_time("2012-01-15T04:01:44.000Z"):
+ with time_machine.travel("2012-01-15T04:01:44.000Z", tick=False):
_create_event(
team=self.team,
event="5th action",
distinct_id="2",
properties={"$os": "Windows 95"},
)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
response = self.client.get(f"/api/projects/{self.team.id}/events/").json()
assert len(response["results"]) == 1
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index 50bf090ab4ec..a84e711d66a3 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from typing import Any, Optional, cast
from uuid import uuid4
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, patch
@@ -26,7 +26,7 @@ from posthog.models import ActivityLog, EventDefinition, Organization, Tag, Team
from products.actions.backend.models.action import Action
-@freeze_time("2020-01-02")
+@time_machine.travel("2020-01-02", tick=False)
class TestEventDefinitionAPI(APIBaseTest):
demo_team: Team = None # type: ignore
@@ -759,7 +759,7 @@ class TestCreateEventDefinitionsSql(SimpleTestCase):
class TestEventDefinitionExcludeStale(APIBaseTest):
"""Stale filter tests need real wall-clock times so the Postgres NOW() comparison
in `exclude_stale` matches the fixture last_seen_at values. The other test class is
- wrapped in freeze_time which Postgres NOW() does not respect."""
+ wrapped in a frozen clock which Postgres NOW() does not respect."""
@parameterized.expand(
[
diff --git a/posthog/api/test/test_ingestion_warnings.py b/posthog/api/test/test_ingestion_warnings.py
index 5f03d53d486e..0d118a6dbce3 100644
--- a/posthog/api/test/test_ingestion_warnings.py
+++ b/posthog/api/test/test_ingestion_warnings.py
@@ -1,7 +1,7 @@
import json
from math import floor
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from rest_framework import status
@@ -94,7 +94,7 @@ class TestIngestionWarningsAPI(ClickhouseTestMixin, APIBaseTest):
timestamp="2021-12-01T00:00:00Z",
)
- @freeze_time("2021-12-04T19:20:00Z")
+ @time_machine.travel("2021-12-04T19:20:00Z", tick=False)
def test_ingestion_warnings_api(self):
response = self.client.get(f"/api/projects/{self.team.pk}/ingestion_warnings")
assert response.status_code == status.HTTP_200_OK
@@ -163,7 +163,7 @@ class TestIngestionWarningsAPI(ClickhouseTestMixin, APIBaseTest):
}
)
- @freeze_time("2021-12-04T19:20:00Z")
+ @time_machine.travel("2021-12-04T19:20:00Z", tick=False)
def test_ingestion_warnings_api_search_by_type(self):
response = self.client.get(f"/api/projects/{self.team.pk}/ingestion_warnings?q=another_type")
assert response.status_code == status.HTTP_200_OK
@@ -185,7 +185,7 @@ class TestIngestionWarningsAPI(ClickhouseTestMixin, APIBaseTest):
]
}
- @freeze_time("2021-12-04T19:20:00Z")
+ @time_machine.travel("2021-12-04T19:20:00Z", tick=False)
def test_ingestion_warnings_api_search_by_id(self):
response = self.client.get(f"/api/projects/{self.team.pk}/ingestion_warnings?q=x-uuid")
assert response.status_code == status.HTTP_200_OK
diff --git a/posthog/api/test/test_ingestion_warnings_v2.py b/posthog/api/test/test_ingestion_warnings_v2.py
index aedd0ffcc0ed..93783cb2a6c7 100644
--- a/posthog/api/test/test_ingestion_warnings_v2.py
+++ b/posthog/api/test/test_ingestion_warnings_v2.py
@@ -1,6 +1,6 @@
import json
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from parameterized import parameterized
@@ -29,7 +29,7 @@ def create_warning(team_id: int, type: str, timestamp: str, details: dict, sourc
)
-@freeze_time("2026-07-07T12:00:00.000Z")
+@time_machine.travel("2026-07-07T12:00:00.000Z", tick=False)
class TestIngestionWarningsV2API(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/test/test_log_entries.py b/posthog/api/test/test_log_entries.py
index a583235a7cc8..6d586808f5aa 100644
--- a/posthog/api/test/test_log_entries.py
+++ b/posthog/api/test/test_log_entries.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from rest_framework import status
@@ -72,7 +72,7 @@ class TestLogEntries(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"results": [],
}
- @freeze_time("2023-09-23 12:00:00")
+ @time_machine.travel("2023-09-23 12:00:00", tick=False)
def test_returns_log_entries(self):
"""Test the simple case of fetching a log entry."""
self.create_log_for_function(level="info", timestamp="2023-09-22 01:00:00")
diff --git a/posthog/api/test/test_my_notifications.py b/posthog/api/test/test_my_notifications.py
index 26d88770957e..753efe68077e 100644
--- a/posthog/api/test/test_my_notifications.py
+++ b/posthog/api/test/test_my_notifications.py
@@ -1,8 +1,7 @@
from datetime import timedelta
from typing import Any, Optional
-from freezegun import freeze_time
-from freezegun.api import FrozenDateTimeFactory, StepTickTimeFactory, TickingDateTimeFactory
+import time_machine
from posthog.test.base import APIBaseTest, FuzzyInt, QueryMatchingTest
from rest_framework import status
@@ -71,30 +70,30 @@ class TestMyNotifications(APIBaseTest, QueryMatchingTest):
return response_json.get("id", None), response_json
def _create_and_edit_things(self):
- with freeze_time("2023-08-17") as frozen_time:
+ with time_machine.travel("2023-08-17", tick=False) as frozen_time:
# add microsecond offset to test if timestamp precision mismatches are handled correctly
- frozen_time.tick(delta=timedelta(microseconds=123))
+ frozen_time.shift(timedelta(microseconds=123))
# almost every change below will be more than 5 minutes apart
created_insights = []
for _ in range(0, 11):
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
insight_id, _ = self._create_insight({})
created_insights.append(insight_id)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
flag_one = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
_feature_flag_json_payload("one"),
).json()["id"]
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
flag_two = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
_feature_flag_json_payload("two"),
).json()["id"]
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
notebook_json = self.client.post(
f"/api/projects/{self.team.id}/notebooks/",
@@ -130,18 +129,18 @@ class TestMyNotifications(APIBaseTest, QueryMatchingTest):
notebook_short_id: str,
notebook_version: int,
the_user: User,
- frozen_time: FrozenDateTimeFactory | StepTickTimeFactory | TickingDateTimeFactory,
+ frozen_time: time_machine.Traveller,
) -> int:
self.client.force_login(the_user)
for created_insight_id in created_insights[:7]:
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
update_response = self.client.patch(
f"/api/projects/{self.team.id}/insights/{created_insight_id}",
{"name": f"{created_insight_id}-insight-changed-by-{the_user.id}"},
)
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
assert (
self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_one}",
@@ -150,7 +149,7 @@ class TestMyNotifications(APIBaseTest, QueryMatchingTest):
== status.HTTP_200_OK
)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
assert (
self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_two}",
@@ -159,7 +158,7 @@ class TestMyNotifications(APIBaseTest, QueryMatchingTest):
== status.HTTP_200_OK
)
- frozen_time.tick(delta=timedelta(minutes=6))
+ frozen_time.shift(timedelta(minutes=6))
# notebooks save while you're typing so, we get multiple activities per edit
for typed_text in [
"print",
@@ -168,7 +167,7 @@ class TestMyNotifications(APIBaseTest, QueryMatchingTest):
"print('hello world again from ",
f"print('hello world again from {the_user.id}')",
]:
- frozen_time.tick(delta=timedelta(seconds=5))
+ frozen_time.shift(timedelta(seconds=5))
assert (
self.client.patch(
f"/api/projects/{self.team.id}/notebooks/{notebook_short_id}",
diff --git a/posthog/api/test/test_organization_domain.py b/posthog/api/test/test_organization_domain.py
index 6efe28da9363..a18acc91bf47 100644
--- a/posthog/api/test/test_organization_domain.py
+++ b/posthog/api/test/test_organization_domain.py
@@ -2,7 +2,7 @@ import datetime
from datetime import timedelta
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import ANY, patch
@@ -208,7 +208,7 @@ class TestOrganizationDomainsAPI(APIBaseTest):
]
)
- with freeze_time("2021-08-08T20:20:08Z"):
+ with time_machine.travel("2021-08-08T20:20:08Z", tick=False):
response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify")
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()
@@ -234,7 +234,7 @@ class TestOrganizationDomainsAPI(APIBaseTest):
mock_dns_query.return_value.resolve.side_effect = dns.resolver.NoAnswer()
- with freeze_time("2021-10-10T10:10:10Z"):
+ with time_machine.travel("2021-10-10T10:10:10Z", tick=False):
with self.is_cloud(True):
response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify")
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -255,7 +255,7 @@ class TestOrganizationDomainsAPI(APIBaseTest):
mock_dns_query.return_value.resolve.side_effect = dns.resolver.NXDOMAIN()
- with freeze_time("2021-10-10T10:10:10Z"):
+ with time_machine.travel("2021-10-10T10:10:10Z", tick=False):
with self.is_cloud(True):
response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify")
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -286,7 +286,7 @@ class TestOrganizationDomainsAPI(APIBaseTest):
]
)
- with freeze_time("2021-10-10T10:10:10Z"):
+ with time_machine.travel("2021-10-10T10:10:10Z", tick=False):
with self.is_cloud(True):
response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify")
self.assertEqual(response.status_code, status.HTTP_200_OK)
diff --git a/posthog/api/test/test_organization_invites.py b/posthog/api/test/test_organization_invites.py
index 1e8596725fd5..8e8d77f2481a 100644
--- a/posthog/api/test/test_organization_invites.py
+++ b/posthog/api/test/test_organization_invites.py
@@ -1,7 +1,7 @@
import random
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, patch
@@ -844,12 +844,12 @@ class TestOrganizationInvitesAPI(APIBaseTest):
self.assertEqual(invite["target_email"], email)
self.assertEqual(invite["private_project_access"], [])
- @freeze_time("2024-01-10")
+ @time_machine.travel("2024-01-10", tick=False)
def test_combine_pending_invites_with_expired_invites(self):
# Create an expired invite
- with freeze_time("2023-01-05"):
+ with time_machine.travel("2023-01-05", tick=False):
OrganizationInvite.objects.create(
organization=self.organization,
target_email=email,
@@ -1974,7 +1974,7 @@ class TestOrganizationInviteRateLimits(APIBaseTest):
@patch("posthog.rate_limit.OrganizationInviteBurstThrottle.rate", new="2/hour")
def test_burst_bucket_resets_after_window(self, _rate_limit_enabled_mock, _time_sensitive_mock):
base_time = now()
- with freeze_time(base_time):
+ with time_machine.travel(base_time, tick=False):
for i in range(2):
response = self.client.post(
"/api/organizations/@current/invites/",
@@ -1987,7 +1987,7 @@ class TestOrganizationInviteRateLimits(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
- with freeze_time(base_time + timedelta(hours=1, seconds=1)):
+ with time_machine.travel(base_time + timedelta(hours=1, seconds=1), tick=False):
response = self.client.post(
"/api/organizations/@current/invites/",
{"target_email": "[email protected]"},
@@ -2001,14 +2001,14 @@ class TestOrganizationInviteRateLimits(APIBaseTest):
# Space requests more than 1 hour apart (defeating any burst bucket)
# but still well within the 24h sustained window.
for i in range(3):
- with freeze_time(base_time + timedelta(hours=2 * i)):
+ with time_machine.travel(base_time + timedelta(hours=2 * i), tick=False):
response = self.client.post(
"/api/organizations/@current/invites/",
{"target_email": f"sustained_{i}@posthog.com"},
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- with freeze_time(base_time + timedelta(hours=8)):
+ with time_machine.travel(base_time + timedelta(hours=8), tick=False):
response = self.client.post(
"/api/organizations/@current/invites/",
{"target_email": "[email protected]"},
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index a38b896a6966..a9eaeaf6bd3f 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -3,7 +3,7 @@ from typing import Optional, cast
from uuid import UUID, uuid4
import pytest
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -378,7 +378,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
("refresh_async", "refresh=async", "RECENT_CACHE_CALCULATE_ASYNC_IF_STALE"),
]
)
- @freeze_time("2020-01-10")
+ @time_machine.travel("2020-01-10", tick=False)
def test_person_property_values_refresh(self, _name, param, expected_mode_name):
from posthog.hogql_queries.property_values_query_runner import PropertyValuesQueryResponse
from posthog.hogql_queries.query_runner import ExecutionMode
@@ -530,7 +530,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["results"], [])
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_delete_person(self):
person = _create_person(
team=self.team,
@@ -591,7 +591,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)[0][0]
self.assertEqual(ch_events, 3)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_delete_person_and_events(self):
person = _create_person(
team=self.team,
@@ -620,7 +620,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(async_deletion.key, str(person.uuid))
self.assertIsNone(async_deletion.delete_verified_at)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
@mock.patch("posthog.api.person.queue_person_recording_deletion")
def test_delete_person_and_recordings(self, _mock_queue_delete):
person = _create_person(
@@ -636,7 +636,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.content, b"") # Empty response
self.assertIsNone(get_person_by_uuid(self.team.pk, str(person.uuid)))
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
@mock.patch("posthog.api.person.queue_person_recording_deletion")
def test_delete_person_and_recordings_and_events(self, _mock_queue_delete):
person = _create_person(
@@ -667,7 +667,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(async_deletion.key, str(person.uuid))
self.assertIsNone(async_deletion.delete_verified_at)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_bulk_delete_ids(self):
person = _create_person(
team=self.team,
@@ -714,7 +714,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(async_deletion.key, str(person.uuid))
self.assertIsNone(async_deletion.delete_verified_at)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_bulk_delete_distinct_id(self):
person = _create_person(
team=self.team,
@@ -861,7 +861,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(data["deletion_errors"], [])
self.assertEqual(AsyncDeletion.objects.filter(team_id=self.team.id).count(), 0)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_deletion_status_lists_pending_deletions(self):
person = _create_person(
team=self.team,
@@ -883,7 +883,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(data["results"][0]["status"], "pending")
self.assertIsNone(data["results"][0]["delete_verified_at"])
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_deletion_status_filters_by_status(self):
person1 = _create_person(
team=self.team,
@@ -928,7 +928,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
data = response.json()
self.assertEqual(data["count"], 2)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_deletion_status_filters_by_person_uuid(self):
person1 = _create_person(
team=self.team,
@@ -1032,7 +1032,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# But async deletion should be scheduled
self.assertEqual(AsyncDeletion.objects.filter(team_id=self.team.id).count(), 1)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_split_people_keep_props(self) -> None:
# created first
person1 = _create_person(
@@ -1836,7 +1836,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(pdi_distinct_id, "deleted_user")
self.assertEqual(pdi_is_deleted, 0)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_patch_user_property_activity(self):
person = _create_person(
team=self.team,
@@ -1944,7 +1944,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
response_include_total = self.client.get("/api/person/?limit=10&include_total").json()
self.assertEqual(response_include_total["count"], 20) # With `include_total`, the total count is returned too
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_pagination_no_gaps_or_duplicates_when_created_at_is_tied(self):
# Bulk-created persons can share an identical created_at, so the `created_at DESC` ordering
# falls to the `id DESC` tiebreaker. Page boundaries must stay disjoint and complete: every
@@ -2025,7 +2025,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.maxDiff = None
self.assertCountEqual(activity, expected)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_delete_events_only(self):
person = _create_person(
team=self.team,
@@ -2053,7 +2053,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert async_deletion.key == str(person.uuid)
assert async_deletion.delete_verified_at is None
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_delete_person_events_not_found(self):
# Use a valid UUID that doesn't exist in the database
non_existent_uuid = "11111111-1111-1111-1111-111111111111"
diff --git a/posthog/api/test/test_properties_timeline.py b/posthog/api/test/test_properties_timeline.py
index 7d86a2cb3212..bfc760f35662 100644
--- a/posthog/api/test/test_properties_timeline.py
+++ b/posthog/api/test/test_properties_timeline.py
@@ -3,7 +3,7 @@ import uuid
import random
from typing import Optional
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -540,7 +540,7 @@ class TestPersonPropertiesTimeline(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-09T21:37:00Z"):
+ with time_machine.travel("2020-01-09T21:37:00Z", tick=False):
timeline = self._get_timeline_result(
events=[
{
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index 543927b8bf67..9cce7763f243 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -1,6 +1,6 @@
import json
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -96,7 +96,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_select_hogql_expressions(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -109,21 +109,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -132,7 +132,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = EventsQuery(
select=[
"properties.key",
@@ -218,7 +218,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["key"])
@snapshot_clickhouse_queries
def test_hogql_property_filter(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -231,21 +231,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -254,7 +254,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = EventsQuery(
select=[
"event",
@@ -283,7 +283,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(event_properties=["key", "path"])
@snapshot_clickhouse_queries
def test_event_property_filter(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -296,21 +296,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -319,7 +319,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = EventsQuery(
select=[
"event",
@@ -357,7 +357,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(event_properties=["key"], person_properties=["email"])
@snapshot_clickhouse_queries
def test_person_property_filter(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -370,21 +370,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -393,7 +393,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = EventsQuery(
select=[
"event",
@@ -417,7 +417,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
def test_safe_clickhouse_error_passed_through(self):
query = {"kind": "EventsQuery", "select": ["timestamp + 'string'"]}
- with freeze_time("2024-10-16 22:10:29.691212"):
+ with time_machine.travel("2024-10-16 22:10:29.691212", tick=False):
response_post = self.client.post(f"/api/environments/{self.team.id}/query/", {"query": query})
self.assertEqual(response_post.status_code, status.HTTP_400_BAD_REQUEST)
@@ -465,7 +465,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(event_properties=["key", "path"])
@snapshot_clickhouse_queries
def test_property_filter_aggregations(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -478,21 +478,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -501,7 +501,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = EventsQuery(select=["properties.key", "count()"])
response = self.client.post(f"/api/environments/{self.team.id}/query/", {"query": query.dict()}).json()
self.assertEqual(len(response["results"]), 3)
@@ -512,7 +512,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_select_event_person(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
person = _create_person(
properties={"name": "Tom", "email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -525,21 +525,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -548,7 +548,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = EventsQuery(
select=["event", "person", "person -- P"],
orderBy=["timestamp DESC"] if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else None,
@@ -570,7 +570,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_events_query_all_time_date(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"name": "Tom", "email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -583,21 +583,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2021-01-10 12:11:00"):
+ with time_machine.travel("2021-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2022-01-10 12:12:00"):
+ with time_machine.travel("2022-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2023-01-10 12:13:00"):
+ with time_machine.travel("2023-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -606,7 +606,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2023-01-12 12:14:00"):
+ with time_machine.travel("2023-01-12 12:14:00", tick=False):
query = EventsQuery(select=["event"], after="all")
response = self.client.post(f"/api/environments/{self.team.id}/query/", {"query": query.dict()}).json()
self.assertEqual(len(response["results"]), 4)
@@ -622,7 +622,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(event_properties=["key"])
@snapshot_clickhouse_queries
def test_full_hogql_query(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -635,21 +635,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -658,7 +658,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = HogQLQuery(query="select event, distinct_id, properties.key from events order by timestamp")
api_response = self.client.post(f"/api/environments/{self.team.id}/query/", {"query": query.dict()}).json()
response = CachedHogQLQueryResponse.model_validate(api_response)
@@ -713,7 +713,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@patch("posthog.hogql.constants.MAX_SELECT_RETURNED_ROWS", 15)
def test_full_hogql_query_limit(self, MAX_SELECT_RETURNED_ROWS=15, DEFAULT_RETURNED_ROWS=10):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
for _ in range(20):
_create_event(
team=self.team,
@@ -723,7 +723,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
response = process_query_dict(
team=self.team,
query_json={
@@ -738,7 +738,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 15)
def test_full_hogql_query_limit_exported(self, CSV_EXPORT_LIMIT=15, DEFAULT_RETURNED_ROWS=10):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
for _ in range(20):
_create_event(
team=self.team,
@@ -748,7 +748,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
response = process_query_dict(
team=self.team,
query_json={
@@ -803,7 +803,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@patch("posthog.hogql.constants.MAX_SELECT_RETURNED_ROWS", 15)
def test_full_events_query_limit(self, MAX_SELECT_RETURNED_ROWS=15, DEFAULT_RETURNED_ROWS=10):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
for _ in range(20):
_create_event(
team=self.team,
@@ -813,7 +813,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
response = process_query_dict(
team=self.team,
query_json={
@@ -830,7 +830,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 15)
def test_full_events_query_limit_exported(self, CSV_EXPORT_LIMIT=15, DEFAULT_RETURNED_ROWS=10):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
for _ in range(20):
_create_event(
team=self.team,
@@ -840,7 +840,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
response = process_query_dict(
team=self.team,
query_json={
@@ -857,7 +857,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
def test_property_definition_annotation_does_not_break_things(self):
PropertyDefinition.objects.create(team=self.team, name="$browser", property_type=PropertyType.String)
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
response = process_query_dict(
team=self.team,
query_json={
@@ -899,7 +899,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_full_hogql_query_view(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -912,21 +912,21 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="2",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:12:00"):
+ with time_machine.travel("2020-01-10 12:12:00", tick=False):
_create_event(
team=self.team,
event="sign out",
distinct_id="3",
properties={"key": "test_val2"},
)
- with freeze_time("2020-01-10 12:13:00"):
+ with time_machine.travel("2020-01-10 12:13:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -935,7 +935,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
self.client.post(
f"/api/environments/{self.team.id}/warehouse_saved_queries/",
{
@@ -964,7 +964,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_full_hogql_query_async(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
_create_person(
properties={"email": "[email protected]"},
distinct_ids=["2", "some-random-uid"],
@@ -977,7 +977,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
distinct_id="2",
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_event(
team=self.team,
event="sign out",
@@ -986,7 +986,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
query = HogQLQuery(query="select * from events")
api_response = self.client.post(
f"/api/environments/{self.team.id}/query/", {"query": query.dict(), "refresh": "force_async"}
@@ -1022,7 +1022,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
def test_full_hogql_query_values(self):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
for _ in range(20):
_create_event(
team=self.team,
@@ -1032,7 +1032,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 12:14:00"):
+ with time_machine.travel("2020-01-10 12:14:00", tick=False):
response = process_query_dict(
team=self.team,
query_json={
@@ -1047,14 +1047,14 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
def test_dashboard_filters_applied(self):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-07 12:00:00"):
+ with time_machine.travel("2020-01-07 12:00:00", tick=False):
_create_event(
team=self.team,
event="sign up",
distinct_id=random_uuid,
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 15:00:00"):
+ with time_machine.travel("2020-01-10 15:00:00", tick=False):
_create_event(
team=self.team,
event="$pageview",
@@ -1063,7 +1063,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 19:00:00"):
+ with time_machine.travel("2020-01-10 19:00:00", tick=False):
response_without_dashboard_filters = process_query_dict(
team=self.team,
query_json={
@@ -1087,14 +1087,14 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
def test_dashboard_filters_applied_with_source(self):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
- with freeze_time("2020-01-07 12:00:00"):
+ with time_machine.travel("2020-01-07 12:00:00", tick=False):
_create_event(
team=self.team,
event="sign up",
distinct_id=random_uuid,
properties={"key": "test_val1"},
)
- with freeze_time("2020-01-10 15:00:00"):
+ with time_machine.travel("2020-01-10 15:00:00", tick=False):
_create_event(
team=self.team,
event="$pageview",
@@ -1103,7 +1103,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-10 19:00:00"):
+ with time_machine.travel("2020-01-10 19:00:00", tick=False):
response_without_dashboard_filters = process_query_dict(
team=self.team,
query_json={
diff --git a/posthog/api/test/test_report.py b/posthog/api/test/test_report.py
index 1366b0e7e8ee..b96c06f376fa 100644
--- a/posthog/api/test/test_report.py
+++ b/posthog/api/test/test_report.py
@@ -1,6 +1,6 @@
import json
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -142,7 +142,7 @@ class TestCspReport(BaseTest):
def test_crash_report_becomes_backdated_event(self, mock_batch_capture):
mock_batch_capture.return_value = MagicMock(raise_for_status=MagicMock())
- with freeze_time("2026-08-12T10:00:00Z"):
+ with time_machine.travel("2026-08-12T10:00:00Z", tick=False):
response = self.client.post(
f"/report/?token={self.team.api_token}&distinct_id=user-distinct-id",
data=json.dumps([CRASH_REPORT]),
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 627d8fff55aa..5c266c8fd867 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -3,7 +3,7 @@ from datetime import timedelta
from functools import wraps
from urllib.parse import quote
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, Mock, patch
@@ -139,7 +139,7 @@ class TestSharing(APIBaseTest):
created_by=cls.user,
)
- @freeze_time("2022-01-01")
+ @time_machine.travel("2022-01-01", tick=False)
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
def test_gets_sharing_config(self, patched_exporter_task: Mock):
assert SharingConfiguration.objects.count() == 0
@@ -181,7 +181,7 @@ class TestSharing(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
mock_record_access.assert_called_once_with(expected_access_method)
- @freeze_time("2022-01-01")
+ @time_machine.travel("2022-01-01", tick=False)
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
def test_does_not_change_token_when_toggling_enabled_state(self, patched_exporter_task: Mock):
assert SharingConfiguration.objects.count() == 0
@@ -492,7 +492,7 @@ class TestSharing(APIBaseTest):
# Create an asset that's past its expiry (PNG assets expire after 180 days)
time_in_the_past = now() - timedelta(days=181)
- with freeze_time(time_in_the_past):
+ with time_machine.travel(time_in_the_past, tick=False):
share_response = self.client.patch(
f"/api/projects/{self.team.id}/{type}/{target.pk}/sharing",
{"enabled": True},
@@ -574,7 +574,7 @@ class TestSharing(APIBaseTest):
assert first is not None
assert first.item_id == str(self.insight.id)
- @freeze_time("2025-01-01 00:00:00")
+ @time_machine.travel("2025-01-01 00:00:00", tick=False)
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
def test_refresh_token_grace_period(self, patched_exporter_task: Mock):
# Enable sharing
@@ -600,17 +600,17 @@ class TestSharing(APIBaseTest):
# Within grace period (4 minutes later), old token should still work
# Note: Grace period is 5 minutes (SHARING_TOKEN_GRACE_PERIOD_SECONDS)
- with freeze_time("2025-01-01 00:04:00"):
+ with time_machine.travel("2025-01-01 00:04:00", tick=False):
response = self.client.get(f"/shared/{initial_token}")
assert response.status_code == 200
# After grace period (6 minutes later), old token should not work
- with freeze_time("2025-01-01 00:06:00"):
+ with time_machine.travel("2025-01-01 00:06:00", tick=False):
response = self.client.get(f"/shared/{initial_token}")
assert response.status_code == 404
# New token should still work after grace period
- with freeze_time("2025-01-01 00:06:00"):
+ with time_machine.travel("2025-01-01 00:06:00", tick=False):
response = self.client.get(f"/shared/{new_token}")
assert response.status_code == 200
diff --git a/posthog/api/test/test_sharing_access_token_security.py b/posthog/api/test/test_sharing_access_token_security.py
index 6873614e18ba..ced1e82e0acb 100644
--- a/posthog/api/test/test_sharing_access_token_security.py
+++ b/posthog/api/test/test_sharing_access_token_security.py
@@ -6,7 +6,7 @@ import json
from datetime import timedelta
from typing import Any, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.conf import settings
@@ -62,7 +62,7 @@ class SharingAccessTokenSecurityTest(APIBaseTest):
# Jump past the grace period so the old token is fully expired
future = timezone.now() + timedelta(seconds=settings.SHARING_TOKEN_GRACE_PERIOD_SECONDS + 60)
- with freeze_time(future):
+ with time_machine.travel(future, tick=False):
# Old token must be rejected
response = self.client.get(
f"/api/environments/{self.team.id}/insights/{insight.id}/",
@@ -111,7 +111,7 @@ class SharingAccessTokenSecurityTest(APIBaseTest):
# Jump past the grace period
future = timezone.now() + timedelta(seconds=settings.SHARING_TOKEN_GRACE_PERIOD_SECONDS + 60)
- with freeze_time(future):
+ with time_machine.travel(future, tick=False):
# Old JWT against expired config must be rejected
response = self.client.get(
f"/api/environments/{self.team.id}/insights/{insight.id}/",
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 9834aecd192d..8b95e41137d8 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest import mock
from unittest.mock import ANY, MagicMock, call, patch
@@ -271,7 +271,7 @@ def team_api_test_factory():
response = self.client.get(f"/api/environments/{other_team.pk}/event_ingestion_restrictions/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_update_team_timezone(self):
self._assert_activity_log_is_empty()
@@ -504,7 +504,7 @@ def team_api_test_factory():
mock_start_workflow.assert_not_called()
self.assertTrue(Team.objects.filter(pk=team.pk).exists())
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_reset_token(self):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
@@ -562,7 +562,7 @@ def team_api_test_factory():
response = self.client.patch(f"/api/environments/{self.team.id}/reset_token/")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_generate_secret_token(self):
from posthog.models.utils import mask_key_value
@@ -617,7 +617,7 @@ def team_api_test_factory():
]
)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_rotate_secret_token(self):
from posthog.models.utils import mask_key_value
@@ -679,7 +679,7 @@ def team_api_test_factory():
]
)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_rotate_secret_token_overwrites_backup_token(self):
from posthog.models.utils import mask_key_value
@@ -772,7 +772,7 @@ def team_api_test_factory():
self.assertTrue((self.team.secret_api_token or "").startswith("phs_"))
self.assertEqual(self.team.secret_api_token_backup, existing_token)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_delete_secret_backup_token(self):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
@@ -884,7 +884,7 @@ def team_api_test_factory():
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), {"is_generating_demo_data": False})
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_team_float_config_can_be_serialized_to_activity_log(self):
# regression test since this isn't true by default
response = self.client.patch(f"/api/environments/@current/", {"session_recording_sample_rate": 0.4})
@@ -1284,7 +1284,7 @@ def team_api_test_factory():
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
@patch("posthog.event_usage.report_user_action")
- @freeze_time("2024-01-01T00:00:00Z")
+ @time_machine.travel("2024-01-01T00:00:00Z", tick=False)
def test_can_add_product_intent(self, mock_report_user_action: MagicMock) -> None:
response = self.client.patch(
f"/api/environments/{self.team.id}/add_product_intent/",
@@ -1315,7 +1315,7 @@ def team_api_test_factory():
@patch("posthog.api.team.enqueue_product_activation_calc_debounced", MagicMock())
@patch("posthog.models.product_intent.ProductIntent.check_and_update_activation", return_value=False)
@patch("posthog.event_usage.report_user_action")
- @freeze_time("2024-01-01T00:00:00Z")
+ @time_machine.travel("2024-01-01T00:00:00Z", tick=False)
def test_can_update_product_intent_if_already_exists(
self,
mock_report_user_action: MagicMock,
@@ -1329,7 +1329,7 @@ def team_api_test_factory():
original_created_at = intent.created_at
assert original_created_at == datetime(2024, 1, 1, 0, 0, 0, tzinfo=UTC)
# change the time of the existing intent
- with freeze_time("2024-01-02T00:00:00Z"):
+ with time_machine.travel("2024-01-02T00:00:00Z", tick=False):
response = self.client.patch(
f"/api/environments/{self.team.id}/add_product_intent/",
{"product_type": "product_analytics"},
@@ -1389,11 +1389,11 @@ def team_api_test_factory():
# The /api/environments/ request is rewritten to /api/projects/ for every client, so the project
# viewset's report_user_action fires (not the team module's).
mock_report_user_action = mock_report_user_action_legacy_endpoint
- with freeze_time("2024-01-01T00:00:00Z"):
+ with time_machine.travel("2024-01-01T00:00:00Z", tick=False):
product_intent = ProductIntent.objects.create(team=self.team, product_type="product_analytics")
assert product_intent.created_at == datetime(2024, 1, 1, 0, 0, 0, tzinfo=UTC)
assert product_intent.onboarding_completed_at is None
- with freeze_time("2024-01-05T00:00:00Z"):
+ with time_machine.travel("2024-01-05T00:00:00Z", tick=False):
response = self.client.patch(
f"/api/environments/{self.team.id}/complete_product_onboarding/",
{"product_type": "product_analytics"},
@@ -1445,11 +1445,11 @@ def team_api_test_factory():
# The /api/environments/ request is rewritten to /api/projects/ for every client, so the project
# viewset's report_user_action fires (not the team module's).
mock_report_user_action = mock_report_user_action_legacy_endpoint
- with freeze_time("2024-01-01T00:00:00Z"):
+ with time_machine.travel("2024-01-01T00:00:00Z", tick=False):
product_intent = ProductIntent.objects.create(team=self.team, product_type="product_analytics")
assert product_intent.created_at == datetime(2024, 1, 1, 0, 0, 0, tzinfo=UTC)
assert product_intent.onboarding_completed_at is None
- with freeze_time("2024-01-05T00:00:00Z"):
+ with time_machine.travel("2024-01-05T00:00:00Z", tick=False):
response = self.client.patch(
f"/api/environments/{self.team.id}/complete_product_onboarding/",
{"product_type": "product_analytics"},
@@ -1856,7 +1856,7 @@ def team_api_test_factory():
self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)
# Set initial retention - first update doesn't set retention_last_updated
- with freeze_time("2025-01-01T00:00:00Z"):
+ with time_machine.travel("2025-01-01T00:00:00Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{"logs_settings": {"retention_days": 30}},
@@ -1865,7 +1865,7 @@ def team_api_test_factory():
assert not hasattr(response.json()["logs_settings"], "retention_last_updated")
# update retention, should set retention_last_updated
- with freeze_time("2025-01-01T00:00:00Z"):
+ with time_machine.travel("2025-01-01T00:00:00Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{"logs_settings": {"retention_days": 14}},
@@ -1874,7 +1874,7 @@ def team_api_test_factory():
assert response.json()["logs_settings"]["retention_last_updated"] is not None
# Try to update retention within 24 hours - should fail
- with freeze_time("2025-01-01T12:00:00Z"):
+ with time_machine.travel("2025-01-01T12:00:00Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{"logs_settings": {"retention_days": 30}},
@@ -1883,7 +1883,7 @@ def team_api_test_factory():
assert "24 hours" in response.json()["detail"]
# Try to update retention after 24 hours - should succeed
- with freeze_time("2025-01-02T00:00:01Z"):
+ with time_machine.travel("2025-01-02T00:00:01Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{"logs_settings": {"retention_days": 30}},
@@ -1936,14 +1936,14 @@ def team_api_test_factory():
self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)
# Set initial retention
- with freeze_time("2025-01-01T00:00:00Z"):
+ with time_machine.travel("2025-01-01T00:00:00Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{"logs_settings": {"retention_days": 30}},
)
assert response.status_code == status.HTTP_200_OK
- with freeze_time("2025-01-01T00:00:00Z"):
+ with time_machine.travel("2025-01-01T00:00:00Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{"logs_settings": {"retention_days": 14}},
@@ -1951,7 +1951,7 @@ def team_api_test_factory():
assert response.status_code == status.HTTP_200_OK
# Change other settings within 24 hours - should succeed
- with freeze_time("2025-01-01T12:00:00Z"):
+ with time_machine.travel("2025-01-01T12:00:00Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{
@@ -1964,7 +1964,7 @@ def team_api_test_factory():
assert response.status_code == status.HTTP_200_OK
# Change retention after 24 hours - should succeed
- with freeze_time("2025-01-02T00:00:01Z"):
+ with time_machine.travel("2025-01-02T00:00:01Z", tick=False):
response = self.client.patch(
"/api/environments/@current/",
{
@@ -2976,7 +2976,7 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore
self.assertEqual(self.team.session_recording_opt_in, True)
self.assertEqual(self.team.surveys_opt_in, True)
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_settings_as_of_requires_at_param(self):
response = self.client.get("/api/environments/@current/settings_as_of/")
assert response.status_code == status.HTTP_400_BAD_REQUEST
@@ -2986,12 +2986,12 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore
def test_settings_as_of_returns_snapshot_with_scope(self):
# Initial state at T0 is UTC (default)
- with freeze_time("2025-01-01T00:00:00Z"):
+ with time_machine.travel("2025-01-01T00:00:00Z", tick=False):
# no change, timezone remains "UTC"
pass
# Change timezone at T1
- with freeze_time("2025-01-02T00:00:00Z"):
+ with time_machine.travel("2025-01-02T00:00:00Z", tick=False):
patch_response = self.client.patch("/api/environments/@current/", {"timezone": "Europe/Lisbon"})
assert patch_response.status_code == status.HTTP_200_OK, patch_response.json()
@@ -3009,12 +3009,12 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore
def test_settings_as_of_full_snapshot_and_filtering(self):
# Set some configs over time to create activity
- with freeze_time("2025-02-01T00:00:00Z"):
+ with time_machine.travel("2025-02-01T00:00:00Z", tick=False):
# Set opt_in true
r1 = self.client.patch("/api/environments/@current/", {"session_recording_opt_in": True})
assert r1.status_code == status.HTTP_200_OK
- with freeze_time("2025-02-02T00:00:00Z"):
+ with time_machine.travel("2025-02-02T00:00:00Z", tick=False):
# Set sample rate and masking config
r2 = self.client.patch(
"/api/environments/@current/",
@@ -3039,7 +3039,7 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore
assert data["session_recording_masking_config"] is None
def test_settings_as_of_scope_only_includes_requested_keys(self):
- with freeze_time("2025-03-01T00:00:00Z"):
+ with time_machine.travel("2025-03-01T00:00:00Z", tick=False):
r = self.client.patch(
"/api/environments/@current/",
{"timezone": "Europe/London", "session_recording_opt_in": False},
diff --git a/posthog/api/test/test_team_deletion.py b/posthog/api/test/test_team_deletion.py
index 908d12c32671..ad2d8db3da79 100644
--- a/posthog/api/test/test_team_deletion.py
+++ b/posthog/api/test/test_team_deletion.py
@@ -1,7 +1,7 @@
import json
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import NonAtomicBaseTest
from unittest.mock import ANY, MagicMock, patch
@@ -50,7 +50,7 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):
created_by=self.user,
)
- @freeze_time("2022-02-08")
+ @time_machine.travel("2022-02-08", tick=False)
def test_delete_team_activity_log(self):
team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)
diff --git a/posthog/api/test/test_two_factor_reset.py b/posthog/api/test/test_two_factor_reset.py
index 7d623d20312f..092488b05ca6 100644
--- a/posthog/api/test/test_two_factor_reset.py
+++ b/posthog/api/test/test_two_factor_reset.py
@@ -2,7 +2,7 @@ import time
import datetime
from importlib import import_module
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -125,7 +125,7 @@ class TestTwoFactorReset(APIBaseTest):
token = self._setup_2fa_reset()
# Move time forward by more than 24 hours
- with freeze_time(timezone.now() + datetime.timedelta(hours=24, minutes=1)):
+ with time_machine.travel(timezone.now() + datetime.timedelta(hours=24, minutes=1), tick=False):
self._setup_half_auth_session()
response = self.client.get(f"/api/reset_2fa/{self.user.uuid}/?token={token}")
@@ -270,11 +270,11 @@ class TestTwoFactorReset(APIBaseTest):
def test_new_reset_request_invalidates_old_token(self):
"""Test that requesting a new reset invalidates the old token."""
# Get first token at time T
- with freeze_time("2024-01-01 12:00:00"):
+ with time_machine.travel("2024-01-01 12:00:00", tick=False):
token1 = self._setup_2fa_reset()
# Request a new reset at time T+1 (which updates requested_2fa_reset_at)
- with freeze_time("2024-01-01 12:00:01"):
+ with time_machine.travel("2024-01-01 12:00:01", tick=False):
self.user.requested_2fa_reset_at = datetime.datetime.now(datetime.UTC)
self.user.save(update_fields=["requested_2fa_reset_at"])
token2 = TwoFactorResetVerifier.create_token(self.user)
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 26944b074103..da79f42a3b18 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -6,7 +6,7 @@ from typing import cast
from urllib.parse import quote, unquote, urlparse
import pytest
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, NonAtomicBaseTest
from unittest import mock
from unittest.mock import ANY, patch
@@ -240,7 +240,7 @@ class TestUserAPI(APIBaseTest):
from posthog.models import OrganizationInvite
other_org = Organization.objects.create(name="Other Org For Pending Invites Test")
- with freeze_time(timezone.now() - timedelta(days=INVITE_DAYS_VALIDITY + 1)):
+ with time_machine.travel(timezone.now() - timedelta(days=INVITE_DAYS_VALIDITY + 1), tick=False):
OrganizationInvite.objects.create(
organization=other_org,
target_email=self.user.email,
@@ -938,7 +938,7 @@ class TestUserAPI(APIBaseTest):
self.user.is_email_verified = True
self.user.save()
with self.is_cloud(True):
- with freeze_time("2020-01-01T21:37:00+00:00"):
+ with time_machine.travel("2020-01-01T21:37:00+00:00", tick=False):
response = self.client.patch(
"/api/users/@me/",
{
@@ -957,7 +957,7 @@ class TestUserAPI(APIBaseTest):
mock_is_email_available.assert_called_once()
mock_send_code.assert_called_once_with(self.user.pk, ANY, "[email protected]")
- with freeze_time("2020-01-01T21:37:00+00:00"):
+ with time_machine.travel("2020-01-01T21:37:00+00:00", tick=False):
response = self.client.post(
f"/api/users/verify_email/",
{"uuid": self.user.uuid, "code": mock_send_code.call_args[0][1]},
@@ -3249,7 +3249,7 @@ class TestEmailVerificationCodeAPI(APIBaseTest):
def test_expired_code_is_rejected(self):
code = self._request_code()
- with freeze_time(timezone.now() + datetime.timedelta(minutes=31)):
+ with time_machine.travel(timezone.now() + datetime.timedelta(minutes=31), tick=False):
response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["code"], "invalid_code")
diff --git a/posthog/api/test/test_web_vitals.py b/posthog/api/test/test_web_vitals.py
index bf22b19c6016..49bba04dc434 100644
--- a/posthog/api/test/test_web_vitals.py
+++ b/posthog/api/test/test_web_vitals.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from rest_framework import status
@@ -42,7 +42,7 @@ class TestWebVitalsAPI(ClickhouseTestMixin, APIBaseTest):
def test_web_vitals_with_data(self):
# Freeze time at query time
timestamp = f"2024-01-07T12:00:00.000Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
session_id = str(uuid7("2024-01-07"))
# Create some events for each of the metrics
diff --git a/posthog/caching/test/test_stale_utils.py b/posthog/caching/test/test_stale_utils.py
index 84fc5b1d1c6d..c325da9a25f0 100644
--- a/posthog/caching/test/test_stale_utils.py
+++ b/posthog/caching/test/test_stale_utils.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.caching.utils import is_stale
@@ -40,7 +40,7 @@ date_to = datetime(2021, 1, 1, 0, 0, 1, tzinfo=UTC)
(team_a, date_to - timedelta(days=1), "day", timedelta(seconds=0), False),
],
)
-@freeze_time("2021-01-01T00:00:00Z")
+@time_machine.travel("2021-01-01T00:00:00Z", tick=False)
def test_is_stale(team, date_to, interval, last_refresh, expected):
assert is_stale(team, date_to, interval, datetime.now(UTC) - last_refresh) == expected
@@ -77,7 +77,7 @@ def test_is_stale(team, date_to, interval, last_refresh, expected):
),
],
)
-@freeze_time("2025-01-01T00:00:00Z")
+@time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_is_stale_with_target_age(team, date_to, interval, last_refresh, target_age, expected):
"""Test that target_age parameter overrides interval-based staleness calculation."""
assert is_stale(team, date_to, interval, last_refresh, target_age=target_age) == expected
diff --git a/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py b/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
index 248f120aceae..50d0806f170e 100644
--- a/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
+++ b/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.cdp.templates.aws_kinesis.template_aws_kinesis import template as template_aws_kinesis
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
@@ -7,7 +7,7 @@ from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
class TestTemplateAwsKinesis(BaseHogFunctionTemplateTest):
template = template_aws_kinesis
- @freeze_time("2024-04-16T12:34:51Z")
+ @time_machine.travel("2024-04-16T12:34:51Z", tick=False)
def test_function_works(self):
res = self.run_function(
inputs={
diff --git a/posthog/cdp/templates/braze/test_template_braze.py b/posthog/cdp/templates/braze/test_template_braze.py
index 9cfab4132932..fd5e40e41fc2 100644
--- a/posthog/cdp/templates/braze/test_template_braze.py
+++ b/posthog/cdp/templates/braze/test_template_braze.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.cdp.templates.braze.template_braze import template as template_braze
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
@@ -7,7 +7,7 @@ from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
class TestTemplateBraze(BaseHogFunctionTemplateTest):
template = template_braze
- @freeze_time("2024-04-16T12:34:51Z")
+ @time_machine.travel("2024-04-16T12:34:51Z", tick=False)
def test_function_works(self):
res = self.run_function(
inputs={
diff --git a/posthog/cdp/templates/onesignal/test_template_onesignal.py b/posthog/cdp/templates/onesignal/test_template_onesignal.py
index c259d08a7534..7d91bb952b68 100644
--- a/posthog/cdp/templates/onesignal/test_template_onesignal.py
+++ b/posthog/cdp/templates/onesignal/test_template_onesignal.py
@@ -1,5 +1,5 @@
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
from posthog.cdp.templates.onesignal.template_onesignal import template as template_onesignal
@@ -10,7 +10,7 @@ from common.hogvm.python.utils import UncaughtHogVMException
class TestTemplateOneSignal(BaseHogFunctionTemplateTest):
template = template_onesignal
- @freeze_time("2024-04-16T12:34:51Z")
+ @time_machine.travel("2024-04-16T12:34:51Z", tick=False)
def test_function_works(self):
res = self.run_function(
inputs={
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index f61c46202537..b65d3b4a07c2 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -4,7 +4,7 @@ from typing import cast
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.conf import settings as django_settings
@@ -582,7 +582,7 @@ def test_cleanup_old_events_by_partition(cluster: ClickhouseCluster):
@pytest.mark.django_db
-@freeze_time("2025-09-15")
+@time_machine.travel("2025-09-15", tick=False)
def test_cleanup_old_events_delete_query_format(cluster: ClickhouseCluster, snapshot):
from unittest.mock import patch
diff --git a/posthog/helpers/tests/test_encrypted_fields.py b/posthog/helpers/tests/test_encrypted_fields.py
index d4fa6a741bcd..6cb2c7bfbb02 100644
--- a/posthog/helpers/tests/test_encrypted_fields.py
+++ b/posthog/helpers/tests/test_encrypted_fields.py
@@ -1,6 +1,6 @@
import base64
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -65,7 +65,7 @@ class TestEncryptedFields(BaseTest):
Simple test case to be replicated in node tests or anywhere else that the same secrets will be used
"""
ef = EncryptedFieldMixin()
- with freeze_time("2024-01-01T00:01:00Z"):
+ with time_machine.travel("2024-01-01T00:01:00Z", tick=False):
with patch("os.urandom", return_value=b"\x00" * 16):
encrypted = ef.f.encrypt(bytes("test-case", "utf-8")).decode("utf-8")
diff --git a/posthog/hogql/database/schema/test/base.py b/posthog/hogql/database/schema/test/base.py
index 608e519f28c0..6759948f7e1f 100644
--- a/posthog/hogql/database/schema/test/base.py
+++ b/posthog/hogql/database/schema/test/base.py
@@ -3,7 +3,7 @@ import tempfile
from datetime import datetime
from pathlib import Path
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -118,7 +118,7 @@ class RevenueAnalyticsManagedViewsetsTestMixin(RevenueAnalyticsTestBase):
super().tearDown()
def create_and_materialize_viewsets(self):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(
team=self.team, kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS
)
diff --git a/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py b/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py
index 3ea446fb5be6..4cc1f30c17e8 100644
--- a/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py
+++ b/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py
@@ -1,6 +1,6 @@
from decimal import Decimal
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, snapshot_clickhouse_queries
from posthog.schema import (
@@ -215,7 +215,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
self.team.revenue_analytics_config.save()
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select(
"SELECT key, revenue_analytics.revenue, $virt_revenue FROM groups where key = {key}",
@@ -239,7 +239,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
for key in ["cus_1", "cus_2", "cus_3", "cus_4", "cus_5", "cus_6", "dummy"]:
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
queries = [
"SELECT key, revenue_analytics.revenue FROM groups ORDER BY key ASC",
"SELECT key, $virt_revenue FROM groups ORDER BY key ASC",
@@ -279,7 +279,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
]:
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select("SELECT key, revenue_analytics.revenue, $virt_revenue FROM groups ORDER BY key ASC"),
self.team,
@@ -317,7 +317,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
]:
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select("SELECT key, revenue_analytics.revenue, $virt_revenue FROM groups ORDER BY key ASC"),
self.team,
@@ -346,7 +346,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
for key in ["cus_1", "cus_2", "cus_3", "cus_4", "cus_5", "cus_6", "dummy"]:
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select(
"SELECT key, revenue_analytics.revenue, revenue_analytics.mrr FROM groups ORDER BY key ASC"
@@ -385,7 +385,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
self.team.revenue_analytics_config.save()
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select(
"SELECT key, revenue_analytics.revenue, revenue_analytics.mrr FROM groups WHERE key = {key}",
@@ -410,7 +410,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
for key in ["cus_1", "cus_2", "cus_3", "cus_4", "cus_5", "cus_6"]:
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = execute_hogql_query(
parse_select("SELECT group_key, revenue, mrr FROM groups_revenue_analytics ORDER BY mrr DESC"),
self.team,
@@ -447,7 +447,7 @@ class TestGroupsRevenueAnalytics(TestGroupsRevenueAnalyticsMixin):
self.team.revenue_analytics_config.save()
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = execute_hogql_query(
parse_select("SELECT group_key, revenue, mrr FROM groups_revenue_analytics ORDER BY group_key ASC"),
self.team,
@@ -484,7 +484,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
self.team.save()
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
response = execute_hogql_query(
parse_select(
"SELECT key, revenue_analytics.revenue, $virt_revenue FROM groups where key = {key}",
@@ -509,7 +509,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
queries = [
"SELECT key, revenue_analytics.revenue FROM groups ORDER BY key ASC",
"SELECT key, $virt_revenue FROM groups ORDER BY key ASC",
@@ -548,7 +548,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
response = execute_hogql_query(
parse_select("SELECT key, revenue_analytics.revenue, $virt_revenue FROM groups ORDER BY key ASC"),
self.team,
@@ -586,7 +586,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
response = execute_hogql_query(
parse_select("SELECT key, revenue_analytics.revenue, $virt_revenue FROM groups ORDER BY key ASC"),
self.team,
@@ -616,7 +616,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
response = execute_hogql_query(
parse_select(
"SELECT key, revenue_analytics.revenue, revenue_analytics.mrr FROM groups ORDER BY key ASC"
@@ -656,7 +656,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
self.team.save()
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
response = execute_hogql_query(
parse_select(
"SELECT key, revenue_analytics.revenue, revenue_analytics.mrr FROM groups WHERE key = {key}",
@@ -682,7 +682,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
create_group(team_id=self.team.pk, group_type_index=0, group_key=key)
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
results = execute_hogql_query(
parse_select("SELECT group_key, revenue, mrr FROM groups_revenue_analytics ORDER BY mrr DESC"),
self.team,
@@ -720,7 +720,7 @@ class TestGroupsRevenueAnalyticsManagedViewsets(
self.team.save()
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
results = execute_hogql_query(
parse_select("SELECT group_key, revenue, mrr FROM groups_revenue_analytics ORDER BY group_key ASC"),
self.team,
diff --git a/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py b/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
index ecfe3164a0b5..9242a0432d13 100644
--- a/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
+++ b/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
@@ -1,7 +1,7 @@
from decimal import Decimal
from uuid import UUID
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, snapshot_clickhouse_queries
from unittest.mock import patch
@@ -127,7 +127,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
self.team.revenue_analytics_config.save()
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select(
"select revenue_analytics.revenue, $virt_revenue from persons where id = {id}",
@@ -150,7 +150,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
distinct_id_to_person_id[distinct_id] = person.uuid
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
queries = [
"SELECT id, revenue_analytics.revenue from persons order by id asc",
"SELECT id, $virt_revenue from persons order by id asc",
@@ -191,7 +191,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
distinct_id_to_person_id[distinct_id] = person.uuid
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select("SELECT id, revenue_analytics.revenue, $virt_revenue FROM persons ORDER BY id ASC"),
self.team,
@@ -243,7 +243,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
distinct_id_to_person_id[distinct_id] = person.uuid
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select("SELECT id, revenue_analytics.revenue, $virt_revenue from persons order by id asc"),
self.team,
@@ -277,7 +277,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
# Dummy person without revenue
dummy_person = _create_person(team_id=self.team.pk, distinct_ids=["dummy"])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select("SELECT id, $virt_revenue FROM persons ORDER BY $virt_revenue ASC"),
self.team,
@@ -314,7 +314,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
expected_revenue = Decimal("766.0654934005") # cus_1 283.8496260553 + cus_2 482.2158673452
expected_mrr = Decimal("63.7684363904") # cus_1 22.9631447238 + cus_2 40.8052916666
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
table_results = execute_hogql_query(
parse_select(
"SELECT person_id, revenue, mrr FROM persons_revenue_analytics WHERE person_id = {id}",
@@ -358,7 +358,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
# `cus_2` through `cus_6` match no person, so they carry the all-zeros UUID and are dropped.
# Only the two attributable rows remain, one from each leg.
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = execute_hogql_query(
parse_select("SELECT person_id, revenue, mrr FROM persons_revenue_analytics"),
self.team,
@@ -393,7 +393,10 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
field_name="persons",
)
- with freeze_time(self.QUERY_TIMESTAMP), patch.object(persons_revenue_analytics, "logger") as mock_logger:
+ with (
+ time_machine.travel(self.QUERY_TIMESTAMP, tick=False),
+ patch.object(persons_revenue_analytics, "logger") as mock_logger,
+ ):
results = execute_hogql_query(
parse_select("SELECT person_id, revenue FROM persons_revenue_analytics"),
self.team,
@@ -437,7 +440,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
person = _create_person(team_id=self.team.pk, distinct_ids=["cus_1"])
expected_rows = [(person.uuid, Decimal("283.8496260553"))]
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = execute_hogql_query(
parse_select(
"""
@@ -464,7 +467,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
distinct_id_to_person_id[distinct_id] = person.uuid
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = execute_hogql_query(
parse_select(
"SELECT person_id, revenue, mrr FROM persons_revenue_analytics ORDER BY mrr DESC, revenue DESC"
@@ -502,7 +505,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
self.team.revenue_analytics_config.save()
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = execute_hogql_query(
parse_select("SELECT person_id, revenue, mrr FROM persons_revenue_analytics ORDER BY person_id ASC"),
self.team,
@@ -533,7 +536,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
self.team.save()
# Breaking down by revenue doesnt make any sense, but this is just proving it works
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = TrendsQuery(
**{
"kind": "TrendsQuery",
@@ -570,7 +573,7 @@ class TestPersonsRevenueAnalyticsManagedViewsets(
self.create_and_materialize_viewsets()
# Breaking down by revenue doesnt make any sense, but this is just proving it works
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
query = TrendsQuery(
**{
"kind": "TrendsQuery",
@@ -602,7 +605,7 @@ class TestPersonsRevenueAnalyticsManagedViewsets(
self.team.save()
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
results = execute_hogql_query(
parse_select("SELECT person_id, revenue, mrr FROM persons_revenue_analytics ORDER BY person_id ASC"),
self.team,
@@ -626,7 +629,7 @@ class TestPersonsRevenueAnalyticsManagedViewsets(
person = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
distinct_id_to_person_id[distinct_id] = person.uuid
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
results = execute_hogql_query(
parse_select(
"SELECT person_id, revenue, mrr FROM persons_revenue_analytics ORDER BY mrr DESC, revenue DESC"
@@ -660,7 +663,7 @@ class TestPersonsRevenueAnalyticsManagedViewsets(
distinct_id_to_person_id[distinct_id] = person.uuid
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
queries = [
"SELECT id, revenue_analytics.revenue from persons order by id asc",
"SELECT id, $virt_revenue from persons order by id asc",
@@ -696,7 +699,7 @@ class TestPersonsRevenueAnalyticsManagedViewsets(
self.team.save()
self.create_and_materialize_viewsets()
- with freeze_time(self.QUERY_TIMESTAMP), self.snapshot_select_queries():
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False), self.snapshot_select_queries():
response = execute_hogql_query(
parse_select(
"select revenue_analytics.revenue, $virt_revenue from persons where id = {id}",
diff --git a/posthog/hogql/database/schema/test/test_session_replay_events.py b/posthog/hogql/database/schema/test/test_session_replay_events.py
index 4401bed93778..a998a335e3a0 100644
--- a/posthog/hogql/database/schema/test/test_session_replay_events.py
+++ b/posthog/hogql/database/schema/test/test_session_replay_events.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -27,7 +27,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SES
from posthog.uuidt import uuid7
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestFilterSessionReplaysBySessions(ClickhouseTestMixin, APIBaseTest):
session_with_one_hour = str(uuid7("2021-01-01T10"))
session_with_different_session_and_replay_duration = str(uuid7("2021-01-01T11"))
@@ -136,7 +136,7 @@ class TestFilterSessionReplaysBySessions(ClickhouseTestMixin, APIBaseTest):
]
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestFilterSessionReplaysByEvents(ClickhouseTestMixin, APIBaseTest):
allow_dual_schema_snapshots = True
@@ -259,7 +259,7 @@ class TestFilterSessionReplaysByEvents(ClickhouseTestMixin, APIBaseTest):
]
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestFilterSessionReplaysByPerson(ClickhouseTestMixin, APIBaseTest):
allow_dual_schema_snapshots = True
@@ -399,7 +399,7 @@ class TestFilterSessionReplaysByPerson(ClickhouseTestMixin, APIBaseTest):
]
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestFilterSessionReplaysByConsoleLogs(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
@@ -471,7 +471,7 @@ class TestFilterSessionReplaysByConsoleLogs(ClickhouseTestMixin, APIBaseTest):
assert response.results == [("This is an info message",), ("This is a generic message",)]
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSelectAggregatedArrayColumns(ClickhouseTestMixin, APIBaseTest):
"""Regression coverage for `groupUniqArrayArray` columns on the session_replay_events lazy table.
diff --git a/posthog/hogql/database/test/test_activity_logs_restrictions.py b/posthog/hogql/database/test/test_activity_logs_restrictions.py
index 81969af28a86..2f4fc8f3a0ad 100644
--- a/posthog/hogql/database/test/test_activity_logs_restrictions.py
+++ b/posthog/hogql/database/test/test_activity_logs_restrictions.py
@@ -1,7 +1,7 @@
from datetime import timedelta
from typing import Literal
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -219,7 +219,7 @@ class TestActivityLogsCacheKey(BaseTest):
def test_cache_key_varies_with_the_retention_window(self):
# A cache hit returns before the printer applies the floor, so without this a result cached
# on a longer plan keeps serving rows the organization is no longer entitled to read.
- with freeze_time("2026-08-14T10:30:00Z"):
+ with time_machine.travel("2026-08-14T10:30:00Z", tick=False):
wide = self._payload(limit=365, unit="days")
narrow = self._payload(limit=30, unit="days")
@@ -274,11 +274,11 @@ class TestActivityLogsCacheKey(BaseTest):
]
self.organization.save()
- with freeze_time("2026-08-14T10:30:00Z"):
+ with time_machine.travel("2026-08-14T10:30:00Z", tick=False):
earlier = get_query_runner(
HogQLQuery(query="SELECT id FROM system.activity_logs"), team=self.team, user=self.user
).get_cache_key()
- with freeze_time("2026-08-14T11:30:00Z"):
+ with time_machine.travel("2026-08-14T11:30:00Z", tick=False):
later = get_query_runner(
HogQLQuery(query="SELECT id FROM system.activity_logs"), team=self.team, user=self.user
).get_cache_key()
diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.py
index 65db4e45a1bf..c498630cdad7 100644
--- a/posthog/hogql/test/test_filters.py
+++ b/posthog/hogql/test/test_filters.py
@@ -1,6 +1,6 @@
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -96,7 +96,7 @@ class TestFilters(BaseTest):
replace_filters(select, HogQLFilters(dateRange=DateRange(date_from="2020-02-02")), self.team)
def test_replace_filters_date_range(self):
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
# open-ended range: bounded at the end of today instead of including future-dated rows
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
@@ -178,7 +178,7 @@ class TestFilters(BaseTest):
def test_replace_filters_relative_date_from_snaps_to_start_of_day(self, date_from: str, expected: str):
# Regression: relative presets used to keep the wall-clock time of day, so "This month" on a
# dashboard silently dropped rows between midnight and the current time on the first day
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT event FROM events WHERE timestamp >= {filters.dateRange.from}"),
HogQLFilters(dateRange=DateRange(date_from=date_from)),
@@ -192,7 +192,7 @@ class TestFilters(BaseTest):
def test_replace_filters_date_from_respects_week_start_day(self):
self.team.week_start_day = 1
self.team.save()
- with freeze_time("2020-02-15T13:37:42Z"): # a Saturday
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False): # a Saturday
select = replace_filters(
self._parse_select("SELECT event FROM events WHERE timestamp >= {filters.dateRange.from}"),
HogQLFilters(dateRange=DateRange(date_from="wStart")),
@@ -206,7 +206,7 @@ class TestFilters(BaseTest):
def test_replace_filters_sub_day_date_from_stays_rolling(self):
# Sub-day ranges ("last 1 hour" in logs/traces) must keep their exact lower bound and stay
# open-ended — snapping them to calendar boundaries would change the window's meaning
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="-1h")),
@@ -229,7 +229,7 @@ class TestFilters(BaseTest):
def test_replace_filters_date_to_resolution(self, date_to: Optional[str], expected: str):
# Regression: an unset date_to used to drop the upper bound entirely, so "This month" and
# "Last 7 days" included future-dated rows
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
HogQLFilters(dateRange=DateRange(date_from="-7d", date_to=date_to)),
@@ -243,7 +243,7 @@ class TestFilters(BaseTest):
def test_replace_filters_open_ended_date_to_uses_team_timezone(self):
self.team.timezone = "America/New_York"
self.team.save()
- with freeze_time("2020-02-15T03:00:00Z"): # still Feb 14 in New York
+ with time_machine.travel("2020-02-15T03:00:00Z", tick=False): # still Feb 14 in New York
select = replace_filters(
self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
HogQLFilters(dateRange=DateRange(date_from="-7d")),
@@ -261,7 +261,7 @@ class TestFilters(BaseTest):
]
)
def test_replace_filters_date_to_with_explicit_date(self, date_to: Optional[str], expected: str):
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
HogQLFilters(dateRange=DateRange(date_from="2020-02-01", date_to=date_to, explicitDate=True)),
@@ -295,7 +295,7 @@ class TestFilters(BaseTest):
# "All time" must not gain an end-of-today cap: unlike QueryDateRange (where "all" means
# "since the first event"), here it promises the whole table, including future-dated
# warehouse rows
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="all")),
@@ -308,7 +308,7 @@ class TestFilters(BaseTest):
def test_replace_filters_this_month_preset(self):
# The exact shape a dashboard's "This month" filter produces: date_from="mStart", no date_to
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="mStart")),
@@ -406,7 +406,7 @@ class TestFilters(BaseTest):
)
def test_replace_filters_groups_date_range(self):
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT group_key FROM groups where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),
@@ -480,7 +480,7 @@ class TestFilters(BaseTest):
)
def test_replace_filters_groups_date_and_properties(self):
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT group_key FROM groups where {filters}"),
HogQLFilters(
@@ -526,7 +526,7 @@ class TestFilters(BaseTest):
self.assertEqual(self._print_ast(select), f"SELECT id FROM persons WHERE true LIMIT {MAX_SELECT_RETURNED_ROWS}")
def test_replace_filters_persons_date_range(self):
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select("SELECT id FROM persons where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),
@@ -633,7 +633,7 @@ class TestFilters(BaseTest):
replace_filters(select, HogQLFilters(filterTestAccounts=True), self.team)
def test_replace_filters_events_joined_with_persons_keep_event_scope(self):
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select(
"SELECT event FROM events JOIN persons ON events.person_id = persons.id where {filters}"
@@ -665,7 +665,7 @@ class TestFilters(BaseTest):
def test_bound_filters_date_range_and_property(self):
# persons is a table the plain {filters} placeholder rejects, so this exercises the unlock
- with freeze_time("2020-02-15T13:37:42Z"):
+ with time_machine.travel("2020-02-15T13:37:42Z", tick=False):
select = replace_filters(
self._parse_select(
"SELECT id FROM persons WHERE {filters(created_at AS timestamp, properties.plan AS 'plan')}"
diff --git a/posthog/hogql/test/test_mapping.py b/posthog/hogql/test/test_mapping.py
index d78600f10ff6..99cb1aa3a3aa 100644
--- a/posthog/hogql/test/test_mapping.py
+++ b/posthog/hogql/test/test_mapping.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin
from posthog.hogql import ast
@@ -125,7 +125,7 @@ class TestMappings(ClickhouseTestMixin, BaseTest):
)
assert "overloadSuccess" in sql
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_postgres_functions(self):
response = execute_hogql_query(
"""
diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.py
index f6328882e7d5..46ca8d91cce9 100644
--- a/posthog/hogql/test/test_property.py
+++ b/posthog/hogql/test/test_property.py
@@ -1,7 +1,7 @@
from collections.abc import Iterable
from typing import Any, Literal, Optional, Union, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest, _create_event, cleanup_materialized_columns
from unittest.mock import MagicMock, patch
@@ -415,7 +415,7 @@ class TestProperty(BaseTest):
("is_date_exact_relative", "-1y", "is_date_exact", ast.CompareOperationOp.Eq, "2025-04-09 12:00:00"),
]
)
- @freeze_time("2026-04-09T12:00:00Z")
+ @time_machine.travel("2026-04-09T12:00:00Z", tick=False)
def test_property_to_expr_date_operator_relative(self, _name, value, operator, op, expected_rhs):
result = self._property_to_expr({"type": "event", "key": "a", "value": value, "operator": operator})
assert isinstance(result, ast.CompareOperation)
@@ -2119,7 +2119,7 @@ class TestProperty(BaseTest):
)
def test_behavioral_explicit_datetime_bounds(self):
- with freeze_time("2024-05-15T12:00:00Z"):
+ with time_machine.travel("2024-05-15T12:00:00Z", tick=False):
expected_from = relative_date_parse("-7d", self.team.timezone_info)
self.assertEqual(
self._property_to_expr(
@@ -2184,7 +2184,7 @@ class TestProperty(BaseTest):
)
def test_behavioral_explicit_datetime_to_bounds_a_relative_window(self):
- with freeze_time("2024-05-15T12:00:00Z"):
+ with time_machine.travel("2024-05-15T12:00:00Z", tick=False):
expected_to = relative_date_parse("-1d", self.team.timezone_info)
self.assertEqual(
self._property_to_expr(self._behavioral_filter(explicit_datetime_to="-1d")),
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index f58bf107d4d4..6225edddd810 100644
--- a/posthog/hogql/test/test_query.py
+++ b/posthog/hogql/test/test_query.py
@@ -5,7 +5,7 @@ from uuid import UUID
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -128,7 +128,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
response = execute_hogql_query(
@@ -142,7 +142,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_subquery(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
response = execute_hogql_query(
@@ -156,7 +156,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_subquery_alias(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
response = execute_hogql_query(
@@ -227,7 +227,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_distinct(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
response = execute_hogql_query(
@@ -241,7 +241,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_person_distinct_ids(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
f"select distinct person_id, distinct_id from person_distinct_ids",
@@ -252,7 +252,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(len(response.results) > 0)
def test_query_timings(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
response = execute_hogql_query_with_timings(
"select count(), event from events where properties.random_uuid = {random_uuid} group by event",
@@ -268,7 +268,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_simple(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -290,7 +290,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_pdi(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -314,7 +314,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_pdi(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -329,7 +329,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_e_pdi(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -530,7 +530,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_pdi_persons(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -551,7 +551,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_pdi_person_properties(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -569,7 +569,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_first_to_persons(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
properties={"email": "[email protected]"},
team=self.team,
@@ -598,7 +598,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_lazy_on_both_sides(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
properties={"email": "[email protected]"},
team=self.team,
@@ -633,7 +633,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_persons_to_events(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
properties={"email": "[email protected]"},
team=self.team,
@@ -658,7 +658,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_pdi_person(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -674,7 +674,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_query_joins_events_pdi_person_properties(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -689,7 +689,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_pdi_e_person_properties(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -704,7 +704,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_person_properties(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -718,7 +718,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_events_person_properties_in_aggregration(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
"SELECT s.pdi.person.properties.sneaky_mail, count() FROM events s GROUP BY s.pdi.person.properties.sneaky_mail LIMIT 10",
@@ -730,7 +730,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_select_person_on_events(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
"SELECT poe.properties.sneaky_mail, count() FROM events s GROUP BY poe.properties.sneaky_mail LIMIT 10",
@@ -743,7 +743,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_query_select_person_with_joins_without_poe(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -759,7 +759,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
@override_settings(PERSON_ON_EVENTS_OVERRIDE=True, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_query_select_person_with_poe_without_joins(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
response = execute_hogql_query(
@@ -774,7 +774,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_prop_cohort_basic(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
distinct_ids=["some_other_id"],
team_id=self.team.pk,
@@ -846,7 +846,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_prop_cohort_static(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
distinct_ids=["some_other_id"],
team_id=self.team.pk,
@@ -905,7 +905,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_join_with_property_materialized_session_id(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
distinct_ids=["some_id"],
team_id=self.team.pk,
@@ -949,7 +949,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_join_with_property_not_materialized(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
_create_person(
distinct_ids=["some_id"],
team_id=self.team.pk,
@@ -1012,7 +1012,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
having cnt > 10
limit 1
"""
- with freeze_time("2025-02-15 22:52:00"):
+ with time_machine.travel("2025-02-15 22:52:00", tick=False):
response = execute_hogql_query(query, team=self.team, pretty=False)
self.assertEqual(response.results, [])
self.assertResponseMatchesSnapshot(response)
@@ -1028,7 +1028,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
where timestamp >= addDays(today(), -10) and json_int = 17
limit 1
"""
- with freeze_time("2025-02-15 22:52:00"):
+ with time_machine.travel("2025-02-15 22:52:00", tick=False):
response = execute_hogql_query(query, team=self.team, pretty=False)
self.assertEqual(response.results, [])
self.assertResponseMatchesSnapshot(response)
@@ -1050,7 +1050,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
GROUP BY major_version
ORDER BY major_version
"""
- with freeze_time("2025-02-15 22:52:00"):
+ with time_machine.travel("2025-02-15 22:52:00", tick=False):
response = execute_hogql_query(query, team=self.team, pretty=False)
self.assertEqual(response.results, [])
self.assertResponseMatchesSnapshot(response)
@@ -1069,7 +1069,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_tuple_access(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
# sample pivot table, testing tuple access
query = """
@@ -1098,7 +1098,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertResponseMatchesSnapshot(response)
def test_null_properties(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
_create_event(
distinct_id="bla",
@@ -1143,7 +1143,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
for person in range(5):
distinct_id = f"person_{person}_{random_uuid}"
- with freeze_time("2020-01-10 00:00:00"):
+ with time_machine.travel("2020-01-10 00:00:00", tick=False):
_create_person(
properties={"name": f"Person {person}", "random_uuid": random_uuid},
team=self.team,
@@ -1157,7 +1157,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
properties={"character": "Luigi"},
)
flush_persons_and_events()
- with freeze_time("2020-01-10 00:10:00"):
+ with time_machine.travel("2020-01-10 00:10:00", tick=False):
_create_event(
distinct_id=distinct_id,
event="random bla",
@@ -1165,7 +1165,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
properties={"character": "Luigi"},
)
flush_persons_and_events()
- with freeze_time("2020-01-10 00:20:00"):
+ with time_machine.travel("2020-01-10 00:20:00", tick=False):
_create_event(
distinct_id=distinct_id,
event="random boo",
@@ -1218,7 +1218,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
for person in range(5):
distinct_id = f"person_{person}_{random_uuid}"
- with freeze_time("2020-01-10 00:00:00"):
+ with time_machine.travel("2020-01-10 00:00:00", tick=False):
_create_person(
properties={"name": f"Person {person}", "random_uuid": random_uuid},
team=self.team,
@@ -1232,7 +1232,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
properties={"character": "Luigi"},
)
flush_persons_and_events()
- with freeze_time("2020-01-10 00:10:00"):
+ with time_machine.travel("2020-01-10 00:10:00", tick=False):
_create_event(
distinct_id=distinct_id,
event="random bla",
@@ -1240,7 +1240,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
properties={"character": "Luigi"},
)
flush_persons_and_events()
- with freeze_time("2020-01-10 00:20:00"):
+ with time_machine.travel("2020-01-10 00:20:00", tick=False):
_create_event(
distinct_id=distinct_id,
event="random boo",
@@ -1345,7 +1345,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_with_pivot_table_1_level(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
# sample pivot table, testing tuple access
query = """
@@ -1384,7 +1384,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_with_pivot_table_2_levels(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
self._create_random_events()
# sample pivot table, testing tuple access
query = """
@@ -1423,7 +1423,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertResponseMatchesSnapshot(response)
def test_property_access_with_arrays(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
_create_person(team=self.team, distinct_ids=[f"P{random_uuid}"], is_identified=True)
_create_event(
@@ -1882,7 +1882,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.results, [(expected,)])
- @freeze_time("2026-08-06 12:00:00")
+ @time_machine.travel("2026-08-06 12:00:00", tick=False)
def test_relative_date_variable_is_resolved_when_the_query_runs(self):
insight_variable = InsightVariable.objects.create(
team=self.team,
@@ -1908,7 +1908,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_hogql_query_filters(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
for i in range(10):
_create_event(
@@ -1980,7 +1980,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
OFFSET 0
"""
- with freeze_time("2025-02-15 22:52:00"):
+ with time_machine.travel("2025-02-15 22:52:00", tick=False):
response = execute_hogql_query(query, team=self.team, pretty=False)
self.assertEqual(response.results, [])
self.assertResponseMatchesSnapshot(response)
@@ -2026,7 +2026,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
)
def test_hogql_query_filters_alias(self):
- with freeze_time("2020-01-10"):
+ with time_machine.travel("2020-01-10", tick=False):
random_uuid = self._create_random_events()
query = "SELECT event, distinct_id from events e WHERE {filters}"
filters = HogQLFilters(
@@ -2068,7 +2068,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_hogql_query_session_filters(self):
- with freeze_time("2024-07-05"):
+ with time_machine.travel("2024-07-05", tick=False):
s1 = str(uuid7("2024-07-03", 42))
s2 = str(uuid7("2024-07-04", 43))
_create_event(
@@ -2103,7 +2103,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_hogql_query_filters_session_date_range(self):
- with freeze_time("2024-07-05"):
+ with time_machine.travel("2024-07-05", tick=False):
s1 = str(uuid7("2024-07-03", 42))
s2 = str(uuid7("2024-07-05", 43))
_create_event(
@@ -2135,18 +2135,18 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.results, [(s2, "https://example.com/2")])
def test_events_sessions_table(self):
- with freeze_time("2020-01-10 12:00:00"):
+ with time_machine.travel("2020-01-10 12:00:00", tick=False):
random_uuid = self._create_random_events()
session_id = str(uuid7())
- with freeze_time("2020-01-10 12:10:00"):
+ with time_machine.travel("2020-01-10 12:10:00", tick=False):
_create_event(
distinct_id=random_uuid,
event="random event",
team=self.team,
properties={"$session_id": session_id},
)
- with freeze_time("2020-01-10 12:20:00"):
+ with time_machine.travel("2020-01-10 12:20:00", tick=False):
_create_event(
distinct_id=random_uuid,
event="random event",
diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.py
index 3ab1117c5834..43b19d8a9149 100644
--- a/posthog/hogql/test/test_resolver.py
+++ b/posthog/hogql/test/test_resolver.py
@@ -3,7 +3,7 @@ from typing import Any, ClassVar, Optional, cast
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -454,7 +454,7 @@ class TestResolver(BaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_resolve_constant_type(self):
- with freeze_time("2020-01-10 00:00:00"):
+ with time_machine.travel("2020-01-10 00:00:00", tick=False):
expr = self._select(
"SELECT 1, 'boo', true, 1.1232, null, {date}, {datetime}, {uuid}, {array}, {array12}, {tuple}",
placeholders={
diff --git a/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py b/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py
index b677ee1bf415..46592a247618 100644
--- a/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -205,7 +205,7 @@ class TestEventTaxonomyQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_caching(self):
now = timezone.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
_create_person(
distinct_ids=["person1"],
properties={"email": "[email protected]"},
@@ -239,14 +239,14 @@ class TestEventTaxonomyQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.cache_key, key)
self.assertEqual(len(response.results), 0)
- with freeze_time(now + timedelta(minutes=59)):
+ with time_machine.travel(now + timedelta(minutes=59), tick=False):
runner = EventTaxonomyQueryRunner(team=self.team, query=EventTaxonomyQuery(event="event1"))
response = runner.run()
assert isinstance(response, CachedEventTaxonomyQueryResponse)
self.assertEqual(len(response.results), 0)
- with freeze_time(now + timedelta(minutes=61)):
+ with time_machine.travel(now + timedelta(minutes=61), tick=False):
runner = EventTaxonomyQueryRunner(team=self.team, query=EventTaxonomyQuery(event="event1"))
response = runner.run()
diff --git a/posthog/hogql_queries/ai/test/test_sessions_aggregation.py b/posthog/hogql_queries/ai/test/test_sessions_aggregation.py
index 115e790787ca..3ac4648530e8 100644
--- a/posthog/hogql_queries/ai/test/test_sessions_aggregation.py
+++ b/posthog/hogql_queries/ai/test/test_sessions_aggregation.py
@@ -1,7 +1,7 @@
import uuid
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from parameterized import parameterized
@@ -131,7 +131,7 @@ def _create_ai_embedding_event(
)
-@freeze_time("2025-01-16T00:00:00Z")
+@time_machine.travel("2025-01-16T00:00:00Z", tick=False)
class TestSessionsAggregation(ClickhouseTestMixin, BaseTest):
def _execute_sessions_query(self) -> list[dict]:
flush_persons_and_events()
diff --git a/posthog/hogql_queries/ai/test/test_team_taxonomy_query_runner.py b/posthog/hogql_queries/ai/test/test_team_taxonomy_query_runner.py
index 7da7fcb46353..bf721aa7dd88 100644
--- a/posthog/hogql_queries/ai/test/test_team_taxonomy_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_team_taxonomy_query_runner.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -65,7 +65,7 @@ class TestTeamTaxonomyQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_caching(self):
now = timezone.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
_create_person(
distinct_ids=["person1"],
properties={"email": "[email protected]"},
@@ -100,14 +100,14 @@ class TestTeamTaxonomyQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Cached: still 1 CH result + well-known events
self.assertEqual(len(response.results), 1 + len(WELL_KNOWN_EVENT_NAMES))
- with freeze_time(now + timedelta(minutes=59)):
+ with time_machine.travel(now + timedelta(minutes=59), tick=False):
runner = TeamTaxonomyQueryRunner(team=self.team, query=TeamTaxonomyQuery())
response = runner.run()
assert isinstance(response, CachedTeamTaxonomyQueryResponse)
self.assertEqual(len(response.results), 1 + len(WELL_KNOWN_EVENT_NAMES))
- with freeze_time(now + timedelta(minutes=61)):
+ with time_machine.travel(now + timedelta(minutes=61), tick=False):
runner = TeamTaxonomyQueryRunner(team=self.team, query=TeamTaxonomyQuery())
response = runner.run()
diff --git a/posthog/hogql_queries/ai/test/test_trace_neighbors_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_neighbors_query_runner.py
index 0301d11d215e..2a44fa2e51b6 100644
--- a/posthog/hogql_queries/ai/test/test_trace_neighbors_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_trace_neighbors_query_runner.py
@@ -2,7 +2,7 @@ import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person
from posthog.schema import DateRange, EventPropertyFilter, PropertyOperator, TraceNeighborsQuery
@@ -391,7 +391,7 @@ class TestTraceNeighborsQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(response.olderTraceId, "trace1")
self.assertEqual(response.newerTraceId, "trace4")
- @freeze_time("2025-01-15T00:00:00Z")
+ @time_machine.travel("2025-01-15T00:00:00Z", tick=False)
def test_filter_test_accounts(self):
"""Test that test account filtering works correctly."""
self.team.test_account_filters = [
diff --git a/posthog/hogql_queries/ai/test/test_trace_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
index 018f1a59a5bd..11008edb2a37 100644
--- a/posthog/hogql_queries/ai/test/test_trace_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
@@ -4,7 +4,7 @@ from typing import Any, Literal, TypedDict
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries
from unittest.mock import patch
@@ -445,7 +445,7 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
response.results[0].events[0].properties.items(),
)
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_person_properties(self):
"""Test that person data is not loaded server-side (frontend handles it via lazy loader)."""
_create_person(distinct_ids=["person1"], team=self.team, properties={"email": "[email protected]"})
@@ -462,7 +462,7 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(response.results[0].distinctId, "person1")
self.assertIsNone(response.results[0].person)
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_distinct_id_prefers_trace_event(self):
"""When a $ai_trace event exists, its distinct_id should be used even if
other events in the trace have an earlier timestamp with a different distinct_id."""
@@ -492,7 +492,7 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 1)
self.assertEqual(response.results[0].distinctId, "real-user-id")
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_distinct_id_falls_back_without_trace_event(self):
"""When no $ai_trace event exists, the distinct_id from the earliest event should be used."""
_create_person(distinct_ids=["person1"], team=self.team)
@@ -511,7 +511,7 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 1)
self.assertEqual(response.results[0].distinctId, "person1")
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_date_range(self):
"""Test that date range filtering works correctly."""
_create_person(distinct_ids=["person1"], team=self.team)
@@ -1852,7 +1852,7 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
# Should sum: Span A (100) + Generation B (200) = 300, exclude Generation A1
self.assertEqual(response.results[0].totalLatency, 300.0)
- @freeze_time("2025-01-15T12:00:00Z")
+ @time_machine.travel("2025-01-15T12:00:00Z", tick=False)
def test_fallback_to_events_when_ai_events_empty(self):
"""When ai_events has no data, the fallback to events returns correct results with proper numeric types."""
trace_id = "fallback-test-trace"
diff --git a/posthog/hogql_queries/ai/test/test_traces_query_runner.py b/posthog/hogql_queries/ai/test/test_traces_query_runner.py
index cd9e573403a7..d152bcffbbce 100644
--- a/posthog/hogql_queries/ai/test/test_traces_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_traces_query_runner.py
@@ -4,7 +4,7 @@ from typing import Any, Literal, TypedDict
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries
from unittest.mock import patch
@@ -270,7 +270,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
for key, value in expected_event.items():
self.assertEqual(event_dict[key], value, f"Field {key} does not match")
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_field_mapping(self):
_create_person(distinct_ids=["person1"], team=self.team)
@@ -346,7 +346,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
# test_trace_id_filter removed - TracesQuery no longer supports traceId parameter
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_sums_distinguish_reported_zero_from_no_report(self):
_create_person(distinct_ids=["person1"], team=self.team)
_create_ai_generation_event(
@@ -388,7 +388,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertIsNone(unpriced_trace.inputCost)
self.assertIsNone(unpriced_trace.inputTokens)
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_stored_sentiment_evaluations_are_mapped_to_trace_and_generation(self):
event_uuid = uuid.uuid4()
generation_id = "generation-id-1"
@@ -429,7 +429,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
assert len(trace.events) == 1
assert trace.events[0].sentiment is None
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
@patch("posthog.hogql_queries.ai.traces_query_runner.load_trace_sentiment_evaluations")
def test_stored_sentiment_evaluation_lookup_is_opt_in(self, mock_load_sentiment):
_create_person(distinct_ids=["person1"], team=self.team)
@@ -454,7 +454,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
assert response.results[0].sentiment is None
mock_load_sentiment.assert_not_called()
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_pagination(self):
_create_person(distinct_ids=["person1"], team=self.team)
@@ -478,7 +478,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(response.hasMore, False)
self.assertEqual([t.id for t in response.results], ["trace_2", "trace_1", "trace_0"])
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_pagination_with_multi_event_traces(self):
"""
Regression test: pagination must not produce overlapping results when traces
@@ -530,7 +530,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
# Walking the pages visits every trace exactly once
self.assertEqual(page1_ids + page2_ids + page3_ids, ["trace_4", "trace_3", "trace_2", "trace_1", "trace_0"])
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_maps_all_fields(self):
_create_person(distinct_ids=["person1"], team=self.team)
_create_ai_generation_event(
@@ -564,7 +564,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
response.results[0].events[0].properties.items(),
)
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_distinct_id_returned(self):
_create_person(distinct_ids=["person1"], team=self.team, properties={"email": "[email protected]"})
_create_ai_generation_event(
@@ -577,7 +577,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertIsNone(response.results[0].person)
self.assertEqual(response.results[0].distinctId, "person1")
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_distinct_id_prefers_trace_event(self):
"""When a $ai_trace event exists, its distinct_id should be used even if
other events in the trace have an earlier timestamp with a different distinct_id."""
@@ -604,7 +604,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 1)
self.assertEqual(response.results[0].distinctId, "real-user-id")
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
def test_distinct_id_falls_back_without_trace_event(self):
"""When no $ai_trace event exists, the distinct_id from the earliest event should be used."""
_create_person(distinct_ids=["person1"], team=self.team)
@@ -626,7 +626,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 1)
self.assertEqual(response.results[0].distinctId, "person1")
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_date_range(self):
_create_person(distinct_ids=["person1"], team=self.team)
_create_ai_generation_event(
@@ -2030,7 +2030,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
# Should sum: Span A (100) + Generation B (200) = 300, exclude Generation A1
self.assertEqual(response.results[0].totalLatency, 300.0)
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_person_id_filter(self):
"""Test that personId parameter filters traces by person."""
person1 = _create_person(distinct_ids=["user1"], team=self.team)
@@ -2066,7 +2066,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
response = TracesQueryRunner(team=self.team, query=TracesQuery(personId=str(uuid.uuid4()))).calculate()
self.assertEqual(len(response.results), 0)
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_group_key_filter(self):
"""Test that groupKey and groupTypeIndex parameters filter traces by group."""
@@ -2217,7 +2217,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
)
self.assertEqual(runner.paginator.limit, 50)
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_export_returns_more_than_default_limit(self):
"""Test that export context returns more than 100 traces (the old hardcoded default)."""
_create_person(distinct_ids=["person1"], team=self.team)
@@ -2239,7 +2239,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 110)
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_random_order(self):
"""Test that randomOrder parameter returns traces in random order instead of timestamp DESC."""
_create_person(distinct_ids=["person1"], team=self.team)
@@ -2277,7 +2277,7 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertGreaterEqual(trace_num, 0)
self.assertLess(trace_num, 10)
- @freeze_time("2025-01-16T00:00:00Z")
+ @time_machine.travel("2025-01-16T00:00:00Z", tick=False)
def test_request_and_web_search_cost_aggregation(self):
_create_person(distinct_ids=["person1"], team=self.team)
trace_id = "trace_cost_components"
diff --git a/posthog/hogql_queries/endpoints/test/test_endpoints_usage_query_runners.py b/posthog/hogql_queries/endpoints/test/test_endpoints_usage_query_runners.py
index 4751b2a67303..d57432522fa3 100644
--- a/posthog/hogql_queries/endpoints/test/test_endpoints_usage_query_runners.py
+++ b/posthog/hogql_queries/endpoints/test/test_endpoints_usage_query_runners.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from parameterized import parameterized
@@ -41,7 +41,7 @@ class TestSafeFloat(APIBaseTest):
class TestEndpointsUsageOverviewQueryRunner(ClickhouseTestMixin, QueryMatchingTest, APIBaseTest):
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_overview_query_sql(self):
query = EndpointsUsageOverviewQuery(
kind="EndpointsUsageOverviewQuery",
@@ -53,7 +53,7 @@ class TestEndpointsUsageOverviewQueryRunner(ClickhouseTestMixin, QueryMatchingTe
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_overview_query_with_endpoint_filter_sql(self):
query = EndpointsUsageOverviewQuery(
kind="EndpointsUsageOverviewQuery",
@@ -66,7 +66,7 @@ class TestEndpointsUsageOverviewQueryRunner(ClickhouseTestMixin, QueryMatchingTe
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_overview_query_with_materialization_filter_sql(self):
query = EndpointsUsageOverviewQuery(
kind="EndpointsUsageOverviewQuery",
@@ -79,7 +79,7 @@ class TestEndpointsUsageOverviewQueryRunner(ClickhouseTestMixin, QueryMatchingTe
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_row_to_metrics_dict(self):
query = EndpointsUsageOverviewQuery(
kind="EndpointsUsageOverviewQuery",
@@ -110,7 +110,7 @@ class TestEndpointsUsageOverviewQueryRunner(ClickhouseTestMixin, QueryMatchingTe
(0.0, 0.0, 0.0),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_calculate_change_pct(self, current, previous, expected):
query = EndpointsUsageOverviewQuery(
kind="EndpointsUsageOverviewQuery",
@@ -124,7 +124,7 @@ class TestEndpointsUsageOverviewQueryRunner(ClickhouseTestMixin, QueryMatchingTe
class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest, APIBaseTest):
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_requests_metric_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -137,7 +137,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_bytes_read_metric_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -150,7 +150,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_cpu_seconds_metric_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -163,7 +163,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_error_rate_metric_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -176,7 +176,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_hourly_interval_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -190,7 +190,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_weekly_interval_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -204,7 +204,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_with_endpoint_breakdown_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -218,7 +218,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_with_materialization_breakdown_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -232,7 +232,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_trends_query_with_status_breakdown_sql(self):
query = EndpointsUsageTrendsQuery(
kind="EndpointsUsageTrendsQuery",
@@ -248,7 +248,7 @@ class TestEndpointsUsageTrendsQueryRunner(ClickhouseTestMixin, QueryMatchingTest
class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest, APIBaseTest):
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_by_endpoint_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
@@ -261,7 +261,7 @@ class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest,
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_by_materialization_type_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
@@ -274,7 +274,7 @@ class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest,
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_by_api_key_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
@@ -287,7 +287,7 @@ class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest,
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_by_status_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
@@ -300,7 +300,7 @@ class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest,
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_with_pagination_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
@@ -315,7 +315,7 @@ class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest,
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_with_order_by_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
@@ -329,7 +329,7 @@ class TestEndpointsUsageTableQueryRunner(ClickhouseTestMixin, QueryMatchingTest,
self.assertQueryMatchesSnapshot(hogql)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_table_query_with_materialization_filter_sql(self):
query = EndpointsUsageTableQuery(
kind="EndpointsUsageTableQuery",
diff --git a/posthog/hogql_queries/groups/test/test_groups_query_runner.py b/posthog/hogql_queries/groups/test/test_groups_query_runner.py
index bff7d62272b4..eb7a8337f987 100644
--- a/posthog/hogql_queries/groups/test/test_groups_query_runner.py
+++ b/posthog/hogql_queries/groups/test/test_groups_query_runner.py
@@ -2,7 +2,7 @@ import datetime
from datetime import timedelta
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from django.test import override_settings
@@ -54,7 +54,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
properties={"name": f"proj{i}.inc"},
)
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner(self):
self.create_standard_test_groups()
@@ -74,7 +74,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[1][0], {"display_name": "org1.inc", "key": "org1"})
self.assertEqual(result.results[2][0], {"display_name": "org2.inc", "key": "org2"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
def test_groups_query_runner_with_numeric_name_property(self):
# Regression: a numeric `name` property type made coalesce(properties.name, key)
# resolve to Variant(Float64, String), which clickhouse_driver can't deserialize.
@@ -107,7 +107,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[1][0], {"display_name": "10", "key": "org1"})
self.assertEqual(result.results[2][0], {"display_name": "20", "key": "org2"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner_with_offset(self):
self.create_standard_test_groups()
@@ -125,7 +125,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.columns, ["group_name"])
self.assertEqual(result.results[0][0], {"display_name": "org2.inc", "key": "org2"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner_with_property_columns(self):
self.create_standard_test_groups()
@@ -148,7 +148,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[1][2], 0)
self.assertEqual(result.results[2][2], 300)
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_search(self):
self.create_standard_test_groups()
@@ -166,7 +166,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.columns, ["group_name"])
self.assertEqual(result.results[0][0], {"display_name": "org2.inc", "key": "org2"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_search_ranking(self):
create_group_type_mapping(
@@ -206,7 +206,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[3][0], {"display_name": "best_test_ever", "key": "contains2"})
self.assertEqual(result.results[4][0], {"display_name": "my_test_group", "key": "contains"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_search_ranking_with_key_fallback(self):
"""Test search ranking when groups don't have name property and fall back to key"""
@@ -242,7 +242,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[1][0]["key"], "api_v2", "Prefix match ranked second")
self.assertEqual(result.results[2][0]["key"], "legacy_api", "Contains match ranked last")
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_search_ordering_with_user_orderby(self):
"""Test that similarity ordering comes after user-specified orderBy, not after default created_at DESC"""
@@ -283,7 +283,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[2][0]["display_name"], "testing", "Prefix match ranked last, lowest arr")
self.assertEqual(result.results[2][2], "100")
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner_with_order_by(self):
self.create_standard_test_groups()
@@ -341,7 +341,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[1][0], {"display_name": "org1.inc", "key": "org1"})
self.assertEqual(result.results[2][0], {"display_name": "org0.inc", "key": "org0"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner_with_string_property(self):
self.create_standard_test_groups()
@@ -368,7 +368,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.columns, ["group_name"])
self.assertEqual(result.results[0][0], {"display_name": "org0.inc", "key": "org0"})
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner_with_numeric_property(self):
self.create_standard_test_groups()
@@ -398,7 +398,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.results[0][2], 150)
self.assertEqual(result.results[1][2], 300)
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
@snapshot_clickhouse_queries
def test_groups_query_runner_normalize_multiple_groups(self):
create_group_type_mapping_without_created_at(
diff --git a/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py b/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py
index a3e6a5791ac5..f81a1093540e 100644
--- a/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py
+++ b/posthog/hogql_queries/properties_timeline/test/test_query_date_range.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from posthog.hogql_queries.properties_timeline.query_date_range import QueryDateRange
@@ -7,7 +7,7 @@ from posthog.models.filters.filter import Filter
class TestQueryDateRange(APIBaseTest):
def test_parsed_date(self):
- with freeze_time("2021-08-25T00:00:00.000Z"):
+ with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):
filter = Filter(
data={
"date_from": "-48h",
@@ -30,7 +30,7 @@ class TestQueryDateRange(APIBaseTest):
)
def test_parsed_date_hour(self):
- with freeze_time("2021-08-25T00:00:00.000Z"):
+ with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):
filter = Filter(
data={
"date_from": "-48h",
@@ -53,7 +53,7 @@ class TestQueryDateRange(APIBaseTest):
) # ensure last hour is included
def test_parsed_date_middle_of_hour(self):
- with freeze_time("2021-08-25T00:00:00.000Z"):
+ with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):
filter = Filter(
data={
"date_from": "2021-08-23 05:00:00",
@@ -77,7 +77,7 @@ class TestQueryDateRange(APIBaseTest):
) # ensure last hour is included
def test_parsed_date_week_rounded(self):
- with freeze_time("2021-08-25T00:00:00.000Z"):
+ with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):
filter = Filter(
data={
"date_from": "-7d",
@@ -100,7 +100,7 @@ class TestQueryDateRange(APIBaseTest):
)
def test_is_hourly(self):
- with freeze_time("2021-08-25T00:00:00.000Z"):
+ with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):
filter = Filter(
data={
"date_from": "-48h",
@@ -115,7 +115,7 @@ class TestQueryDateRange(APIBaseTest):
self.assertTrue(query_date_range.is_hourly("-48h"))
self.assertFalse(query_date_range.is_hourly(None))
- with freeze_time("2021-08-25T00:00:00.000Z"):
+ with time_machine.travel("2021-08-25T00:00:00.000Z", tick=False):
filter = Filter(
data={
"date_from": "-48h",
diff --git a/posthog/hogql_queries/test/test_actors_query_runner.py b/posthog/hogql_queries/test/test_actors_query_runner.py
index bfa1abf22c0b..543f40175a45 100644
--- a/posthog/hogql_queries/test/test_actors_query_runner.py
+++ b/posthog/hogql_queries/test/test_actors_query_runner.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
@@ -255,9 +255,9 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIsNotNone(results, "The query should execute without errors")
- @freeze_time("2023-05-10T15:23:00Z")
+ @time_machine.travel("2023-05-10T15:23:00Z", tick=False)
def test_persons_query_with_insight_actors_source_order_by_last_seen(self):
- with freeze_time("2023-05-07T15:23:00Z"):
+ with time_machine.travel("2023-05-07T15:23:00Z", tick=False):
_create_person(
properties={
"email": f"[email protected]",
@@ -268,7 +268,7 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
is_identified=True,
)
_create_event(distinct_id="jump-the-gun", event="clicky", team=self.team)
- with freeze_time("2023-05-09T15:23:00Z"):
+ with time_machine.travel("2023-05-09T15:23:00Z", tick=False):
_create_person(
properties={
"email": "[email protected]",
@@ -430,9 +430,9 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.results, [[f"jacob4@{self.random_uuid}.posthog.com"]])
def test_source_lifecycle_query(self):
- with freeze_time("2021-01-01T12:00:00Z"):
+ with time_machine.travel("2021-01-01T12:00:00Z", tick=False):
self.random_uuid = self._create_random_persons()
- with freeze_time("2021-01-03T12:00:00Z"):
+ with time_machine.travel("2021-01-03T12:00:00Z", tick=False):
source_query = LifecycleQuery(
series=[EventsNode(event="clicky-4")],
properties=[
@@ -967,7 +967,7 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
for uuid in person_uuids:
self.assertIn(uuid, result)
- @freeze_time("2023-05-07T15:23:00Z")
+ @time_machine.travel("2023-05-07T15:23:00Z", tick=False)
def test_last_seen_for_persons(self):
_create_person(
properties={"email": "[email protected]"},
diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.py
index 26da2e39ffb9..8820e37987f8 100644
--- a/posthog/hogql_queries/test/test_events_query_runner.py
+++ b/posthog/hogql_queries/test/test_events_query_runner.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import Any, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -44,7 +44,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
distinct_id, timestamp, event_properties = row[0], row[1], row[2]
# Optional 4th element pins the event uuid so cursor-pagination SQL stays deterministic.
event_uuid = row[3] if len(row) > 3 else None
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
if distinct_id not in distinct_ids_handled:
person_result.append(
_create_person(
@@ -95,7 +95,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def _run_boolean_field_query(self, filter: EventPropertyFilter):
- with freeze_time("2020-01-11T12:01:00"):
+ with time_machine.travel("2020-01-11T12:01:00", tick=False):
query = EventsQuery(
after="-24h",
event="$pageview",
@@ -153,7 +153,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-11T12:01:00"):
+ with time_machine.travel("2020-01-11T12:01:00", tick=False):
query = EventsQuery(kind="EventsQuery", after="-24h", orderBy=["timestamp ASC"], select=["*"])
response = EventsQueryRunner(query=query, team=self.team).run()
@@ -221,7 +221,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
flush_persons_and_events()
- with freeze_time("2020-01-11T12:01:00"):
+ with time_machine.travel("2020-01-11T12:01:00", tick=False):
query = EventsQuery(
after="-24h",
event="$pageview",
@@ -255,7 +255,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
flush_persons_and_events()
- with freeze_time("2020-01-11T12:01:00"):
+ with time_machine.travel("2020-01-11T12:01:00", tick=False):
query = EventsQuery(
after="-24h",
event="$pageview",
@@ -377,7 +377,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
flush_persons_and_events()
- with freeze_time("2020-01-11T12:01:00"):
+ with time_machine.travel("2020-01-11T12:01:00", tick=False):
query = EventsQuery(
after="2020-01-11",
before="2020-01-15",
@@ -402,7 +402,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_element_chain_property_filter(self):
# Create an event with 'div' in elements_chain
_create_event(
@@ -487,7 +487,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.results[0][0]["properties"]["attr"], "no div")
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_presorted_events_table(self):
self._create_events(
data=[
@@ -536,7 +536,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert isinstance(response, CachedEventsQueryResponse)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_presorted_events_table_order_by_event(self):
"""Test presorted optimization when ordering by event column."""
self._create_events(data=[("p2", "2021-01-20T12:00:14Z", {})], event="beta_event")
@@ -563,7 +563,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[2][0]["distinct_id"] == "p3"
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_presorted_events_table_order_by_property(self):
"""Test presorted optimization when ordering by property."""
self._create_events(
@@ -595,7 +595,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[2][0]["distinct_id"] == "p3"
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_presorted_events_table_multiple_order_by(self):
"""Test presorted optimization with multiple ORDER BY clauses."""
self._create_events(
@@ -930,7 +930,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
all_results = []
for offset in (0, 2, 4):
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["properties.idx", "timestamp"],
@@ -989,7 +989,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
all_results = []
cursor = None
for _ in range(3):
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["properties.idx", "timestamp"],
@@ -1029,7 +1029,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
all_results = []
cursor = None
for _ in range(3):
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["properties.idx", "timestamp"],
@@ -1064,7 +1064,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["event", "timestamp"],
@@ -1088,7 +1088,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["count()", "timestamp"],
@@ -1112,7 +1112,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["*"],
@@ -1143,7 +1143,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
all_indices: list[str] = []
cursor = None
for _ in range(5):
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["uuid", "properties.idx", "timestamp"],
@@ -1180,7 +1180,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
event="custom_event",
)
- with freeze_time("2020-01-12"):
+ with time_machine.travel("2020-01-12", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["*"],
@@ -1202,7 +1202,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
self.organization.save()
- @freeze_time("2020-01-11T12:00:05Z")
+ @time_machine.travel("2020-01-11T12:00:05Z", tick=False)
def test_restricted_person_properties_stripped_from_person_column(self):
from posthog.models import PropertyDefinition
@@ -1247,7 +1247,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert "email" not in person_data["properties"]
assert "name" in person_data["properties"]
- @freeze_time("2020-01-11T12:00:05Z")
+ @time_machine.travel("2020-01-11T12:00:05Z", tick=False)
def test_restricted_event_property_in_select_raises_error(self):
from posthog.hogql.errors import ResolutionError
@@ -1283,7 +1283,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
with self.assertRaises(ResolutionError):
runner.run()
- @freeze_time("2020-01-11T12:00:05Z")
+ @time_machine.travel("2020-01-11T12:00:05Z", tick=False)
def test_restricted_display_property_does_not_break_person_display_name(self):
from posthog.models import PropertyDefinition
@@ -1327,7 +1327,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) > 0
assert response.results[0][0]["display_name"] == "Test User"
- @freeze_time("2020-01-11T12:00:05Z")
+ @time_machine.travel("2020-01-11T12:00:05Z", tick=False)
def test_users_with_different_restrictions_get_different_cache_keys(self):
self._enable_property_access_control()
@@ -1376,7 +1376,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
"Users with different property access restrictions must get different cache keys"
)
- @freeze_time("2020-01-11T12:00:05Z")
+ @time_machine.travel("2020-01-11T12:00:05Z", tick=False)
def test_users_without_restrictions_share_cache_key(self):
# no property access control rules — both users should share the same cache key
other_user = self._create_user("[email protected]")
@@ -1398,7 +1398,7 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
"Users without property access restrictions should share the same cache key"
)
- @freeze_time("2020-01-11T12:00:05Z")
+ @time_machine.travel("2020-01-11T12:00:05Z", tick=False)
def test_cached_results_not_served_across_restriction_boundaries(self):
from posthog.models import PropertyDefinition
diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.py
index e8fae4322540..02c728262425 100644
--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py
+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py
@@ -2,7 +2,7 @@ from datetime import datetime
from typing import cast
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events
from unittest.mock import MagicMock, patch
@@ -448,13 +448,13 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):
def test_person_metadata_cohort_membership_end_to_end(self) -> None:
# Persons need a deterministic created_at in BOTH Postgres and ClickHouse.
- # _create_person with immediate=True under freeze_time writes both stores; we also
+ # _create_person with immediate=True under a frozen clock writes both stores; we also
# pass created_at explicitly so the assertion stays valid even if Postgres stops
# using auto_now_add or default=timezone.now in a future migration.
utc = ZoneInfo("UTC")
old_dt = datetime(2023, 1, 1, tzinfo=utc)
new_dt = datetime(2025, 1, 1, tzinfo=utc)
- with freeze_time(old_dt):
+ with time_machine.travel(old_dt, tick=False):
old_person = _create_person(
team=self.team,
distinct_ids=["old"],
@@ -462,7 +462,7 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):
created_at=old_dt,
immediate=True,
)
- with freeze_time(new_dt):
+ with time_machine.travel(new_dt, tick=False):
new_person = _create_person(
team=self.team,
distinct_ids=["new"],
@@ -577,7 +577,7 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):
utc = ZoneInfo("UTC")
old_dt = datetime(2023, 1, 1, tzinfo=utc)
new_dt = datetime(2025, 1, 1, tzinfo=utc)
- with freeze_time(old_dt):
+ with time_machine.travel(old_dt, tick=False):
old_person = _create_person(
team=self.team,
distinct_ids=["old_neg"],
@@ -585,7 +585,7 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):
created_at=old_dt,
immediate=True,
)
- with freeze_time(new_dt):
+ with time_machine.travel(new_dt, tick=False):
new_person = _create_person(
team=self.team,
distinct_ids=["new_neg"],
diff --git a/posthog/hogql_queries/test/test_insight_actors_query_runner.py b/posthog/hogql_queries/test/test_insight_actors_query_runner.py
index b5a3a8b5eba9..284c127cb46f 100644
--- a/posthog/hogql_queries/test/test_insight_actors_query_runner.py
+++ b/posthog/hogql_queries/test/test_insight_actors_query_runner.py
@@ -1,7 +1,7 @@
import re
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -54,7 +54,7 @@ class TestInsightActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
for id, timestamps in data:
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[id],
diff --git a/posthog/hogql_queries/test/test_query_failure_handling.py b/posthog/hogql_queries/test/test_query_failure_handling.py
index edd586d6520a..8327bc43f98b 100644
--- a/posthog/hogql_queries/test/test_query_failure_handling.py
+++ b/posthog/hogql_queries/test/test_query_failure_handling.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.test import SimpleTestCase
@@ -106,7 +106,7 @@ class TestQueryFailureHandling(SimpleTestCase):
assert budget_for_limit_context(limit_context) == expected
def test_build_failure_exception_preserves_class_and_status(self):
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
original_detail = str(ClickHouseQueryTimeOut().detail)
record = _record("timeout", 3, original_detail, open_until=datetime.now(UTC) + timedelta(minutes=2))
@@ -129,7 +129,7 @@ class TestQueryFailureHandling(SimpleTestCase):
assert "was not run again" in str(error.detail)
def test_build_failure_exception_first_failure_wording(self):
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
original_detail = str(ClickHouseQueryMemoryLimitExceeded().detail)
record = _record("memory_limit", 1, original_detail, open_until=datetime.now(UTC) + timedelta(minutes=2))
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 28fe25d876ac..647931b062b3 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -5,7 +5,7 @@ from typing import Any, Literal, Optional
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, cleanup_materialized_columns
from unittest import mock
@@ -536,7 +536,7 @@ class TestQueryRunner(BaseTest):
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
- with freeze_time(datetime(2023, 2, 4, 13, 37, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37, 42), tick=False):
# in cache-only mode, returns cache miss response if uncached
response = runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)
self.assertIsInstance(response, CacheMissResponse)
@@ -558,28 +558,28 @@ class TestQueryRunner(BaseTest):
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
self.assertEqual(response.is_cached, False)
- with freeze_time(datetime(2023, 2, 4, 13, 37 + 11, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37 + 11, 42), tick=False):
# returns fresh response if stale
response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
self.assertEqual(response.is_cached, False)
mock_on_commit.assert_not_called()
- with freeze_time(datetime(2023, 2, 4, 13, 37 + 11 + 5, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37 + 11 + 5, 42), tick=False):
# returns cached response - does not kick off calculation in the background
response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE)
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
self.assertEqual(response.is_cached, True)
mock_on_commit.assert_not_called()
- with freeze_time(datetime(2023, 2, 4, 13, 37 + 11 + 11, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37 + 11 + 11, 42), tick=False):
# returns cached response but kicks off calculation in the background
response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE)
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
self.assertEqual(response.is_cached, True)
mock_on_commit.assert_called_once()
- with freeze_time(datetime(2023, 2, 4, 23, 55, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 23, 55, 42), tick=False):
# returns cached response for extended time
response = runner.run(execution_mode=ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE)
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
@@ -587,7 +587,7 @@ class TestQueryRunner(BaseTest):
mock_on_commit.assert_called_once() # still once
mock_on_commit.reset_mock()
- with freeze_time(datetime(2023, 2, 5, 23, 55, 42)):
+ with time_machine.travel(datetime(2023, 2, 5, 23, 55, 42), tick=False):
# returns cached response for extended time but finally kicks off calculation in the background
response = runner.run(execution_mode=ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE)
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
@@ -600,7 +600,7 @@ class TestQueryRunner(BaseTest):
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
- with freeze_time(datetime(2023, 2, 4, 13, 37, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37, 42), tick=False):
# in cache-only mode, returns cache miss response if uncached
response = runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)
self.assertIsInstance(response, CacheMissResponse)
@@ -620,7 +620,7 @@ class TestQueryRunner(BaseTest):
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
self.assertEqual(response.is_cached, True)
- with freeze_time(datetime(2023, 2, 4, 13, 37 + 11, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37 + 11, 42), tick=False):
# returns fresh response if stale
response = runner.run(
execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS
@@ -657,12 +657,12 @@ class TestQueryRunner(BaseTest):
return last_refresh + timedelta(hours=24) if last_refresh else None
start = datetime(2023, 2, 4, 13, 37, 42, tzinfo=UTC)
- with freeze_time(start):
+ with time_machine.travel(start, tick=False):
OpinionatedQueryRunner(query={"some_attr": "bla"}, team=self.team).run(
execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
)
- with freeze_time(start + cache_age):
+ with time_machine.travel(start + cache_age, tick=False):
response = OpinionatedQueryRunner(query={"some_attr": "bla"}, team=self.team).run(
execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
cache_age_seconds=1800,
@@ -673,7 +673,7 @@ class TestQueryRunner(BaseTest):
TestQueryRunner = self.setup_test_query_runner_class()
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
- with freeze_time(datetime(2023, 2, 4, 13, 37, 42, tzinfo=UTC)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37, 42, tzinfo=UTC), tick=False):
response = runner.run(
execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
cache_age_seconds=999,
@@ -739,7 +739,7 @@ class TestQueryRunner(BaseTest):
mock_query_cache_cls.return_value = mock_cache_manager
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
- with freeze_time(datetime(2023, 2, 4, 13, 37, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37, 42), tick=False):
response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
self.assertIsInstance(response, TheTestCachedBasicQueryResponse)
@@ -936,7 +936,7 @@ class TestQueryRunner(BaseTest):
TestQueryRunner = self.setup_test_query_runner_class()
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
- with freeze_time(datetime(2023, 2, 4, 13, 37, 42)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 37, 42), tick=False):
runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
before_success = QUERY_EXECUTION_TOTAL.labels(
@@ -948,7 +948,7 @@ class TestQueryRunner(BaseTest):
before_duration_sum = QUERY_EXECUTION_DURATION.labels(query_type="TestQuery")._sum.get()
# Cache is fresh (< 10 min old), so this hits the cache without recalculating
- with freeze_time(datetime(2023, 2, 4, 13, 38, 0)):
+ with time_machine.travel(datetime(2023, 2, 4, 13, 38, 0), tick=False):
runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
assert (
@@ -1785,9 +1785,9 @@ class TestQueryFailureCaching(BaseTest):
runner_class = setup_test_query_runner_class()
runner = runner_class(query={"some_attr": "bla"}, team=self.team)
with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
- with freeze_time("2026-01-01T00:00:00Z") as frozen:
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS) # seed the cache
- frozen.tick(timedelta(minutes=15)) # past the harness's 10-minute staleness window
+ frozen.shift(timedelta(minutes=15)) # past the harness's 10-minute staleness window
mock_calculate = self._open_breaker(runner_class, runner)
with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
@@ -1841,7 +1841,7 @@ class TestQueryFailureCaching(BaseTest):
runner_class = setup_test_query_runner_class()
runner = runner_class(query={"some_attr": "bla"}, team=self.team)
with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
- with freeze_time("2026-01-01T00:00:00Z") as frozen:
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
with mock.patch.object(
runner_class, "_calculate", autospec=True, side_effect=ClickHouseQueryTimeOut()
) as mock_calculate:
@@ -1857,7 +1857,7 @@ class TestQueryFailureCaching(BaseTest):
# once the backoff elapses, the next run executes (the real harness _calculate),
# succeeds, and closes the breaker
- frozen.tick(BASE_BACKOFF + timedelta(seconds=1))
+ frozen.shift(BASE_BACKOFF + timedelta(seconds=1))
runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
assert QueryFailureCache(runner.get_cache_key()).get_open() is None
diff --git a/posthog/hogql_queries/test/test_session_batch_events_query_runner.py b/posthog/hogql_queries/test/test_session_batch_events_query_runner.py
index 8135ee97cbed..64c81ad831f9 100644
--- a/posthog/hogql_queries/test/test_session_batch_events_query_runner.py
+++ b/posthog/hogql_queries/test/test_session_batch_events_query_runner.py
@@ -2,7 +2,7 @@ import uuid
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from posthog.schema import (
@@ -34,7 +34,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
"""Create events for testing with session IDs."""
for distinct_id, timestamp, session_id, event_properties in data:
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
# Add session_id to event properties
properties = {**event_properties, "$session_id": session_id}
_create_event(
@@ -59,7 +59,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
# Query to get all
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
query = EventsQuery(
kind="EventsQuery",
select=["*"],
@@ -93,7 +93,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user4", "2025-01-11T15:00:01Z", self.session_4_id, {"page": "/signup"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
# Create query for sessions 1, 2, and 3 (excluding session_4)
query = create_session_batch_events_query(
session_ids=[self.session_1_id, self.session_2_id, self.session_3_id],
@@ -140,7 +140,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user1", "2025-01-11T12:00:01Z", self.session_1_id, {"page": "/home"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
# Query for multiple sessions, but only one has events
query = create_session_batch_events_query(
session_ids=[self.session_1_id, self.session_2_id, self.session_3_id],
@@ -167,7 +167,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
# Create a feature flag event that should be ignored by default
- with freeze_time("2025-01-11T12:01:00Z"):
+ with time_machine.travel("2025-01-11T12:01:00Z", tick=False):
_create_event(
team=self.team,
event="$feature_flag_called",
@@ -177,7 +177,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
# Query the events with and without ignoring the feature flag event
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
for ignore_status in [True, False]:
if ignore_status:
# Use default ignore settings
@@ -218,7 +218,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user2", "2025-01-11T13:00:01Z", self.session_2_id, {"page": "/about"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
# Create query with group_by_session=False
query = SessionBatchEventsQuery(
session_ids=[self.session_1_id, self.session_2_id],
@@ -247,7 +247,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
# Query with custom field selection
query = create_session_batch_events_query(
session_ids=[self.session_1_id],
@@ -275,7 +275,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user1", "2025-01-11T12:00:01Z", self.session_1_id, {"page": "/home"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
query = create_session_batch_events_query(
session_ids=[self.session_1_id],
before="2025-01-12T00:00:00",
@@ -311,7 +311,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user2", "2025-01-11T13:00:01Z", self.session_2_id, {"page": "/about"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
query = create_session_batch_events_query(
session_ids=[self.session_1_id, self.session_2_id],
before="2025-01-12T00:00:00",
@@ -342,7 +342,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user1", "2025-01-11T12:00:01Z", self.session_1_id, {"page": "/home"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
query = SessionBatchEventsQuery(
session_ids=[self.session_1_id],
select=["event", "timestamp", "properties.$session_id"],
@@ -373,7 +373,7 @@ class TestSessionBatchEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("user1", "2025-01-11T12:04:00Z", session_id, {"page": "/page5"}),
]
)
- with freeze_time("2025-01-11T16:00:00"):
+ with time_machine.travel("2025-01-11T16:00:00", tick=False):
all_events = []
# Test first page with limit=2, offset=0
query = create_session_batch_events_query(
diff --git a/posthog/hogql_queries/test/test_sessions_query_runner.py b/posthog/hogql_queries/test/test_sessions_query_runner.py
index d809908f0c7b..b06f088603e3 100644
--- a/posthog/hogql_queries/test/test_sessions_query_runner.py
+++ b/posthog/hogql_queries/test/test_sessions_query_runner.py
@@ -1,7 +1,7 @@
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -50,7 +50,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
session_id = session_id_map[session_key]
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
if distinct_id not in distinct_ids_seen:
persons.append(
_create_person(
@@ -87,7 +87,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -113,7 +113,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T15:00:00Z"):
+ with time_machine.travel("2024-01-01T15:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -144,7 +144,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-05T00:00:00Z"):
+ with time_machine.travel("2024-01-05T00:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-02",
before="2024-01-03T23:59:59Z",
@@ -170,7 +170,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T15:00:00Z"):
+ with time_machine.travel("2024-01-01T15:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -200,7 +200,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -229,7 +229,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -257,7 +257,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -322,7 +322,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -357,7 +357,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.team.save()
self.team.refresh_from_db()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -389,7 +389,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.team.save()
self.team.refresh_from_db()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -429,7 +429,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
"""An empty-string property should fall through to the next configured property."""
timestamp = "2024-01-01T12:00:00Z"
session_id = str(uuid7(timestamp))
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["user1"],
@@ -448,7 +448,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.team.save()
self.team.refresh_from_db()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -488,7 +488,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.team.save()
self.team.refresh_from_db()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -515,7 +515,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -546,7 +546,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -576,7 +576,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -607,7 +607,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -635,7 +635,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -659,7 +659,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -684,7 +684,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -710,7 +710,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -736,7 +736,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -763,7 +763,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -792,7 +792,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -818,7 +818,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -855,7 +855,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -888,7 +888,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -935,7 +935,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -968,7 +968,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -994,7 +994,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1044,7 +1044,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1086,7 +1086,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
properties={"age": 25},
)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
_create_event(
team=self.team,
event="$pageview",
@@ -1096,7 +1096,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1150,7 +1150,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1179,7 +1179,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
# Get session IDs first
all_query = SessionsQuery(after="2024-01-01", kind="SessionsQuery", select=["session_id"])
all_response = SessionsQueryRunner(query=all_query, team=self.team).run()
@@ -1216,7 +1216,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
all_query = SessionsQuery(after="2024-01-01", kind="SessionsQuery", select=["session_id"])
all_response = SessionsQueryRunner(query=all_query, team=self.team).run()
assert isinstance(all_response, CachedSessionsQueryResponse)
@@ -1246,7 +1246,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1260,7 +1260,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_session_id_event_property_with_other_event_filters_keeps_subquery(self):
"""When $session_id is combined with an event name filter, we still need the events subquery
for the event filter, but $session_id is applied directly to sessions."""
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1293,7 +1293,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1308,7 +1308,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) == 3
def test_default_after_is_one_hour(self):
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(kind="SessionsQuery", select=["session_id"])
runner = SessionsQueryRunner(query=query, team=self.team)
printed = to_printed_hogql(runner.to_query(), team=self.team)
@@ -1330,7 +1330,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1379,7 +1379,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1438,7 +1438,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
cohort.calculate_people_ch(pending_version=0)
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
@@ -1458,7 +1458,7 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
self.team.save()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
query = SessionsQuery(
after="2024-01-01",
kind="SessionsQuery",
diff --git a/posthog/hogql_queries/test/test_sessions_timeline_query_runner.py b/posthog/hogql_queries/test/test_sessions_timeline_query_runner.py
index 692313b18616..29e92afb4c44 100644
--- a/posthog/hogql_queries/test/test_sessions_timeline_query_runner.py
+++ b/posthog/hogql_queries/test/test_sessions_timeline_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from unittest.mock import patch
@@ -633,7 +633,7 @@ class TestSessionsTimelineQueryRunner(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2023-10-01T16:00:00Z"):
+ with time_machine.travel("2023-10-01T16:00:00Z", tick=False):
runner = self._create_runner(SessionsTimelineQuery())
response = runner.calculate()
diff --git a/posthog/hogql_queries/utils/test/test_timestamp_utils.py b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
index 1fae477d79da..67ca9bf4c5a4 100644
--- a/posthog/hogql_queries/utils/test/test_timestamp_utils.py
+++ b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
@@ -1,7 +1,7 @@
import datetime
from zoneinfo import ZoneInfo
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from unittest.mock import MagicMock, patch
@@ -352,7 +352,7 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
cached_earliest_timestamp = get_earliest_timestamp_from_series(self.team, series)
self.assertEqual(cached_earliest_timestamp, earliest_timestamp)
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_unfiltered_earliest_timestamp_returns_earliest_event(self):
_create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2020-01-04T14:10:00Z")
_create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2020-01-06T14:10:00Z")
@@ -362,7 +362,7 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
2020, 1, 4, 14, 10, tzinfo=datetime.UTC
)
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_unfiltered_earliest_timestamp_floors_at_2015(self):
# Events before 2015-01-01 are treated as corrupt and ignored.
_create_event(team=self.team, event="sign up", distinct_id="1", timestamp="1984-01-06T14:10:00Z")
@@ -373,12 +373,12 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
assert get_earliest_timestamp_unfiltered(self.team) == datetime.datetime(2015, 1, 1, 1, tzinfo=datetime.UTC)
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_unfiltered_earliest_timestamp_falls_back_when_no_events(self):
# No events: fall back to now - DEFAULT_EARLIEST_TIME_DELTA (one week).
assert get_earliest_timestamp_unfiltered(self.team) == datetime.datetime(2021, 1, 14, tzinfo=datetime.UTC)
- @freeze_time("2021-01-21")
+ @time_machine.travel("2021-01-21", tick=False)
def test_unfiltered_earliest_timestamp_caches_real_result(self):
_create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2021-01-01T12:00:00Z")
flush_persons_and_events()
diff --git a/posthog/management/commands/test/test_send_ai_observability_usage_report.py b/posthog/management/commands/test/test_send_ai_observability_usage_report.py
index 0ca547334a67..504191fa25ec 100644
--- a/posthog/management/commands/test/test_send_ai_observability_usage_report.py
+++ b/posthog/management/commands/test/test_send_ai_observability_usage_report.py
@@ -1,5 +1,5 @@
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.core.cache import cache
@@ -23,7 +23,7 @@ def _clear_dispatch_claims() -> None:
cache.delete(usage_report_dispatch_lock_key(date))
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_send_ai_observability_usage_report_defaults_to_current_date() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report")
@@ -35,7 +35,7 @@ def test_send_ai_observability_usage_report_defaults_to_current_date() -> None:
)
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_send_ai_observability_usage_report_preserves_passed_date() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--date=2026-07-15")
@@ -47,7 +47,7 @@ def test_send_ai_observability_usage_report_preserves_passed_date() -> None:
)
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_send_ai_observability_usage_report_dry_run_runs_sync_with_dry_run_flag() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--dry-run")
@@ -60,7 +60,7 @@ def test_send_ai_observability_usage_report_dry_run_runs_sync_with_dry_run_flag(
mock_send_reports.delay.assert_not_called()
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_send_ai_observability_usage_report_async_dispatches_delay_with_parsed_org_ids() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--async", "--org-ids=org-a, org-b,")
@@ -73,7 +73,7 @@ def test_send_ai_observability_usage_report_async_dispatches_delay_with_parsed_o
mock_send_reports.assert_not_called()
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_second_dispatch_for_the_same_date_is_refused() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--async")
@@ -84,7 +84,7 @@ def test_second_dispatch_for_the_same_date_is_refused() -> None:
mock_send_reports.delay.assert_called_once()
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_dispatch_claims_are_scoped_per_date() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--async", "--date=2026-07-15")
@@ -93,7 +93,7 @@ def test_dispatch_claims_are_scoped_per_date() -> None:
assert mock_send_reports.delay.call_count == 2
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_dry_run_does_not_claim_the_date() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--dry-run")
@@ -102,7 +102,7 @@ def test_dry_run_does_not_claim_the_date() -> None:
mock_send_reports.delay.assert_called_once()
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_failed_dispatch_releases_the_claim() -> None:
with patch(TASK_PATH) as mock_send_reports:
mock_send_reports.delay.side_effect = [RuntimeError("broker down"), None]
@@ -114,7 +114,7 @@ def test_failed_dispatch_releases_the_claim() -> None:
assert mock_send_reports.delay.call_count == 2
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_equivalent_date_spellings_share_one_claim() -> None:
with patch(TASK_PATH) as mock_send_reports:
call_command("send_ai_observability_usage_report", "--async", "--date=2026-07-15")
@@ -129,7 +129,7 @@ def test_equivalent_date_spellings_share_one_claim() -> None:
)
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_unreadable_date_is_rejected_without_dispatching() -> None:
with patch(TASK_PATH) as mock_send_reports:
with pytest.raises(CommandError, match="Could not read"):
@@ -138,7 +138,7 @@ def test_unreadable_date_is_rejected_without_dispatching() -> None:
mock_send_reports.delay.assert_not_called()
-@freeze_time("2026-07-22T12:00:00Z")
+@time_machine.travel("2026-07-22T12:00:00Z", tick=False)
def test_failed_synchronous_run_releases_the_claim() -> None:
with patch(TASK_PATH) as mock_send_reports:
mock_send_reports.side_effect = [RuntimeError("clickhouse down"), None]
diff --git a/posthog/management/commands/test/test_send_usage_report.py b/posthog/management/commands/test/test_send_usage_report.py
index 5646d1aad3b3..15cfa79f4d9b 100644
--- a/posthog/management/commands/test/test_send_usage_report.py
+++ b/posthog/management/commands/test/test_send_usage_report.py
@@ -1,10 +1,10 @@
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.core.management import call_command
-@freeze_time("2026-06-02T12:00:00Z")
+@time_machine.travel("2026-06-02T12:00:00Z", tick=False)
def test_send_usage_report_defaults_to_current_date() -> None:
with patch("posthog.management.commands.send_usage_report.send_all_org_usage_reports") as mock_send_reports:
call_command("send_usage_report")
@@ -17,7 +17,7 @@ def test_send_usage_report_defaults_to_current_date() -> None:
)
-@freeze_time("2026-06-02T12:00:00Z")
+@time_machine.travel("2026-06-02T12:00:00Z", tick=False)
def test_send_usage_report_preserves_passed_date() -> None:
with patch("posthog.management.commands.send_usage_report.send_all_org_usage_reports") as mock_send_reports:
call_command("send_usage_report", "--date=2026-05-31")
diff --git a/posthog/models/file_system/test/test_file_system_view_log.py b/posthog/models/file_system/test/test_file_system_view_log.py
index ba58cce40825..0f545f43f8ae 100644
--- a/posthog/models/file_system/test/test_file_system_view_log.py
+++ b/posthog/models/file_system/test/test_file_system_view_log.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Protocol, cast
-from freezegun import freeze_time
+import time_machine
from django.test import TestCase
@@ -34,13 +34,13 @@ class TestFileSystemViewLog(TestCase):
)
dashboard = Dashboard.objects.create(team=self.team, name="Dashboard", created_by=self.user)
- with freeze_time("2024-01-01T10:00:00Z"):
+ with time_machine.travel("2024-01-01T10:00:00Z", tick=False):
log_file_system_view(user=self.user, obj=insight)
- with freeze_time("2024-01-02T10:00:00Z"):
+ with time_machine.travel("2024-01-02T10:00:00Z", tick=False):
log_file_system_view(user=self.user, obj=dashboard)
- with freeze_time("2024-01-03T10:00:00Z"):
+ with time_machine.travel("2024-01-03T10:00:00Z", tick=False):
log_file_system_view(user=self.user, obj=dashboard)
view_order = [
@@ -89,13 +89,13 @@ class TestFileSystemViewLog(TestCase):
last_modified_by=self.user,
)
- with freeze_time("2024-02-01T10:00:00Z"):
+ with time_machine.travel("2024-02-01T10:00:00Z", tick=False):
log_file_system_view(user=self.user, obj=insight)
- with freeze_time("2024-02-01T10:00:03Z"):
+ with time_machine.travel("2024-02-01T10:00:03Z", tick=False):
log_file_system_view(user=self.user, obj=insight)
- with freeze_time("2024-02-01T10:00:10Z"):
+ with time_machine.travel("2024-02-01T10:00:10Z", tick=False):
log_file_system_view(user=self.user, obj=insight)
logs = FileSystemViewLog.objects.filter(team=self.team, user=self.user, type="insight", ref=insight.short_id)
diff --git a/posthog/models/filters/test/test_retention_filter.py b/posthog/models/filters/test/test_retention_filter.py
index d1ea8be84ed3..efcc17e4d899 100644
--- a/posthog/models/filters/test/test_retention_filter.py
+++ b/posthog/models/filters/test/test_retention_filter.py
@@ -1,4 +1,4 @@
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from posthog.models.filters.retention_filter import RetentionFilter
@@ -8,7 +8,7 @@ class TestFilter(BaseTest):
maxDiff = None
def test_fill_date_from_and_date_to(self):
- with freeze_time("2020-10-01T12:00:00Z"):
+ with time_machine.travel("2020-10-01T12:00:00Z", tick=False):
filter = RetentionFilter(data={}, team=self.team)
self.assertEqual(filter.date_from.isoformat(), "2020-09-21T00:00:00+00:00")
self.assertEqual(filter.date_to.isoformat(), "2020-10-02T00:00:00+00:00")
@@ -59,7 +59,7 @@ class TestFilter(BaseTest):
"sampling_factor": "",
}
- with freeze_time("2020-10-01T12:00:00Z"):
+ with time_machine.travel("2020-10-01T12:00:00Z", tick=False):
filter = RetentionFilter(data={"date_to": "2020-08-01"}, team=self.team)
self.assertEqual(filter.date_from.isoformat(), "2020-07-22T00:00:00+00:00")
self.assertEqual(filter.date_to.isoformat(), "2020-08-02T00:00:00+00:00")
diff --git a/posthog/models/property/test/test_relative_date.py b/posthog/models/property/test/test_relative_date.py
index f8b0e5ad1398..7b673222169d 100644
--- a/posthog/models/property/test/test_relative_date.py
+++ b/posthog/models/property/test/test_relative_date.py
@@ -1,7 +1,7 @@
import datetime
import unittest
-from freezegun import freeze_time
+import time_machine
from dateutil import tz
@@ -10,7 +10,7 @@ from posthog.models.property.relative_date import relative_date_parse_for_featur
class TestRelativeDateParsing(unittest.TestCase):
def test_invalid_input(self):
- with freeze_time("2020-01-01T12:01:20.1340Z"):
+ with time_machine.travel("2020-01-01T12:01:20.1340Z", tick=False):
assert relative_date_parse_for_feature_flag_matching("1") is None
assert relative_date_parse_for_feature_flag_matching("1x") is None
assert relative_date_parse_for_feature_flag_matching("1.2y") is None
@@ -29,7 +29,7 @@ class TestRelativeDateParsing(unittest.TestCase):
assert relative_date_parse_for_feature_flag_matching("100000000000000000y") is None
def test_hour_parsing(self):
- with freeze_time("2020-01-01T12:01:20.1340Z"):
+ with time_machine.travel("2020-01-01T12:01:20.1340Z", tick=False):
assert relative_date_parse_for_feature_flag_matching("1h") == datetime.datetime(
2020, 1, 1, 11, 1, 20, 134000, tzinfo=tz.gettz("UTC")
)
@@ -54,7 +54,7 @@ class TestRelativeDateParsing(unittest.TestCase):
) == relative_date_parse_for_feature_flag_matching("2d")
def test_day_parsing(self):
- with freeze_time("2020-01-01T12:01:20.1340Z"):
+ with time_machine.travel("2020-01-01T12:01:20.1340Z", tick=False):
assert relative_date_parse_for_feature_flag_matching("1d") == datetime.datetime(
2019, 12, 31, 12, 1, 20, 134000, tzinfo=tz.gettz("UTC")
)
@@ -76,7 +76,7 @@ class TestRelativeDateParsing(unittest.TestCase):
)
def test_week_parsing(self):
- with freeze_time("2020-01-01T12:01:20.1340Z"):
+ with time_machine.travel("2020-01-01T12:01:20.1340Z", tick=False):
assert relative_date_parse_for_feature_flag_matching("1w") == datetime.datetime(
2019, 12, 25, 12, 1, 20, 134000, tzinfo=tz.gettz("UTC")
)
@@ -98,7 +98,7 @@ class TestRelativeDateParsing(unittest.TestCase):
)
def test_month_parsing(self):
- with freeze_time("2020-01-01T12:01:20.1340Z"):
+ with time_machine.travel("2020-01-01T12:01:20.1340Z", tick=False):
assert relative_date_parse_for_feature_flag_matching("1m") == datetime.datetime(
2019, 12, 1, 12, 1, 20, 134000, tzinfo=tz.gettz("UTC")
)
@@ -119,7 +119,7 @@ class TestRelativeDateParsing(unittest.TestCase):
"12m"
) == relative_date_parse_for_feature_flag_matching("1y")
- with freeze_time("2020-04-03T00:00:00"):
+ with time_machine.travel("2020-04-03T00:00:00", tick=False):
assert relative_date_parse_for_feature_flag_matching("1m") == datetime.datetime(
2020, 3, 3, 0, 0, 0, tzinfo=tz.gettz("UTC")
)
@@ -141,7 +141,7 @@ class TestRelativeDateParsing(unittest.TestCase):
) == relative_date_parse_for_feature_flag_matching("1y")
def test_year_parsing(self):
- with freeze_time("2020-01-01T12:01:20.1340Z"):
+ with time_machine.travel("2020-01-01T12:01:20.1340Z", tick=False):
assert relative_date_parse_for_feature_flag_matching("1y") == datetime.datetime(
2019, 1, 1, 12, 1, 20, 134000, tzinfo=tz.gettz("UTC")
)
diff --git a/posthog/models/team/test_production_event_activation.py b/posthog/models/team/test_production_event_activation.py
index d171dd79e333..503265050224 100644
--- a/posthog/models/team/test_production_event_activation.py
+++ b/posthog/models/team/test_production_event_activation.py
@@ -2,7 +2,7 @@ from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest import TestCase
from unittest.mock import MagicMock, patch
@@ -438,7 +438,7 @@ class TestEvaluateAndMarkTeamBatch(ClickhouseTestMixin, BaseTest):
def test_qualifying_team_is_flagged(self) -> None:
_seed_event(self.team.id, properties={"$host": PRODUCTION_HOST})
- with freeze_time("2026-06-05T12:00:00Z"), _mock_capture():
+ with time_machine.travel("2026-06-05T12:00:00Z", tick=False), _mock_capture():
qualifying, marked = evaluate_and_mark_team_batch(
[self.team.id], now=datetime(2026, 6, 5, 12, 0, 0, tzinfo=UTC)
)
@@ -469,7 +469,7 @@ class TestEvaluateAndMarkTeamBatch(ClickhouseTestMixin, BaseTest):
def test_non_qualifying_team_only_gets_last_checked_at_bumped(self) -> None:
_seed_event(self.team.id, properties={"$host": "localhost:3000"})
- with freeze_time("2026-06-05T12:00:00Z"):
+ with time_machine.travel("2026-06-05T12:00:00Z", tick=False):
qualifying, marked = evaluate_and_mark_team_batch(
[self.team.id], now=datetime(2026, 6, 5, 12, 0, 0, tzinfo=UTC)
)
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 39dfe03c6a35..1ece8e2df30d 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, call, patch
@@ -948,7 +948,7 @@ class TestGitHubIntegrationModel(BaseTest):
def test_github_integration_refresh_token(self, mock_client_request):
mock_client_request.side_effect = self.mock_github_client_request(status_code=201)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = GitHubIntegration.integration_from_installation_id(
"INSTALLATION_ID",
self.team.id,
@@ -957,7 +957,7 @@ class TestGitHubIntegrationModel(BaseTest):
assert GitHubIntegration(integration).access_token_expired() is False
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
assert GitHubIntegration(integration).access_token_expired() is True
GitHubIntegration(integration).refresh_access_token()
@@ -1074,12 +1074,12 @@ class TestGitHubIntegrationModel(BaseTest):
{"access_token": "ACCESS_TOKEN"},
)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
assert GitHubIntegration(integration).ensure_account_name() is False
assert GitHubIntegration(integration).ensure_account_name() is False
assert mock_client_request.call_count == 1
- with freeze_time("2024-01-01T12:06:00Z"):
+ with time_machine.travel("2024-01-01T12:06:00Z", tick=False):
GitHubIntegration(integration).ensure_account_name()
assert mock_client_request.call_count == 2
integration.refresh_from_db()
@@ -1146,7 +1146,7 @@ class TestGitHubIntegrationModel(BaseTest):
integration = self.create_integration({"expires_at": 3600}, {"token": "REFRESH"})
mock_client_request.side_effect = self.mock_github_client_request(status_code=400, error_text="error")
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration.errors = ""
integration.save()
@@ -1163,7 +1163,7 @@ class TestGitHubIntegrationModel(BaseTest):
"""Test that errors field is reset to empty string after successful refresh_access_token"""
mock_client_request.side_effect = self.mock_github_client_request(status_code=201)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = GitHubIntegration.integration_from_installation_id(
"INSTALLATION_ID",
self.team.id,
@@ -1899,7 +1899,7 @@ class TestGitHubIntegrationModel(BaseTest):
else:
raise_if_github_rate_limited(response) # must not raise
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
def test_raise_if_github_rate_limited_populates_fields(self):
reset_timestamp = int(time.time()) + 60
response = MagicMock()
@@ -1916,7 +1916,7 @@ class TestGitHubIntegrationModel(BaseTest):
assert exc_info.value.reset_at == reset_timestamp
assert exc_info.value.retry_after == 30
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
def test_raise_if_github_rate_limited_derives_retry_after_from_reset_at(self):
reset_timestamp = int(time.time()) + 45
response = MagicMock()
diff --git a/posthog/models/test/integration/test_google_cloud.py b/posthog/models/test/integration/test_google_cloud.py
index fb40f119079d..6115057c15bf 100644
--- a/posthog/models/test/integration/test_google_cloud.py
+++ b/posthog/models/test/integration/test_google_cloud.py
@@ -5,7 +5,7 @@ from datetime import datetime
from typing import Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -49,7 +49,7 @@ class TestGoogleCloudIntegrationModel(BaseTest):
mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)
mock_credentials.return_value.refresh = lambda _: None
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = GoogleCloudIntegration.integration_from_key(
"google-pubsub",
self.mock_keyfile,
@@ -77,7 +77,7 @@ class TestGoogleCloudIntegrationModel(BaseTest):
mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)
mock_credentials.return_value.refresh = lambda _: None
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = GoogleCloudIntegration.integration_from_key(
"google-pubsub",
self.mock_keyfile,
@@ -85,10 +85,10 @@ class TestGoogleCloudIntegrationModel(BaseTest):
self.user,
)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
assert GoogleCloudIntegration(integration).access_token_expired() is False
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
assert GoogleCloudIntegration(integration).access_token_expired() is True
mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600 * 3)
@@ -130,7 +130,7 @@ class TestGoogleCloudIntegrationModel(BaseTest):
sensitive_config=self.mock_keyfile,
)
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
GoogleCloudIntegration(integration).refresh_access_token()
# After refresh, sensitive_config should be migrated to the nested structure
@@ -151,7 +151,7 @@ class TestGoogleCloudIntegrationModel(BaseTest):
mock_credentials.return_value.expiry = datetime.fromtimestamp(1704110400 + 3600)
mock_credentials.return_value.refresh = lambda _: None
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = GoogleCloudIntegration.integration_from_key(
"google-pubsub",
self.mock_keyfile,
@@ -159,7 +159,7 @@ class TestGoogleCloudIntegrationModel(BaseTest):
self.user,
)
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
token = GoogleCloudIntegration(integration).get_access_token()
assert token == "ACCESS_TOKEN"
diff --git a/posthog/models/test/integration/test_model.py b/posthog/models/test/integration/test_model.py
index 71efff5c7f3b..558d88ee1c49 100644
--- a/posthog/models/test/integration/test_model.py
+++ b/posthog/models/test/integration/test_model.py
@@ -5,7 +5,7 @@ import time
from typing import Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -43,7 +43,7 @@ class TestIntegrationModel(BaseTest):
def test_sensitive_config_encrypted(self):
# Fernet encryption is deterministic, but has a temporal component and utilizes os.urandom() for the IV
- with freeze_time("2024-01-01T00:01:00Z"):
+ with time_machine.travel("2024-01-01T00:01:00Z", tick=False):
with patch("os.urandom", return_value=b"\x00" * 16):
integration = self.create_integration("slack")
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index baea6f207aca..640849a30855 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -9,7 +9,7 @@ from typing import Optional
from urllib.parse import parse_qs, urlencode
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -155,7 +155,7 @@ class TestOauthIntegrationModel(BaseTest):
"expires_in": 3600,
}
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = OauthIntegration.integration_from_oauth_response(
"salesforce",
self.team.id,
@@ -327,7 +327,7 @@ class TestOauthIntegrationModel(BaseTest):
],
}
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = OauthIntegration.integration_from_oauth_response(
"hubspot",
self.team.id,
@@ -378,7 +378,7 @@ class TestOauthIntegrationModel(BaseTest):
"expires_in": 3600,
}
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = OauthIntegration.integration_from_oauth_response(
"linkedin-ads",
self.team.id,
@@ -405,22 +405,22 @@ class TestOauthIntegrationModel(BaseTest):
def test_integration_access_token_expired(self):
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
# Access token is not expired
assert not OauthIntegration(integration).access_token_expired()
- with freeze_time(now + timedelta(seconds=1000) - timedelta(seconds=501)):
+ with time_machine.travel(now + timedelta(seconds=1000) - timedelta(seconds=501), tick=False):
# After the expiry but before the threshold it is not expired
assert not OauthIntegration(integration).access_token_expired()
- with freeze_time(now + timedelta(seconds=1000) - timedelta(seconds=499)):
+ with time_machine.travel(now + timedelta(seconds=1000) - timedelta(seconds=499), tick=False):
# After the threshold it is expired
assert OauthIntegration(integration).access_token_expired()
- with freeze_time(now + timedelta(seconds=1000)):
+ with time_machine.travel(now + timedelta(seconds=1000), tick=False):
# After the threshold it is expired
assert OauthIntegration(integration).access_token_expired()
@@ -435,7 +435,7 @@ class TestOauthIntegrationModel(BaseTest):
integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -481,7 +481,7 @@ class TestOauthIntegrationModel(BaseTest):
integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -501,7 +501,7 @@ class TestOauthIntegrationModel(BaseTest):
integration = self.create_integration(kind="tiktok-ads", config={"expires_in": 1000})
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -527,7 +527,7 @@ class TestOauthIntegrationModel(BaseTest):
integration = self.create_integration(kind="hubspot", config={"expires_in": 1000, "refreshed_at": 1700000000})
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -680,7 +680,7 @@ class TestOauthIntegrationModel(BaseTest):
integration.errors = "TOKEN_REFRESH_FAILED"
integration.save()
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -705,7 +705,7 @@ class TestOauthIntegrationModel(BaseTest):
config["refresh_failure_count"] = prior_failures
integration = self.create_integration(kind="hubspot", config=config)
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -947,7 +947,7 @@ class TestOauthIntegrationModel(BaseTest):
# Note: no expires_in field
}
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = OauthIntegration.integration_from_oauth_response(
"salesforce",
self.team.id,
@@ -965,7 +965,7 @@ class TestOauthIntegrationModel(BaseTest):
def test_salesforce_access_token_expired_without_expires_in(self):
"""Test that Salesforce tokens without expires_in info use 1 hour default"""
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
# Create integration without expires_in
integration = self.create_integration(
kind="salesforce",
@@ -975,22 +975,22 @@ class TestOauthIntegrationModel(BaseTest):
oauth_integration = OauthIntegration(integration)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
# Token should not be expired initially
assert not oauth_integration.access_token_expired()
- with freeze_time(now + timedelta(minutes=29)):
+ with time_machine.travel(now + timedelta(minutes=29), tick=False):
# Should not be expired before 30 minutes (half of 1 hour default)
assert not oauth_integration.access_token_expired()
- with freeze_time(now + timedelta(minutes=31)):
+ with time_machine.travel(now + timedelta(minutes=31), tick=False):
# Should be expired after 30 minutes (halfway point of 1 hour)
assert oauth_integration.access_token_expired()
def test_non_salesforce_access_token_expired_without_expires_in(self):
"""Test that non-Salesforce integrations without expires_in return False"""
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
# Create non-Salesforce integration without expires_in - override the default
integration = Integration.objects.create(
team=self.team,
@@ -1001,7 +1001,7 @@ class TestOauthIntegrationModel(BaseTest):
oauth_integration = OauthIntegration(integration)
- with freeze_time(now + timedelta(hours=5)):
+ with time_machine.travel(now + timedelta(hours=5), tick=False):
# Should never expire without expires_in for non-Salesforce
assert not oauth_integration.access_token_expired()
@@ -1017,7 +1017,7 @@ class TestOauthIntegrationModel(BaseTest):
integration = self.create_integration(kind="salesforce", config={"expires_in": 1000})
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -1112,7 +1112,7 @@ class TestOauthIntegrationModel(BaseTest):
integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})
- with freeze_time("2024-01-01T14:00:00Z"):
+ with time_machine.travel("2024-01-01T14:00:00Z", tick=False):
with self.settings(**self.mock_settings):
OauthIntegration(integration).refresh_access_token()
@@ -1388,7 +1388,7 @@ class TestResendIntegrationModel(BaseTest):
"token_type": "Bearer",
}
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
integration = OauthIntegration.integration_from_oauth_response(
"resend",
self.team.id,
diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.py
index e9b390f0d5f4..919af6fa8a4c 100644
--- a/posthog/models/test/test_data_deletion_request.py
+++ b/posthog/models/test/test_data_deletion_request.py
@@ -3,7 +3,7 @@ from collections.abc import Callable
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.core.exceptions import ValidationError
@@ -282,7 +282,7 @@ def test_compile_hogql_predicate_missing_team_raises_validation_error(db):
compile_hogql_predicate(request)
-@freeze_time("2026-06-17T12:00:00Z")
+@time_machine.travel("2026-06-17T12:00:00Z", tick=False)
def test_compile_hogql_predicate_boolean_person_property_not_coerced(team):
"""A boolean-typed person property compared to a non-``true``/``false`` string must not be
coerced to Bool. The coercion (``accurateCastOrNull(transform(...), 'Bool')``) maps the
@@ -599,7 +599,7 @@ def test_cached_compile_hogql_predicate_blank_predicate_skips_compile():
assert cached_compile_hogql_predicate(request) == ("", {})
-@freeze_time("2026-06-17T12:00:00Z")
+@time_machine.travel("2026-06-17T12:00:00Z", tick=False)
@pytest.mark.parametrize(
"overrides,expected_fragment",
[
diff --git a/posthog/models/test/test_firebase_integration.py b/posthog/models/test/test_firebase_integration.py
index 6e8bc604cc05..689313a8184b 100644
--- a/posthog/models/test/test_firebase_integration.py
+++ b/posthog/models/test/test_firebase_integration.py
@@ -1,7 +1,7 @@
import time
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -146,7 +146,7 @@ class TestFirebaseIntegration(BaseTest):
with self.assertRaisesMessage(Exception, "FirebaseIntegration init called with Integration with wrong 'kind'"):
FirebaseIntegration(integration)
- @freeze_time("2024-01-01T00:00:00Z")
+ @time_machine.travel("2024-01-01T00:00:00Z", tick=False)
def test_access_token_not_expired_initially(self):
integration = Integration.objects.create(
team=self.team,
@@ -163,7 +163,7 @@ class TestFirebaseIntegration(BaseTest):
assert wrapper.access_token_expired() is False
- @freeze_time("2024-01-01T00:00:00Z")
+ @time_machine.travel("2024-01-01T00:00:00Z", tick=False)
def test_access_token_expired_after_half_expiry(self):
integration = Integration.objects.create(
team=self.team,
@@ -180,7 +180,7 @@ class TestFirebaseIntegration(BaseTest):
assert wrapper.access_token_expired() is True
- @freeze_time("2024-01-01T00:00:00Z")
+ @time_machine.travel("2024-01-01T00:00:00Z", tick=False)
def test_access_token_expired_custom_threshold(self):
integration = Integration.objects.create(
team=self.team,
diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.py
index 09167651cd6e..f7687cb0ab91 100644
--- a/posthog/models/test/test_oauth.py
+++ b/posthog/models/test/test_oauth.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -115,7 +115,7 @@ class TestOAuthModels(TestCase):
self.assertEqual(app.required_scopes, ["insight:read"])
self.assertEqual(app.ceiling_scopes, ["insight:read", "dashboard:read"])
- @freeze_time("2024-01-01 00:00:00")
+ @time_machine.travel("2024-01-01 00:00:00", tick=False)
def test_create_oauth_application_with_skip_authorization_fails(self):
# Test that creating an application with skip_authorization=True raises an error
with self.assertRaises(ValidationError):
@@ -613,7 +613,7 @@ class TestOAuthModels(TestCase):
self.assertFalse(OAuthGrant.objects.filter(id=grant.id).exists())
self.assertFalse(OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists())
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_revoke_application_sessions_revokes_across_all_users_and_leaves_other_apps(self):
app = self._make_app("Narrowed App", "narrowed_client_id")
other_app = self._make_app("Other App", "other_client_id")
@@ -646,7 +646,7 @@ class TestOAuthModels(TestCase):
self.assertEqual(OAuthRefreshToken.objects.filter(application=app, revoked__isnull=True).count(), 0)
self.assertTrue(OAuthAccessToken.objects.filter(id=survivor.id).exists())
- @freeze_time("2026-01-01 00:00:00")
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
def test_revoke_application_sessions_stamps_sessions_revoked_at(self):
app = self._make_app("Stamped App", "stamped_client_id")
other_app = self._make_app("Untouched App", "untouched_client_id")
diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.py
index c1d76a65bee5..3035114c158b 100644
--- a/posthog/models/test/test_product_intent.py
+++ b/posthog/models/test/test_product_intent.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -64,7 +64,7 @@ class TestProductIntent(BaseTest):
assert intent is not None
assert intent.contexts == {ProductIntentContext.QUICK_START_PRODUCT_SELECTED: 2}
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
def test_register_with_onboarding_sets_onboarding_completed_at(self):
ProductIntent.register(
team=self.team,
@@ -78,7 +78,7 @@ class TestProductIntent(BaseTest):
assert intent.onboarding_completed_at == datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)
assert intent.contexts == {ProductIntentContext.ONBOARDING_PRODUCT_SELECTED___PRIMARY: 1}
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
def test_register_without_onboarding_does_not_set_onboarding_completed_at(self):
ProductIntent.register(
team=self.team,
@@ -92,7 +92,7 @@ class TestProductIntent(BaseTest):
assert intent.onboarding_completed_at is None
assert intent.contexts == {ProductIntentContext.TAXONOMIC_FILTER_EMPTY_STATE: 1}
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_has_activated_data_warehouse_with_valid_query(self):
Insight.objects.create(
team=self.team, query={"kind": "DataVisualizationNode", "source": {"query": "SELECT * FROM custom_table"}}
@@ -100,7 +100,7 @@ class TestProductIntent(BaseTest):
self.assertTrue(self.product_intent.has_activated_data_warehouse())
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_has_activated_data_warehouse_with_excluded_table(self):
Insight.objects.create(
team=self.team, query={"kind": "DataVisualizationNode", "source": {"query": "SELECT * FROM events"}}
@@ -108,9 +108,9 @@ class TestProductIntent(BaseTest):
self.assertFalse(self.product_intent.has_activated_data_warehouse())
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_has_activated_data_warehouse_with_old_insight(self):
- with freeze_time("2024-05-15T12:00:00Z"): # Before June 1st, 2024
+ with time_machine.travel("2024-05-15T12:00:00Z", tick=False): # Before June 1st, 2024
Insight.objects.create(
team=self.team,
query={"kind": "DataVisualizationNode", "source": {"query": "SELECT * FROM custom_table"}},
@@ -118,7 +118,7 @@ class TestProductIntent(BaseTest):
self.assertFalse(self.product_intent.has_activated_data_warehouse())
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_check_and_update_activation_sets_activated_at(self):
Insight.objects.create(
team=self.team, query={"kind": "DataVisualizationNode", "source": {"query": "SELECT * FROM custom_table"}}
@@ -129,7 +129,7 @@ class TestProductIntent(BaseTest):
self.product_intent.refresh_from_db()
assert self.product_intent.activated_at == datetime(2024, 6, 15, 12, 0, 0, tzinfo=UTC)
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_calculate_product_activation_task(self):
# Create an insight that should trigger activation
Insight.objects.create(
@@ -151,13 +151,13 @@ class TestProductIntent(BaseTest):
self.product_intent.refresh_from_db()
self.assertIsNone(self.product_intent.activated_at)
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_calculate_product_activation_skips_activated_products(self):
# Set product as already activated
self.product_intent.activated_at = datetime.now(tz=UTC)
self.product_intent.save()
- with freeze_time(datetime.now(tz=UTC) + timedelta(days=2)):
+ with time_machine.travel(datetime.now(tz=UTC) + timedelta(days=2), tick=False):
calculate_product_activation(self.team.id)
self.product_intent.refresh_from_db()
assert self.product_intent.activated_at == datetime(2024, 6, 15, 12, 0, 0, tzinfo=UTC)
@@ -236,7 +236,7 @@ class TestProductIntent(BaseTest):
self.assertFalse(self.product_intent.has_activated_feature_flags())
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_has_activated_session_replay_with_five_recordings_viewed_and_filters_set(self):
# Create 5 recordings and mark them as viewed
for i in range(5):
@@ -256,7 +256,7 @@ class TestProductIntent(BaseTest):
self.assertTrue(self.product_intent.has_activated_session_replay())
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_has_not_activated_session_replay_with_less_than_five_recordings(self):
# Create a product intent with the filters set
ProductIntent.objects.create(
@@ -276,7 +276,7 @@ class TestProductIntent(BaseTest):
assert self.product_intent.has_activated_session_replay() is False
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_has_not_activated_session_replay_with_unviewed_recordings(self):
# Create a product intent with the filters set
ProductIntent.objects.create(
@@ -319,7 +319,7 @@ class TestProductIntent(BaseTest):
assert self.product_intent.has_activated_session_replay() is False
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@patch("posthog.event_usage.report_user_action")
def test_register_reports_correct_user_action_for_onboarding(self, mock_report_user_action):
ProductIntent.register(
@@ -347,7 +347,7 @@ class TestProductIntent(BaseTest):
team=self.team,
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@patch("posthog.event_usage.report_user_action")
def test_register_reports_correct_user_action_for_non_onboarding(self, mock_report_user_action):
ProductIntent.register(
@@ -375,7 +375,7 @@ class TestProductIntent(BaseTest):
team=self.team,
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@patch("posthog.event_usage.report_user_action")
def test_register_managed_warehouse_intent(self, mock_report_user_action):
# Managed warehouse is a distinct product from data_warehouse imports. Provisioning is the
@@ -511,7 +511,7 @@ class TestProductIntent(BaseTest):
assert self.product_intent.has_activated_product_analytics() is True
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
@patch("posthog.event_usage.report_user_action")
def test_register_tracks_intent_even_when_already_activated(self, mock_report_user_action):
# Create an insight that should trigger activation for data_warehouse
@@ -580,7 +580,7 @@ class TestProductIntent(BaseTest):
Survey.objects.create(team=self.team, name="Survey Test")
assert self.product_intent.has_activated_surveys() is False
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_check_and_update_activation_skips_if_already_activated(self):
# First activate it
Insight.objects.create(
@@ -591,7 +591,7 @@ class TestProductIntent(BaseTest):
initial_last_checked = self.product_intent.activation_last_checked_at
# Move time forward and check again
- with freeze_time("2024-06-16T12:00:00Z"):
+ with time_machine.travel("2024-06-16T12:00:00Z", tick=False):
result = self.product_intent.check_and_update_activation()
self.product_intent.refresh_from_db()
@@ -599,7 +599,7 @@ class TestProductIntent(BaseTest):
assert self.product_intent.activated_at == initial_activated_at # Activation time unchanged
assert self.product_intent.activation_last_checked_at == initial_last_checked # Last checked unchanged
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_check_and_update_activation_updates_last_checked_for_non_activated(self):
initial_last_checked = self.product_intent.activation_last_checked_at
result = self.product_intent.check_and_update_activation()
diff --git a/posthog/models/test/test_subscription_activity_log.py b/posthog/models/test/test_subscription_activity_log.py
index ceef91f632aa..2bedf1e35abd 100644
--- a/posthog/models/test/test_subscription_activity_log.py
+++ b/posthog/models/test/test_subscription_activity_log.py
@@ -2,7 +2,7 @@ from collections.abc import Callable
from datetime import datetime
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -14,7 +14,7 @@ from products.exports.backend.models.subscription import Subscription
from products.product_analytics.backend.facade.models import Insight
-@freeze_time("2022-01-01")
+@time_machine.travel("2022-01-01", tick=False)
class TestSubscriptionActivityLog(BaseTest):
def _create_subscription(self, **kwargs) -> Subscription:
params: dict = {
@@ -32,7 +32,7 @@ class TestSubscriptionActivityLog(BaseTest):
return Subscription.objects.create(**params)
def _subscription_logs(self):
- # Every row shares one created_at under freeze_time, leaving order undefined. The UUIDT
+ # Every row shares one created_at under a frozen clock, leaving order undefined. The UUIDT
# id's per-millisecond series counter increments per insert, so id tie-breaks in insertion order.
return ActivityLog.objects.filter(scope="Subscription").order_by("created_at", "id")
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index 5af100cfccc5..8d7a8b4cc19d 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -62,7 +62,7 @@ class TestSubscriptionScheduling:
),
]
)
- @freeze_time("2024-01-01 08:00:00")
+ @time_machine.travel("2024-01-01 08:00:00", tick=False)
def test_selected_weekdays_control_delivery_dates(
self,
_name: str,
@@ -81,7 +81,7 @@ class TestSubscriptionScheduling:
assert next_delivery_date == expected_next_delivery
- @freeze_time("2024-01-01 08:00:00")
+ @time_machine.travel("2024-01-01 08:00:00", tick=False)
def test_daily_interval_without_a_possible_weekday_returns_none(self) -> None:
next_delivery_date = Subscription._compute_next_delivery_date(
frequency="daily",
@@ -114,7 +114,7 @@ class TestSubscriptionDeliveryConfig:
@patch.object(settings, "JWT_SIGNING_KEY", "not-so-secret")
-@freeze_time("2022-01-01")
+@time_machine.travel("2022-01-01", tick=False)
class TestSubscription(BaseTest):
def _create_insight_subscription(self, **kwargs):
insight = Insight.objects.create(team=self.team)
@@ -269,7 +269,7 @@ class TestSubscription(BaseTest):
subscription.refresh_from_db()
assert subscription.ai_query_plan == (plan if plan_survives else None)
- @freeze_time("2022-01-11 09:55:00")
+ @time_machine.travel("2022-01-11 09:55:00", tick=False)
def test_set_next_delivery_date_when_in_upcoming_delta(self):
subscription = Subscription.objects.create(
id=1,
@@ -286,7 +286,7 @@ class TestSubscription(BaseTest):
assert subscription.next_delivery_date == datetime(2022, 1, 12, 10, 0, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
- @freeze_time("2022-01-11 09:55:00")
+ @time_machine.travel("2022-01-11 09:55:00", tick=False)
def test_set_next_delivery_date_when_days_behind(self):
subscription = Subscription.objects.create(
id=1,
@@ -341,11 +341,11 @@ class TestSubscription(BaseTest):
token = get_unsubscribe_token(subscription, "[email protected]")
- with freeze_time(datetime(2022, 1, 1) + timedelta(days=UNSUBSCRIBE_TOKEN_EXP_DAYS + 1)):
+ with time_machine.travel(datetime(2022, 1, 1) + timedelta(days=UNSUBSCRIBE_TOKEN_EXP_DAYS + 1), tick=False):
with pytest.raises(jwt.exceptions.ExpiredSignatureError):
unsubscribe_using_token(token)
- with freeze_time(datetime(2022, 1, 1) + timedelta(days=UNSUBSCRIBE_TOKEN_EXP_DAYS - 1)):
+ with time_machine.travel(datetime(2022, 1, 1) + timedelta(days=UNSUBSCRIBE_TOKEN_EXP_DAYS - 1), tick=False):
subscription = unsubscribe_using_token(token)
assert "[email protected]" not in subscription.target_value
@@ -662,7 +662,7 @@ class TestSubscription(BaseTest):
]
)
def test_weekday_rrule_edge_cases(self, _name, freeze_date, bysetpos, expected_next):
- with freeze_time(freeze_date):
+ with time_machine.travel(freeze_date, tick=False):
subscription = self._create_insight_subscription(
interval=1,
frequency="monthly",
diff --git a/posthog/models/web_preaggregated/test_web_preaggregated_sql.py b/posthog/models/web_preaggregated/test_web_preaggregated_sql.py
index 62621b56e88e..8758d8d4ea86 100644
--- a/posthog/models/web_preaggregated/test_web_preaggregated_sql.py
+++ b/posthog/models/web_preaggregated/test_web_preaggregated_sql.py
@@ -1,5 +1,5 @@
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person
from posthog.clickhouse.client.execute import sync_execute
@@ -212,7 +212,7 @@ class TestHourlyPartitioningIntegration:
class TestWebPreaggregatedInserts(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
- with freeze_time("2024-01-01T09:00:00Z"):
+ with time_machine.travel("2024-01-01T09:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_0"])
_create_event(
diff --git a/posthog/query_cache/test/test_failures.py b/posthog/query_cache/test/test_failures.py
index ed132e910c66..89c65f310b6c 100644
--- a/posthog/query_cache/test/test_failures.py
+++ b/posthog/query_cache/test/test_failures.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from django.core.cache import caches
from django.test import SimpleTestCase
@@ -66,7 +66,7 @@ class TestQueryFailureCache(SimpleTestCase):
def test_load_dependent_breaker_opens_after_threshold_and_backs_off_exponentially(self):
failure_cache = QueryFailureCache("cache_key_1")
- with freeze_time("2026-01-01T00:00:00Z") as frozen:
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
for _ in range(KIND_POLICIES["timeout"].open_threshold - 1):
failure_cache.record_failure("timeout", "failed")
assert failure_cache.get_open() is None
@@ -76,7 +76,7 @@ class TestQueryFailureCache(SimpleTestCase):
assert record.open_until == datetime.now(UTC) + BASE_BACKOFF
assert failure_cache.get_open() is not None
- frozen.tick(BASE_BACKOFF + timedelta(seconds=1))
+ frozen.shift(BASE_BACKOFF + timedelta(seconds=1))
assert failure_cache.get_open() is None
record = failure_cache.record_failure("timeout", "failed")
assert record is not None
@@ -85,7 +85,7 @@ class TestQueryFailureCache(SimpleTestCase):
@parameterized.expand([("memory_limit",), ("query_size",), ("too_many_bytes",)])
def test_deterministic_kinds_open_on_first_failure(self, kind):
failure_cache = QueryFailureCache(f"cache_key_instant_{kind}")
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
record = failure_cache.record_failure(kind, "failed")
assert record is not None
assert record.consecutive_failures == 1
@@ -99,7 +99,7 @@ class TestQueryFailureCache(SimpleTestCase):
def test_backoff_is_capped_and_survives_high_failure_counts(self):
# 50 failures is past the point where uncapped backoff math overflows timedelta.
failure_cache = QueryFailureCache("cache_key_2")
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
record = None
for _ in range(50):
record = failure_cache.record_failure("timeout", "failed")
@@ -117,7 +117,7 @@ class TestQueryFailureCache(SimpleTestCase):
def test_clear_closes_breaker_and_resets_count(self):
failure_cache = QueryFailureCache("cache_key_3")
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
for _ in range(3):
failure_cache.record_failure("memory_limit", "failed")
assert failure_cache.get_open() is not None
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py
index f6713c3ab3f5..48d61e795d30 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, create_person_id_override_by_distinct_id
from unittest.mock import patch
@@ -24,7 +24,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SES
from posthog.test.persons import create_person
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
@@ -97,7 +97,7 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_hybrid_query_finds_pre_identification_sessions(self, mock_feature_enabled) -> None:
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
anonymous_id = "anonymous_user_456"
identified_id = "identified_user_456"
session_id_before = "session_before_identification_456"
@@ -163,7 +163,7 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_hybrid_query_finds_all_person_sessions(self, mock_feature_enabled) -> None:
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
distinct_id_1 = "distinct_1"
distinct_id_2 = "distinct_2"
distinct_id_3 = "distinct_3"
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py
index 5a7a4b0d3619..4fc60f4d564a 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from django.utils.timezone import now
@@ -27,7 +27,7 @@ from products.actions.backend.models.action import Action
@parameterized_class([{"allow_event_property_expansion": True}, {"allow_event_property_expansion": False}])
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIBaseTest):
# set by parameterized_class decorator
allow_event_property_expansion: bool
@@ -157,7 +157,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB
),
]
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_for_flags(self, _name: str, properties: dict, expected: list[str]) -> None:
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -243,7 +243,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB
self._assert_query_matches_session_ids({"properties": properties}, expected)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_for_two_is_not_event_properties(self) -> None:
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -321,7 +321,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB
["3", "4"],
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_for_does_not_match_regex_event_properties(self) -> None:
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -398,7 +398,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB
["1", "4"],
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_for_does_not_contain_event_properties(self) -> None:
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index c4b82513371c..2b45332c7efe 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -5,7 +5,7 @@ from itertools import product
from typing import Any, Literal
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -61,7 +61,7 @@ from ee.clickhouse.models.test.test_cohort import get_person_ids_by_cohort_id
@parameterized_class([{"allow_event_property_expansion": True}, {"allow_event_property_expansion": False}])
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
# set by parameterized_class decorator
allow_event_property_expansion: bool
@@ -1307,23 +1307,23 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_listing_ignores_future_replays(self):
- with freeze_time("2023-08-29T12:00:01Z"):
+ with time_machine.travel("2023-08-29T12:00:01Z", tick=False):
produce_replay_summary(team_id=self.team.id, session_id="29th Aug")
- with freeze_time("2023-08-30T14:00:01Z"):
+ with time_machine.travel("2023-08-30T14:00:01Z", tick=False):
produce_replay_summary(team_id=self.team.id, session_id="30th Aug 1400")
- with freeze_time("2023-09-01T12:00:01Z"):
+ with time_machine.travel("2023-09-01T12:00:01Z", tick=False):
produce_replay_summary(team_id=self.team.id, session_id="1st-sep")
- with freeze_time("2023-09-02T12:00:01Z"):
+ with time_machine.travel("2023-09-02T12:00:01Z", tick=False):
produce_replay_summary(team_id=self.team.id, session_id="2nd-sep")
- with freeze_time("2023-09-03T12:00:01Z"):
+ with time_machine.travel("2023-09-03T12:00:01Z", tick=False):
produce_replay_summary(team_id=self.team.id, session_id="3rd-sep")
# before the recording on the thirtieth so should exclude it
- with freeze_time("2023-08-30T12:00:01Z"):
+ with time_machine.travel("2023-08-30T12:00:01Z", tick=False):
# recordings in the future don't show
self._assert_query_matches_session_ids(None, ["29th Aug"])
@@ -1932,7 +1932,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
@also_test_with_materialized_columns(["$session_id", "$browser"], person_properties=["email"])
- @freeze_time("2023-01-04")
+ @time_machine.travel("2023-01-04", tick=False)
def test_action_filter(self):
user = "test_action_filter-user"
create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})
@@ -2532,7 +2532,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
def test_date_from_filter_respects_ttl(self, _name: str, days_ago: int):
- with freeze_time(self.an_hour_ago):
+ with time_machine.travel(self.an_hour_ago, tick=False):
user = "test_date_from_filter_cannot_search_before_ttl-user"
create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})
@@ -2991,7 +2991,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$current_url", "$browser"])
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
def test_any_event_filter_with_properties(self):
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -3123,7 +3123,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
def test_filter_for_recordings_with_console_logs(self):
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -3212,7 +3212,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
def test_filter_for_recordings_with_console_warns(self):
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -3264,7 +3264,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
def test_filter_for_recordings_with_console_errors(self):
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -3316,7 +3316,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
def test_filter_for_recordings_with_mixed_console_counts(self):
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -3444,7 +3444,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
]
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
def test_filter_for_recordings_by_console_text(
self,
console_log_filters: str,
@@ -3842,7 +3842,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
person_properties=["email"],
verify_no_jsonextract=False,
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_with_test_accounts_excluded(self):
self.team.test_account_filters = [
@@ -3924,7 +3924,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
person_properties=["email"],
verify_no_jsonextract=False,
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_with_hogql_event_properties_test_accounts_excluded(self):
self.team.test_account_filters = [
@@ -4025,7 +4025,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
# TRICKY: we had to disable use of materialized columns for part of the query generation
# due to RAM usage issues on the EU cluster
@also_test_with_materialized_columns(event_properties=["is_internal_user"], verify_no_jsonextract=False)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_top_level_event_property_test_account_filter(self):
"""
@@ -4118,7 +4118,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
# TRICKY: we had to disable use of materialized columns for part of the query generation
# due to RAM usage issues on the EU cluster
@also_test_with_materialized_columns(event_properties=["is_internal_user"], verify_no_jsonextract=True)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_top_level_event_property_test_account_filter_allowing_denormalized_props(self):
"""
@@ -4209,7 +4209,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@also_test_with_materialized_columns(event_properties=["is_internal_user"])
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_top_level_hogql_event_property_test_account_filter(self):
"""
@@ -4295,7 +4295,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@also_test_with_materialized_columns(person_properties=["email"], verify_no_jsonextract=False)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_top_level_hogql_person_property_test_account_filter(self):
"""
@@ -4381,7 +4381,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@also_test_with_materialized_columns(person_properties=["email"], verify_no_jsonextract=False)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_top_level_person_property_test_account_filter(self):
"""
@@ -4477,7 +4477,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
["1"],
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_with_two_events_and_multiple_teams(self):
another_team = Team.objects.create(organization=self.organization)
@@ -4510,7 +4510,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
["1"],
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_with_group_filter(self):
create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})
@@ -4626,7 +4626,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
[],
)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_ordering(self):
session_id_one = f"test_ordering-one"
@@ -4665,7 +4665,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@also_test_with_materialized_columns(event_properties=["$host"], verify_no_jsonextract=False)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_top_level_event_host_property_test_account_filter(self):
"""
@@ -4936,7 +4936,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@also_test_with_materialized_columns(person_properties=["email"], verify_no_jsonextract=False)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_filter_users_from_excluded_cohort(self):
"""
@@ -5035,7 +5035,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
@also_test_with_materialized_columns(person_properties=["email"], verify_no_jsonextract=False)
- @freeze_time("2021-01-21T20:00:00.000Z")
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_filter_users_from_excluded_cohort_no_events(self):
"""
@@ -5103,7 +5103,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
)
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestClickhouseSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def _print_query(self, query: SelectQuery) -> str:
return prepare_and_print_ast(
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_operands_queries.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_operands_queries.py
index b6d5b500cede..cb872a4f0e91 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_operands_queries.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_operands_queries.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from django.utils.timezone import now
@@ -33,7 +33,7 @@ ONBOARDING_INITIALIZED = {
}
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSessionRecordingsListOperandsQueries(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
@@ -283,7 +283,7 @@ class TestSessionRecordingsListOperandsQueries(ClickhouseTestMixin, APIBaseTest)
)
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSessionRecordingsNegativeFiltersWithMultipleEvents(ClickhouseTestMixin, APIBaseTest):
"""
Negative filters should match sessions where NO events match the positive condition.
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py
index 1acad2d2de5e..edce55cff9b8 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py
@@ -1,6 +1,6 @@
from uuid import UUID, uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -26,7 +26,7 @@ from posthog.test.persons import create_person
from products.cohorts.backend.models.cohort import Cohort
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
@@ -49,7 +49,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(person_properties=["$some_prop"])
def test_filter_with_cohort_properties(self) -> None:
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
user_one = "test_filter_with_cohort_properties-user"
user_two = "test_filter_with_cohort_properties-user2"
session_id_one = "session_not_in_cohort"
@@ -137,7 +137,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(person_properties=["$some_prop"])
def test_filter_with_static_and_dynamic_cohort_properties(self):
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
user_one = "test_filter_with_cohort_properties-user-in-static-cohort"
user_two = "test_filter_with_cohort_properties-user2-in-dynamic-cohort"
user_three = "test_filter_with_cohort_properties-user3-in-both-cohort"
@@ -325,7 +325,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(person_properties=["$some_prop"])
def test_filter_with_events_and_cohorts(self):
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
user_one = "test_filter_with_events_and_cohorts-user"
user_two = "test_filter_with_events_and_cohorts-user2"
session_id_one = f"test_filter_with_events_and_cohorts-1-{str(uuid4())}"
@@ -443,7 +443,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(person_properties=["$some_prop"])
def test_internal_account_filter_with_cohort_properties(self) -> None:
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
user_one = "test_filter_with_cohort_properties-user"
user_two = "test_filter_with_cohort_properties-user2"
session_id_one = "session_not_in_cohort"
@@ -529,7 +529,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
The filter would incorrectly match because it checked ALL person_ids before applying argMax.
"""
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
distinct_id = "user-with-multiple-person-ids"
session_id = "session-should-not-be-filtered"
@@ -640,7 +640,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
2. The query uses an efficient JOIN-based approach instead of IN subquery
"""
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
# Create a small "internal users" cohort (like employees)
internal_user = "[email protected]"
session_internal = "session-internal-user"
@@ -736,7 +736,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
All sessions should be returned since no one is in the cohort.
"""
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
session_id = "session-with-empty-cohort"
@@ -808,7 +808,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
other property filters (like event properties or person properties).
"""
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
internal_user = "[email protected]"
premium_external = "[email protected]"
free_external = "[email protected]"
@@ -894,7 +894,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
This tests the case where a user wants to exclude multiple cohorts.
"""
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
internal_user = "[email protected]"
beta_user = "[email protected]"
regular_user = "[email protected]"
@@ -976,7 +976,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):
With OR, sessions matching ANY cohort condition should be returned.
"""
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- with freeze_time("2021-08-21T20:00:00.000Z"):
+ with time_machine.travel("2021-08-21T20:00:00.000Z", tick=False):
internal_user = "[email protected]"
beta_user = "[email protected]"
regular_user = "[email protected]"
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
index ebb14857bd49..91d3d7bda551 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
@@ -2,7 +2,7 @@ import json
from datetime import UTC, datetime, timedelta
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -38,10 +38,6 @@ from products.access_control.backend.facade.user_access_control import UserAcces
from products.access_control.backend.models.access_control import AccessControl
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.cohorts.backend.models.cohort import Cohort
-
-# Importing the facade at module scope also keeps its transitive pydantic.v1 import outside the
-# class's frozen time: freezegun's FakeDate breaks pydantic.v1's metaclass construction, and the
-# runner otherwise defers this import to the first test that resolves a linkage.
from products.experiments.backend.facade.replay import (
ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,
IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES,
@@ -55,7 +51,7 @@ FROZEN_NOW = "2021-08-21T20:00:00Z"
BASE_TIME = datetime(2021, 8, 21, 10, 0, tzinfo=UTC)
-@freeze_time(FROZEN_NOW)
+@time_machine.travel(FROZEN_NOW, tick=False)
class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py
index c5abc9a97dde..1806453f8ff4 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, snapshot_clickhouse_queries
from django.utils.timezone import now
@@ -15,7 +15,7 @@ from posthog.test.persons import create_person
from posthog.test.test_utils import create_group_type_mapping_without_created_at
-@freeze_time("2020-01-01T13:46:23")
+@time_machine.travel("2020-01-01T13:46:23", tick=False)
class TestSessionRecordingsListByGroupProperties(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_query_date_range.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_query_date_range.py
index 8884b4c309fe..e44c1f9b5ec0 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_query_date_range.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_query_date_range.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from parameterized import parameterized
@@ -10,7 +10,7 @@ from posthog.schema import DateRange
from posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsQueryDateRange
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestSessionRecordingsQueryDateRange(APIBaseTest):
@parameterized.expand(
[
diff --git a/posthog/session_recordings/queries/test/test_recordings_query_runner.py b/posthog/session_recordings/queries/test/test_recordings_query_runner.py
index d516de3e6486..087ec31c1f01 100644
--- a/posthog/session_recordings/queries/test/test_recordings_query_runner.py
+++ b/posthog/session_recordings/queries/test/test_recordings_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from parameterized import parameterized
@@ -11,7 +11,7 @@ from posthog.session_recordings.queries.test.session_replay_sql import produce_r
from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
-@freeze_time("2021-01-01T13:46:23")
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
class TestRecordingsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/session_recordings/queries/test/test_session_replay_summaries.py b/posthog/session_recordings/queries/test/test_session_replay_summaries.py
index cf4fdb36c850..10a493a98b0f 100644
--- a/posthog/session_recordings/queries/test/test_session_replay_summaries.py
+++ b/posthog/session_recordings/queries/test/test_session_replay_summaries.py
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from uuid import uuid4
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from dateutil.parser import isoparse
@@ -55,7 +55,7 @@ class SessionReplaySummaryQuery:
class TestReceiveSummarizedSessionReplays(ClickhouseTestMixin, BaseTest):
@snapshot_clickhouse_queries
- @freeze_time("2023-01-04T12:34")
+ @time_machine.travel("2023-01-04T12:34", tick=False)
def test_session_replay_summaries_can_be_queried(self):
session_id = "test_session_replay_summaries_can_be_queried-session-id"
diff --git a/posthog/session_recordings/test/test_session_recording_playlist.py b/posthog/session_recordings/test/test_session_recording_playlist.py
index 5673e5f8783a..cba754d7e89a 100644
--- a/posthog/session_recordings/test/test_session_recording_playlist.py
+++ b/posthog/session_recordings/test/test_session_recording_playlist.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
from uuid import uuid4
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
from unittest.mock import MagicMock, patch
@@ -397,7 +397,7 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
assert SessionRecordingPlaylistViewed.objects.count() == 0
- with freeze_time("2022-01-02"):
+ with time_machine.travel("2022-01-02", tick=False):
response_one = self.client.post(
f"/api/projects/{self.team.id}/session_recording_playlists/{short_id}/playlist_viewed"
)
@@ -490,7 +490,7 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
assert "short_id" in create_response.json(), create_response.json()
short_id = create_response.json()["short_id"]
- with freeze_time("2022-01-02"):
+ with time_machine.travel("2022-01-02", tick=False):
response = self.client.patch(
f"/api/projects/{self.team.id}/session_recording_playlists/{short_id}",
{
@@ -966,7 +966,7 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
new=MagicMock(return_value=False),
)
@snapshot_postgres_queries
- @freeze_time("2025-01-01T12:00:00Z")
+ @time_machine.travel("2025-01-01T12:00:00Z", tick=False)
def test_filters_playlist_by_type(self):
# Prime the expiring-playlist cache so its cold-start scan (which builds the
# warehouse HogQL Database and emits a DataWarehouseSavedQuery lookup) stays
diff --git a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py
index f9de469975e2..c06a68fa06f6 100644
--- a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py
+++ b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -318,7 +318,7 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMa
assert response.status_code == status.HTTP_404_NOT_FOUND
assert "Block index out of range" in response.json()["detail"]
- @freeze_time("2023-01-01T00:00:00Z")
+ @time_machine.travel("2023-01-01T00:00:00Z", tick=False)
@patch(
"posthog.session_recordings.session_recording_api.list_blocks",
side_effect=Exception(
@@ -362,7 +362,7 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMa
]
}
- @freeze_time("2023-01-01T00:00:00Z")
+ @time_machine.travel("2023-01-01T00:00:00Z", tick=False)
@patch("posthog.session_recordings.session_recording_api.recording_s3_client.recording_s3_client")
@patch(
"posthog.session_recordings.session_recording_api.list_blocks",
@@ -410,7 +410,7 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMa
"""
)
- @freeze_time("2023-01-01T00:00:00Z")
+ @time_machine.travel("2023-01-01T00:00:00Z", tick=False)
@patch("posthog.session_recordings.session_recording_api.recording_s3_client.recording_s3_client")
@patch(
"posthog.session_recordings.queries.session_replay_events.SessionReplayEvents.exists",
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index 9a219192e27f..7630cc1c0ac8 100644
--- a/posthog/session_recordings/test/test_session_recordings.py
+++ b/posthog/session_recordings/test/test_session_recordings.py
@@ -4,7 +4,7 @@ from typing import cast
from urllib.parse import urlencode
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -355,7 +355,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
self.client.get(f"/api/projects/{self.team.id}/session_recordings")
with (
- freeze_time("2022-06-03T12:00:00.000Z"),
+ time_machine.travel("2022-06-03T12:00:00.000Z", tick=False),
patch(
"posthog.hogql.database.database.feature_enabled_or_false",
return_value=False,
@@ -736,7 +736,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
)
assert update_response.status_code == 404
- @freeze_time("2023-01-01T12:00:00.000Z")
+ @time_machine.travel("2023-01-01T12:00:00.000Z", tick=False)
def test_get_single_session_recording_metadata(self):
p = create_person(
team=self.team,
@@ -849,7 +849,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
assert response.json()["ongoing"] is expected_ongoing
def test_get_single_session_recording_viewed_stats_someone_else_viewed(self):
- with freeze_time("2023-01-01T12:00:00.000Z"):
+ with time_machine.travel("2023-01-01T12:00:00.000Z", tick=False):
session_recording_id = "session_1"
base_time = (now() - relativedelta(days=1)).replace(microsecond=0)
produce_replay_summary(
@@ -876,7 +876,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
}
def test_get_single_session_recording_viewed_stats_current_user_viewed(self):
- with freeze_time("2023-01-01T12:00:00.000Z"):
+ with time_machine.travel("2023-01-01T12:00:00.000Z", tick=False):
session_recording_id = "session_1"
base_time = (now() - relativedelta(days=1)).replace(microsecond=0)
produce_replay_summary(
@@ -1020,7 +1020,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
]
)
def test_session_ids_filter(self, use_recording_events: bool, api_version: int):
- with freeze_time("2020-09-13T12:26:40.000Z"):
+ with time_machine.travel("2020-09-13T12:26:40.000Z", tick=False):
create_person(
team=self.team,
distinct_ids=["user"],
@@ -1054,7 +1054,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
assert response_data["results"][2]["id"] == "3"
def test_session_ids_filter_returns_recordings_outside_default_date_range(self):
- with freeze_time("2020-09-13T12:26:40.000Z"):
+ with time_machine.travel("2020-09-13T12:26:40.000Z", tick=False):
create_person(
team=self.team,
distinct_ids=["user"],
@@ -1074,7 +1074,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
assert response.json()["results"] == []
def test_empty_list_session_ids_filter_returns_no_recordings(self):
- with freeze_time("2020-09-13T12:26:40.000Z"):
+ with time_machine.travel("2020-09-13T12:26:40.000Z", tick=False):
create_person(
team=self.team,
distinct_ids=["user"],
diff --git a/posthog/session_recordings/test/test_session_recordings_sharing.py b/posthog/session_recordings/test/test_session_recordings_sharing.py
index 3a272177aeb8..36aaf9e69a94 100644
--- a/posthog/session_recordings/test/test_session_recordings_sharing.py
+++ b/posthog/session_recordings/test/test_session_recordings_sharing.py
@@ -1,5 +1,5 @@
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from django.utils.timezone import now
@@ -31,7 +31,7 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchi
SessionRecordingViewed.objects.all().delete()
SessionRecording.objects.all().delete()
- with freeze_time("2023-01-01T12:00:00Z"):
+ with time_machine.travel("2023-01-01T12:00:00Z", tick=False):
self.session_id = str(uuid7())
self.produce_replay_summary(
"user",
@@ -68,7 +68,7 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchi
assert "access_token" in response.json()
return response.json()["access_token"]
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_enable_sharing_creates_access_token(self) -> None:
token = self._enable_sharing(self.session_id)
assert isinstance(token, str) and len(token) > 0
@@ -95,7 +95,7 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchi
),
]
)
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_sharing_token_forbidden_access_scenarios(self, _name: str, url_builder) -> None:
self.other_team = create_team(organization=self.organization)
@@ -107,7 +107,7 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchi
response = self.client.get(url)
assert response.status_code == status.HTTP_403_FORBIDDEN
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_sharing_token_allows_authorized_access(self) -> None:
token = self._enable_sharing(self.session_id)
@@ -125,7 +125,7 @@ class TestSessionRecordingsSharing(APIBaseTest, ClickhouseTestMixin, QueryMatchi
"end_time": "2022-12-31T12:00:00Z",
}
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_sharing_token_allows_snapshot_access(self) -> None:
token = self._enable_sharing(self.session_id)
@@ -153,7 +153,7 @@ class TestSessionRecordingsSharingAccessControl(APIBaseTest, ClickhouseTestMixin
self.member_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
- with freeze_time("2023-01-01T12:00:00Z"):
+ with time_machine.travel("2023-01-01T12:00:00Z", tick=False):
self.session_id = str(uuid7())
produce_replay_summary(
team_id=self.team.pk,
@@ -190,7 +190,7 @@ class TestSessionRecordingsSharingAccessControl(APIBaseTest, ClickhouseTestMixin
("editor", status.HTTP_200_OK),
]
)
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_enable_sharing_requires_editor_access(self, access_level: str, expected_status: int) -> None:
self._grant_recording_access(access_level)
self.client.force_login(self.member_user)
@@ -208,7 +208,7 @@ class TestSessionRecordingsSharingAccessControl(APIBaseTest, ClickhouseTestMixin
("editor", status.HTTP_200_OK),
]
)
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_enable_sharing_requires_editor_access_to_sharing_configuration_resource(
self, access_level: str, expected_status: int
) -> None:
@@ -226,7 +226,7 @@ class TestSessionRecordingsSharingAccessControl(APIBaseTest, ClickhouseTestMixin
assert response.status_code == expected_status, response.json()
- @freeze_time("2023-01-01T12:00:00Z")
+ @time_machine.travel("2023-01-01T12:00:00Z", tick=False)
def test_sharing_response_exposes_user_access_level(self) -> None:
self.client.force_login(self.member_user)
diff --git a/posthog/tasks/alerts/test/test_alert_evaluation.py b/posthog/tasks/alerts/test/test_alert_evaluation.py
index 4d266afa1a59..420b610ab93f 100644
--- a/posthog/tasks/alerts/test/test_alert_evaluation.py
+++ b/posthog/tasks/alerts/test/test_alert_evaluation.py
@@ -1,6 +1,6 @@
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from unittest.mock import MagicMock, patch
@@ -14,7 +14,7 @@ from products.alerts.backend.models import AlertCheck, AlertConfiguration
from products.product_analytics.backend.facade.models import Insight
-@freeze_time("2024-06-02T08:55:00.000Z")
+@time_machine.travel("2024-06-02T08:55:00.000Z", tick=False)
@patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])
@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
@@ -116,7 +116,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
).model_dump()
alert_data = self._create_formula_alert(query_dict, series_index=0)
- with freeze_time("2024-06-02T07:55:00.000Z"):
+ with time_machine.travel("2024-06-02T07:55:00.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
flush_persons_and_events()
@@ -140,7 +140,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
).model_dump()
alert_data = self._create_formula_alert(query_dict, series_index=0)
- with freeze_time("2024-06-02T07:55:00.000Z"):
+ with time_machine.travel("2024-06-02T07:55:00.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
flush_persons_and_events()
@@ -163,7 +163,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
).model_dump()
alert_data = self._create_formula_alert(query_dict, series_index=0)
- with freeze_time("2024-06-02T07:55:00.000Z"):
+ with time_machine.travel("2024-06-02T07:55:00.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
flush_persons_and_events()
@@ -192,7 +192,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
).model_dump()
alert_data = self._create_formula_alert(query_dict, series_index=1)
- with freeze_time("2024-06-02T07:55:00.000Z"):
+ with time_machine.travel("2024-06-02T07:55:00.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
flush_persons_and_events()
diff --git a/posthog/tasks/alerts/test/test_alert_subscriptions.py b/posthog/tasks/alerts/test/test_alert_subscriptions.py
index b2484cd3330e..10c805897c00 100644
--- a/posthog/tasks/alerts/test/test_alert_subscriptions.py
+++ b/posthog/tasks/alerts/test/test_alert_subscriptions.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -14,7 +14,7 @@ from posthog.tasks.test.utils_email_tests import mock_email_messages
from products.alerts.backend.models import AlertConfiguration, AlertSubscription
-@freeze_time("2024-06-02T08:55:00.000Z")
+@time_machine.travel("2024-06-02T08:55:00.000Z", tick=False)
class TestAlertSubscriptionOrgMembership(APIBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -80,7 +80,7 @@ class TestAlertSubscriptionOrgMembership(APIBaseTest):
assert email.to[0]["recipient"] == "[email protected]"
-@freeze_time("2024-06-02T08:55:00.000Z")
+@time_machine.travel("2024-06-02T08:55:00.000Z", tick=False)
class TestGetSubscribedUsersEmails(APIBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -150,7 +150,7 @@ class TestGetSubscribedUsersEmails(APIBaseTest):
assert emails == []
-@freeze_time("2024-06-02T08:55:00.000Z")
+@time_machine.travel("2024-06-02T08:55:00.000Z", tick=False)
class TestAlertEmailNotifications(APIBaseTest):
CLASS_DATA_LEVEL_SETUP = False
diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.py
index cb8be406c48f..aba899eeeaf5 100644
--- a/posthog/tasks/alerts/test/test_investigation_notifications.py
+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -21,7 +21,7 @@ from products.product_analytics.backend.facade.models import Insight
NOW = datetime(2026, 5, 4, 12, 0, 0, tzinfo=UTC)
-@freeze_time(NOW)
+@time_machine.travel(NOW, tick=False)
class TestInvestigationNotificationSafetyNet(APIBaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.py
index ff55d60800ef..62fcf7601b8a 100644
--- a/posthog/tasks/alerts/test/test_metrics_alerts.py
+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py
@@ -1,7 +1,7 @@
import datetime as dt
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
@@ -70,7 +70,7 @@ def _stub_investigation_result(metric_name: str, mover_label: str = "pod-1") ->
)
-@freeze_time(FROZEN_TIME)
+@time_machine.travel(FROZEN_TIME, tick=False)
@patch(
"products.alerts.backend.presentation.views.alert.posthoganalytics.feature_enabled", side_effect=_metrics_flag_only
)
diff --git a/posthog/tasks/alerts/test/test_schedule_restriction.py b/posthog/tasks/alerts/test/test_schedule_restriction.py
index 0be61a89e6d4..77b339b9d39f 100644
--- a/posthog/tasks/alerts/test/test_schedule_restriction.py
+++ b/posthog/tasks/alerts/test/test_schedule_restriction.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock
from posthog.tasks.alerts import schedule_restriction as schedule_restriction_module
@@ -74,7 +74,7 @@ class TestNextCheckAtAfterScheduleRestrictionChange:
return alert
def test_cleared_restriction_schedules_from_now_and_restores_existing_value(self) -> None:
- with freeze_time("2026-04-06T14:00:00Z"):
+ with time_machine.travel("2026-04-06T14:00:00Z", tick=False):
existing = datetime(2026, 4, 7, 18, 30, tzinfo=UTC)
alert = self._hourly_alert(schedule_restriction=None, next_check_at=existing)
out = next_check_at_after_schedule_restriction_change(alert)
@@ -82,7 +82,7 @@ class TestNextCheckAtAfterScheduleRestrictionChange:
assert alert.next_check_at == existing
def test_future_next_check_inside_blocked_window_snaps_to_first_unblocked_minute(self) -> None:
- with freeze_time("2026-04-06T14:00:00Z"):
+ with time_machine.travel("2026-04-06T14:00:00Z", tick=False):
alert = self._hourly_alert(
schedule_restriction={"blocked_windows": [{"start": "11:00", "end": "16:00"}]},
next_check_at=datetime(2026, 4, 6, 15, 30, tzinfo=UTC),
@@ -91,7 +91,7 @@ class TestNextCheckAtAfterScheduleRestrictionChange:
assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)
def test_custom_schedule_start_time_inside_blocked_window_snaps_to_first_unblocked_minute(self) -> None:
- with freeze_time("2026-04-06T20:00:00Z"):
+ with time_machine.travel("2026-04-06T20:00:00Z", tick=False):
alert = self._hourly_alert(
schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]},
schedule_start_time="22:30",
@@ -101,7 +101,7 @@ class TestNextCheckAtAfterScheduleRestrictionChange:
assert out == datetime(2026, 4, 7, 7, 0, tzinfo=UTC)
def test_does_not_keep_stale_snap_when_earlier_runs_are_allowed(self) -> None:
- with freeze_time("2026-04-06T16:44:00Z"):
+ with time_machine.travel("2026-04-06T16:44:00Z", tick=False):
alert = self._hourly_alert(
team=MagicMock(timezone="America/Toronto"),
schedule_restriction={"blocked_windows": [{"start": "14:00", "end": "16:00"}]},
diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
index 876cd6f9e8f1..acb28a707e06 100644
--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
@@ -1,7 +1,7 @@
import datetime
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from unittest.mock import ANY, MagicMock, patch
@@ -35,7 +35,7 @@ from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
FROZEN_TIME = dateutil.parser.parse("2024-06-02T08:55:00.000Z")
-@freeze_time(FROZEN_TIME)
+@time_machine.travel(FROZEN_TIME, tick=False)
@patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
return_value=[AlertDelivery(channel="email", target="[email protected]", at="2024-06-02T08:55:00+00:00")],
@@ -178,7 +178,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight = self.create_time_series_trend_insight()
alert = self.create_alert(insight, series_index=0, upper=1)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -227,7 +227,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
alert = self.create_alert(insight, series_index=0, upper=1)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1), tick=False):
_create_event(team=self.team, event="signed_up", distinct_id="1")
_create_event(team=self.team, event="signed_up", distinct_id="2")
flush_persons_and_events()
@@ -246,7 +246,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight, series_index=0, lower=0, upper=2, calculation_interval=AlertCalculationInterval.MONTHLY
)
- with freeze_time(FROZEN_TIME):
+ with time_machine.travel(FROZEN_TIME, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -279,7 +279,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight, series_index=0, lower=0, upper=2, calculation_interval=AlertCalculationInterval.WEEKLY
)
- with freeze_time(FROZEN_TIME):
+ with time_machine.travel(FROZEN_TIME, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -311,7 +311,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight = self.create_time_series_trend_insight(BreakdownFilter(breakdowns=[Breakdown(property="$browser")]))
alert = self.create_alert(insight, series_index=0, upper=1)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -359,7 +359,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight = self.create_time_series_trend_insight(BreakdownFilter(breakdowns=[Breakdown(property="$browser")]))
alert = self.create_alert(insight, series_index=0, lower=2)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -407,7 +407,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight = self.create_time_series_trend_insight(BreakdownFilter(breakdowns=[Breakdown(property="$browser")]))
alert = self.create_alert(insight, series_index=0, lower=1)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(days=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -451,7 +451,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight = self.create_aggregate_trend_insight()
alert = self.create_alert(insight, series_index=0, upper=1)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=4)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=4), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -499,7 +499,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
insight = self.create_aggregate_trend_insight(BreakdownFilter(breakdowns=[Breakdown(property="$browser")]))
alert = self.create_alert(insight, series_index=0, upper=1)
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=4)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=4), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -548,7 +548,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
alert = self.create_alert(insight, series_index=0, upper=1, check_ongoing_interval=True)
# around 8 AM on same day as check
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -591,7 +591,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
alert = self.create_alert(insight, series_index=0, upper=1, check_ongoing_interval=True)
# current day doesn't breach
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -601,7 +601,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# prev day breaches
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=26)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=26), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -639,8 +639,9 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
alert = self.create_alert(insight, series_index=0, upper=1)
# day before yesterday
- with freeze_time(
- FROZEN_TIME - dateutil.relativedelta.relativedelta(days=2) - dateutil.relativedelta.relativedelta(hours=2)
+ with time_machine.travel(
+ FROZEN_TIME - dateutil.relativedelta.relativedelta(days=2) - dateutil.relativedelta.relativedelta(hours=2),
+ tick=False,
):
_create_event(
team=self.team,
@@ -678,7 +679,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
alert = self.create_alert(insight, series_index=0, lower=2)
# around 8 AM on same day as check
- with freeze_time(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=1)):
+ with time_machine.travel(FROZEN_TIME - dateutil.relativedelta.relativedelta(hours=1), tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -726,14 +727,14 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
# Create 3 events for 07:00-07:59 (will be checked at 08:05)
- with freeze_time(dateutil.parser.parse("2024-06-02T07:30:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-02T07:30:00.000Z"), tick=False):
_create_event(team=self.team, event="signed_up", distinct_id="1")
_create_event(team=self.team, event="signed_up", distinct_id="2")
_create_event(team=self.team, event="signed_up", distinct_id="3")
flush_persons_and_events()
# Check at 08:05 - checks previous hour (07:00-07:59), should fire (3 events > upper threshold of 1)
- with freeze_time(dateutil.parser.parse("2024-06-02T08:05:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-02T08:05:00.000Z"), tick=False):
run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
@@ -755,7 +756,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
mock_send_breaches.reset_mock()
# Second check at 09:05 - checks previous hour (08:00-08:59), should not fire (0 events)
- with freeze_time(dateutil.parser.parse("2024-06-02T09:05:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-02T09:05:00.000Z"), tick=False):
run_alert_check(alert["id"])
# Verify execution mode is still CALCULATE_BLOCKING_ALWAYS
diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
index 6255dfc1456c..4d2f36fa141b 100644
--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
@@ -1,6 +1,6 @@
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from unittest.mock import ANY, MagicMock, call, patch
@@ -36,7 +36,7 @@ from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
FROZEN_TIME = dateutil.parser.parse("2024-06-04T08:55:00.000Z")
-@freeze_time(FROZEN_TIME)
+@time_machine.travel(FROZEN_TIME, tick=False)
@patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
return_value=[AlertDelivery(channel="email", target="[email protected]", at="2024-06-04T08:55:00+00:00")],
@@ -168,7 +168,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Previous to previous interval (last to last week) has 0 events
# add events for previous interval (last week on Sat)
last_sat = FROZEN_TIME - dateutil.relativedelta.relativedelta(days=3)
- with freeze_time(last_sat):
+ with time_machine.travel(last_sat, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -234,7 +234,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -246,7 +246,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -329,7 +329,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 2 events
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -347,7 +347,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 1 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -432,7 +432,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -444,7 +444,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -522,7 +522,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 3 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -546,7 +546,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 1 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -629,7 +629,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 2 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -647,7 +647,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 1 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -730,7 +730,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -742,7 +742,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 3 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -823,7 +823,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 3 events
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -847,7 +847,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 1 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -918,7 +918,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -936,7 +936,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1046,7 +1046,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1064,7 +1064,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1174,7 +1174,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1192,7 +1192,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1302,7 +1302,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1332,7 +1332,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1431,7 +1431,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1449,7 +1449,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1531,7 +1531,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 1 event
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1549,7 +1549,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval to have 2 event
# add events for last week (last Tue)
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1629,7 +1629,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# we aggregate our weekly insight numbers to display for Sun (19th May, 26th May, 2nd June)
# set current interval to have 3 events
- with freeze_time(FROZEN_TIME):
+ with time_machine.travel(FROZEN_TIME, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1653,7 +1653,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval (last week) to have 1 event
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1666,7 +1666,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# so event shouldn't fire for the previous week
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1749,7 +1749,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# we aggregate our weekly insight numbers to display for Sun (19th May, 26th May, 2nd June)
# set current interval to have 1 events
- with freeze_time(FROZEN_TIME):
+ with time_machine.travel(FROZEN_TIME, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1761,7 +1761,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval (last week) to have 3 events
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1786,7 +1786,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# so event shouldn't fire for the previous week
last_to_last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=2)
- with freeze_time(last_to_last_tue):
+ with time_machine.travel(last_to_last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1859,7 +1859,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval (last week) to have 2 events
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -1952,7 +1952,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous interval (last week) to have 2 events
last_tue = FROZEN_TIME - dateutil.relativedelta.relativedelta(weeks=1)
- with freeze_time(last_tue):
+ with time_machine.travel(last_tue, tick=False):
_create_event(
team=self.team,
event="signed_up",
@@ -2028,19 +2028,19 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
# Create 2 events in 07:00-07:59
- with freeze_time(dateutil.parser.parse("2024-06-04T07:30:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T07:30:00.000Z"), tick=False):
_create_event(team=self.team, event="signed_up", distinct_id="1")
_create_event(team=self.team, event="signed_up", distinct_id="2")
flush_persons_and_events()
# Create 1 event in 08:00-08:59
- with freeze_time(dateutil.parser.parse("2024-06-04T08:30:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T08:30:00.000Z"), tick=False):
_create_event(team=self.team, event="signed_up", distinct_id="user_1")
flush_persons_and_events()
# Check at 08:05 - checks increase from 06:00-06:59 (0) to 07:00-07:59 (2)
# Increase = 2 - 0 = 2 (breaches upper threshold of 1)
- with freeze_time(dateutil.parser.parse("2024-06-04T08:05:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T08:05:00.000Z"), tick=False):
run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
@@ -2063,7 +2063,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 09:05 - checks increase from 07:00-07:59 (2) to 08:00-08:59 (1)
# Increase = 1 - 2 = -1 (decrease, no breach)
- with freeze_time(dateutil.parser.parse("2024-06-04T09:05:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T09:05:00.000Z"), tick=False):
run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
@@ -2101,14 +2101,14 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
# Create 2 events in 07:00-07:59
- with freeze_time(dateutil.parser.parse("2024-06-04T07:30:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T07:30:00.000Z"), tick=False):
_create_event(team=self.team, event="signed_up", distinct_id="1")
_create_event(team=self.team, event="signed_up", distinct_id="2")
flush_persons_and_events()
# Check at 08:05 - checks decrease from 06:00-06:59 (0) to 07:00-07:59 (2)
# It's increase, do not trigger an alarm
- with freeze_time(dateutil.parser.parse("2024-06-04T08:05:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T08:05:00.000Z"), tick=False):
run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
@@ -2131,7 +2131,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 09:05 - checks decrease from 07:00-07:59 (2) to 08:00-08:59 (0)
# It's decrease by 2, trigger an alarm
- with freeze_time(dateutil.parser.parse("2024-06-04T09:05:00.000Z")):
+ with time_machine.travel(dateutil.parser.parse("2024-06-04T09:05:00.000Z"), tick=False):
run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
index 904d896fb49a..b3de59ca8b06 100644
--- a/posthog/tasks/alerts/test/test_utils.py
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -42,7 +42,7 @@ class TestAlertUtils:
alert.schedule_restriction = None
alert.skip_weekend = False
- with freeze_time("2026-04-06T14:00:00Z"):
+ with time_machine.travel("2026-04-06T14:00:00Z", tick=False):
assert next_check_time(alert) == datetime(2026, 4, 6, 14, 2, 0, tzinfo=UTC)
@parameterized.expand(
diff --git a/posthog/tasks/test/test_ai_observability_usage_report.py b/posthog/tasks/test/test_ai_observability_usage_report.py
index dfb9156fd105..46e3225b3c09 100644
--- a/posthog/tasks/test/test_ai_observability_usage_report.py
+++ b/posthog/tasks/test/test_ai_observability_usage_report.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime, timedelta
from uuid import uuid4
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseDestroyTablesMixin,
@@ -36,7 +36,7 @@ from posthog.tasks.ai_observability_usage_report import (
from posthog.utils import get_previous_day
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesMixin):
"""Tests for AI observability usage reporting functionality."""
@@ -1105,7 +1105,7 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhous
timestamp=jan_5_timestamp,
)
- # Create AI events for January 9th (within the default period based on freeze_time)
+ # Create AI events for January 9th (within the default period based on the frozen clock)
jan_9_timestamp = datetime(2022, 1, 9, 12, 0, 0, tzinfo=UTC)
self._create_ai_events(
self.team,
@@ -1179,7 +1179,7 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhous
assert mock_capture_report.delay.call_count == expected_emissions
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
@parameterized.expand(
[
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index 7577b088e7ca..48920c222021 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -1,7 +1,7 @@
from collections.abc import Callable
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -103,7 +103,7 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla
@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")
def test_create_trends_cohort(self, _calculate_cohort_from_list: MagicMock) -> None:
person_factory(team_id=self.team.pk, distinct_ids=["blabla"])
- with freeze_time("2021-01-01 00:06:34"):
+ with time_machine.travel("2021-01-01 00:06:34", tick=False):
event_factory(
team=self.team,
event="$pageview",
@@ -112,7 +112,7 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla
timestamp="2021-01-01T12:00:00Z",
)
- with freeze_time("2021-01-02 00:06:34"):
+ with time_machine.travel("2021-01-02 00:06:34", tick=False):
event_factory(
team=self.team,
event="$pageview",
diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.py
index d5db19018138..3536359b07f9 100644
--- a/posthog/tasks/test/test_email.py
+++ b/posthog/tasks/test/test_email.py
@@ -2,7 +2,7 @@ import uuid
import datetime as dt
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, run_clickhouse_statement_in_parallel
from unittest.mock import MagicMock, patch
@@ -66,7 +66,7 @@ from products.data_modeling.backend.facade.models import DataModelingJob, DataMo
def create_org_team_and_user(creation_date: str, email: str, ingested_event: bool = False) -> tuple[Organization, User]:
- with freeze_time(creation_date):
+ with time_machine.travel(creation_date, tick=False):
org = Organization.objects.create(name="too_late_org")
Team.objects.create(organization=org, name="Default Project", ingested_event=ingested_event)
user = User.objects.create_and_join(
@@ -726,7 +726,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
def test_send_external_data_failure_digest(self, MockEmailMessage: MagicMock) -> None:
mocked_email_messages = mock_email_messages(MockEmailMessage)
- with freeze_time("2024-05-15 10:00:00"):
+ with time_machine.travel("2024-05-15 10:00:00", tick=False):
sent = send_external_data_failure_digest(
self.team.pk,
[
@@ -768,7 +768,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
) -> None:
mock_email_messages(MockEmailMessage)
- with freeze_time("2024-05-15 09:59:00"):
+ with time_machine.travel("2024-05-15 09:59:00", tick=False):
send_external_data_failure_digest(
self.team.pk,
[
@@ -828,7 +828,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
def test_send_external_data_failure_digest_skips_when_already_sent_today(self, MockEmailMessage: MagicMock) -> None:
mocked_email_messages = mock_email_messages(MockEmailMessage)
- with freeze_time("2024-05-15 10:00:00"):
+ with time_machine.travel("2024-05-15 10:00:00", tick=False):
record, _ = MessagingRecord.objects.get_or_create(
raw_email="[email protected]",
campaign_key=f"external_data_failure_digest_{self.team.pk}_2024-05-15",
@@ -895,7 +895,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
"url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Charge",
}
]
- with freeze_time("2024-05-15 10:00:00"):
+ with time_machine.travel("2024-05-15 10:00:00", tick=False):
send_external_data_failure_digest(self.team.pk, items)
assert mocked_email_messages[0].to == [
@@ -905,11 +905,11 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
self.user.partial_notification_settings = {"plugin_disabled": True}
self.user.save()
- with freeze_time("2024-05-15 18:00:00"):
+ with time_machine.travel("2024-05-15 18:00:00", tick=False):
send_external_data_failure_digest(self.team.pk, items)
assert len(mocked_email_messages) == 1
- with freeze_time("2024-05-16 10:00:00"):
+ with time_machine.travel("2024-05-16 10:00:00", tick=False):
send_external_data_failure_digest(self.team.pk, items)
assert len(mocked_email_messages[1].to) == 2
diff --git a/posthog/tasks/test/test_process_scheduled_changes.py b/posthog/tasks/test/test_process_scheduled_changes.py
index 176126455692..9487d2fac927 100644
--- a/posthog/tasks/test/test_process_scheduled_changes.py
+++ b/posthog/tasks/test/test_process_scheduled_changes.py
@@ -2,7 +2,7 @@ import json
from datetime import UTC, datetime, timedelta
from typing import Any, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest.mock import patch
@@ -169,7 +169,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertEqual(updated_scheduled_change.failure_count, 1)
@snapshot_postgres_queries
- @freeze_time("2023-12-21T09:00:00Z")
+ @time_machine.travel("2023-12-21T09:00:00Z", tick=False)
def test_schedule_feature_flag_multiple_changes(self) -> None:
feature_flag = FeatureFlag.objects.create(
name="Flag",
@@ -341,7 +341,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertEqual(active_change["before"], False) # type: ignore
self.assertEqual(active_change["after"], True) # type: ignore
- @freeze_time("2023-12-21T09:00:00Z")
+ @time_machine.travel("2023-12-21T09:00:00Z", tick=False)
def test_updated_at_field_tracks_processing_time(self) -> None:
"""Test that updated_at is automatically updated when scheduled changes are processed"""
feature_flag = FeatureFlag.objects.create(
@@ -370,7 +370,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertEqual(original_created_at, original_updated_at)
# Advance time to simulate processing delay
- with freeze_time("2023-12-21T09:00:10Z"):
+ with time_machine.travel("2023-12-21T09:00:10Z", tick=False):
# Process the scheduled change
process_scheduled_changes()
@@ -1198,7 +1198,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
updated_flag = FeatureFlag.objects.get(key="past-test-flag")
self.assertEqual(updated_flag.active, True)
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_recurring_schedule_computes_next_weekly_run(self) -> None:
"""Recurring weekly schedule should advance scheduled_at by 1 week, not mark as executed."""
feature_flag = FeatureFlag.objects.create(
@@ -1231,7 +1231,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
feature_flag.refresh_from_db()
self.assertEqual(feature_flag.active, False)
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_recurring_schedule_computes_next_daily_run(self) -> None:
"""Recurring daily schedule should advance scheduled_at by 1 day."""
feature_flag = FeatureFlag.objects.create(
@@ -1259,7 +1259,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertIsNone(scheduled_change.executed_at)
self.assertEqual(scheduled_change.scheduled_at, datetime(2024, 1, 16, 9, 0, tzinfo=UTC))
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_recurring_schedule_computes_next_monthly_run(self) -> None:
"""Recurring monthly schedule should advance scheduled_at by 1 month."""
feature_flag = FeatureFlag.objects.create(
@@ -1287,7 +1287,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertIsNone(scheduled_change.executed_at)
self.assertEqual(scheduled_change.scheduled_at, datetime(2024, 2, 15, 9, 0, tzinfo=UTC))
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_non_recurring_schedule_still_marks_executed(self) -> None:
"""Non-recurring schedules should continue to mark executed_at (existing behavior)."""
feature_flag = FeatureFlag.objects.create(
@@ -1314,7 +1314,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
# Should be marked as executed
self.assertIsNotNone(scheduled_change.executed_at)
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_paused_recurring_schedule_does_not_execute(self) -> None:
"""Paused recurring schedules (is_recurring=False with interval) should be skipped."""
feature_flag = FeatureFlag.objects.create(
@@ -1346,7 +1346,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertIsNone(scheduled_change.last_executed_at)
self.assertEqual(feature_flag.active, True) # Unchanged
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_recurring_schedule_executes_multiple_times(self) -> None:
"""Recurring schedule should execute each time its scheduled_at is due."""
feature_flag = FeatureFlag.objects.create(
@@ -1380,7 +1380,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
feature_flag.save()
# Second execution (next day)
- with freeze_time("2024-01-16T09:00:00Z"):
+ with time_machine.travel("2024-01-16T09:00:00Z", tick=False):
process_scheduled_changes()
scheduled_change.refresh_from_db()
feature_flag.refresh_from_db()
@@ -1388,7 +1388,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertEqual(feature_flag.active, False)
self.assertEqual(scheduled_change.scheduled_at, datetime(2024, 1, 17, 9, 0, tzinfo=UTC))
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_recurring_schedule_computes_next_yearly_run(self) -> None:
"""Recurring yearly schedule should advance scheduled_at by 1 year."""
feature_flag = FeatureFlag.objects.create(
@@ -1418,7 +1418,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
feature_flag.refresh_from_db()
self.assertEqual(feature_flag.active, False)
- @freeze_time("2024-02-29T09:00:00Z")
+ @time_machine.travel("2024-02-29T09:00:00Z", tick=False)
def test_recurring_yearly_schedule_handles_leap_year(self) -> None:
"""Yearly schedule on Feb 29 should advance to Feb 28 in non-leap years."""
feature_flag = FeatureFlag.objects.create(
@@ -1490,7 +1490,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
self.assertFalse(failure_data["will_retry"])
self.assertEqual(failure_data["error_classification"], "unrecoverable")
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_cron_recurring_schedule_executes_and_advances(self) -> None:
feature_flag = FeatureFlag.objects.create(
name="Cron Flag",
@@ -1522,7 +1522,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
# Next weekday at 09:00 is Tuesday 2024-01-16
self.assertEqual(scheduled_change.scheduled_at, datetime(2024, 1, 16, 9, 0, tzinfo=UTC))
- @freeze_time("2024-01-15T09:00:00Z")
+ @time_machine.travel("2024-01-15T09:00:00Z", tick=False)
def test_cron_recurring_schedule_paused_is_skipped(self) -> None:
feature_flag = FeatureFlag.objects.create(
name="Cron Paused Flag",
@@ -1548,7 +1548,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
feature_flag.refresh_from_db()
self.assertFalse(feature_flag.active)
- @freeze_time("2024-01-19T09:00:00Z")
+ @time_machine.travel("2024-01-19T09:00:00Z", tick=False)
def test_cron_recurring_schedule_skips_missed_runs(self) -> None:
feature_flag = FeatureFlag.objects.create(
name="Cron Delayed Flag",
@@ -1577,7 +1577,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
# Should skip past Tue/Wed/Thu/Fri and land on Monday Jan 22
self.assertEqual(scheduled_change.scheduled_at, datetime(2024, 1, 22, 9, 0, tzinfo=UTC))
- @freeze_time("2024-01-16T09:00:00Z")
+ @time_machine.travel("2024-01-16T09:00:00Z", tick=False)
def test_cron_recurring_schedule_respects_end_date(self) -> None:
feature_flag = FeatureFlag.objects.create(
name="Cron End Flag",
@@ -1689,7 +1689,7 @@ class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):
tz: str | None,
expected_next: datetime,
) -> None:
- with freeze_time(frozen_now):
+ with time_machine.travel(frozen_now, tick=False):
feature_flag = FeatureFlag.objects.create(
name=f"Flag {name}",
key=f"flag-{name.replace('_', '-')}",
diff --git a/posthog/tasks/test/test_stop_surveys_reached_target.py b/posthog/tasks/test/test_stop_surveys_reached_target.py
index 4f292fa1bd0b..48f49b53b2ea 100644
--- a/posthog/tasks/test/test_stop_surveys_reached_target.py
+++ b/posthog/tasks/test/test_stop_surveys_reached_target.py
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from typing import Optional
from uuid import UUID
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import TestCase
@@ -54,7 +54,7 @@ class TestStopSurveysReachedTarget(TestCase, ClickhouseTestMixin):
team=survey.team,
)
- @freeze_time("2022-01-01")
+ @time_machine.travel("2022-01-01", tick=False)
@snapshot_clickhouse_queries
def test_stop_surveys_with_enough_responses(self) -> None:
# Fixed ids: the survey id list is inlined into the snapshotted ClickHouse SQL,
diff --git a/posthog/tasks/test/test_update_survey_adaptive_sampling.py b/posthog/tasks/test/test_update_survey_adaptive_sampling.py
index 2600ee318de2..91ee1295f46d 100644
--- a/posthog/tasks/test/test_update_survey_adaptive_sampling.py
+++ b/posthog/tasks/test/test_update_survey_adaptive_sampling.py
@@ -2,7 +2,7 @@ import json
from copy import deepcopy
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -40,7 +40,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):
self.survey.internal_response_sampling_flag = self.internal_response_sampling_flag
self.survey.save()
- @freeze_time("2024-12-13T12:00:00Z")
+ @time_machine.travel("2024-12-13T12:00:00Z", tick=False)
@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
def test_updates_rollout(self, mock_get_count: MagicMock) -> None:
mock_get_count.return_value = 50
@@ -50,7 +50,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):
self.assertEqual(internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"], 20)
mock_get_count.assert_called_once_with(self.survey)
- @freeze_time("2024-12-21T12:00:00Z")
+ @time_machine.travel("2024-12-21T12:00:00Z", tick=False)
@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
def test_updates_rollout_after_interval_is_over(self, mock_get_count: MagicMock) -> None:
mock_get_count.return_value = 50
@@ -63,7 +63,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):
response_sampling_daily_limits = json.loads(survey.response_sampling_daily_limits)
self.assertEqual(response_sampling_daily_limits[0].get("date"), "2024-12-22")
- @freeze_time("2024-12-13T12:00:00Z")
+ @time_machine.travel("2024-12-13T12:00:00Z", tick=False)
@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
def test_no_update_when_limit_reached(self, mock_get_count: MagicMock) -> None:
mock_get_count.return_value = 100
@@ -127,7 +127,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):
),
]
)
- @freeze_time("2024-12-13T12:00:00Z")
+ @time_machine.travel("2024-12-13T12:00:00Z", tick=False)
@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
def test_round_trip_preserves_filters_except_rollout(
self, _name: str, filters: dict, mock_get_count: MagicMock
@@ -147,7 +147,7 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):
internal_response_sampling_flag = FeatureFlag.objects.get(id=self.internal_response_sampling_flag.id)
self.assertEqual(internal_response_sampling_flag.filters, expected)
- @freeze_time("2024-12-13T12:00:00Z")
+ @time_machine.travel("2024-12-13T12:00:00Z", tick=False)
@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
def test_system_write_skips_approval_gate_and_logs_system_activity(
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 0d5af2df3a01..2e458a1376aa 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -7,7 +7,7 @@ from typing import Any
from uuid import uuid4
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseDestroyTablesMixin,
@@ -206,7 +206,7 @@ def _setup_replay_data(team_id: int, include_mobile_replay: bool, include_zero_d
)
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesMixin, QueryMatchingTest):
def setUp(self) -> None:
super().setUp()
@@ -1188,7 +1188,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
return full_reports
- @freeze_time("2022-01-10T00:01:00Z")
+ @time_machine.travel("2022-01-10T00:01:00Z", tick=False)
@patch("os.environ", {"DEPLOYMENT": "tests"})
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("ee.sqs.SQSProducer.get_sqs_producer")
@@ -1228,7 +1228,7 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM
# mock_posthog.capture.assert_has_calls(calls, any_order=True)
-@freeze_time("2022-01-09T00:01:00Z")
+@time_machine.travel("2022-01-09T00:01:00Z", tick=False)
class TestReplayUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesMixin):
def setUp(self) -> None:
super().setUp()
@@ -1833,7 +1833,7 @@ class TestQueryUsageReportSQL:
assert sponsor_params["sponsor_end"] == end + GATEWAY_SPONSORSHIP_LOOKAROUND
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestFeatureFlagsUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -2091,7 +2091,7 @@ class TestFeatureFlagsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickh
assert org_1_report["teams"][str(self.org_1_team_2.id)]["active_hog_transformations_in_period"] == 2
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestSurveysUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -2225,7 +2225,7 @@ class TestSurveysUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseT
assert report["event_count_in_period"] == 0
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestCaptureReportGroupProperties(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -2327,7 +2327,7 @@ class TestHasNonZeroUsage(TestCase):
assert has_non_zero_usage(report) is True
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestCaptureReportTrimsOversizePayload(TestCase):
@patch("posthog.tasks.usage_report.get_ph_client")
def test_capture_report_drops_teams_when_payload_too_large(self, mock_client: MagicMock) -> None:
@@ -2367,7 +2367,7 @@ class TestCaptureReportTrimsOversizePayload(TestCase):
assert len(json.dumps(captured_properties, default=str)) <= MAX_USAGE_REPORT_PAYLOAD_BYTES
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -2390,7 +2390,7 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
def test_external_data_rows_synced_free_period_response(
self, billing_task_mock: MagicMock, posthog_capture_mock: MagicMock
) -> None:
- with freeze_time("2025-11-01T00:00:00Z"):
+ with time_machine.travel("2025-11-01T00:00:00Z", tick=False):
self._setup_teams()
source = ExternalDataSource.objects.create(
@@ -2454,7 +2454,7 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
) -> None:
self._setup_teams()
- with freeze_time("2025-10-30T00:00:00Z"):
+ with time_machine.travel("2025-10-30T00:00:00Z", tick=False):
source_4 = ExternalDataSource.objects.create(
team_id=4,
source_id="source_id_2",
@@ -2463,7 +2463,7 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
source_type=ExternalDataSourceType.STRIPE,
)
- with freeze_time("2025-11-07T01:00:00Z"):
+ with time_machine.travel("2025-11-07T01:00:00Z", tick=False):
source_3 = ExternalDataSource.objects.create(
team_id=3,
source_id="source_id",
@@ -2526,7 +2526,7 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
def test_external_data_rows_synced_before_free_period_response(
self, billing_task_mock: MagicMock, posthog_capture_mock: MagicMock
) -> None:
- with freeze_time("2025-10-28T23:59:00Z"):
+ with time_machine.travel("2025-10-28T23:59:00Z", tick=False):
self._setup_teams()
source = ExternalDataSource.objects.create(
@@ -3034,7 +3034,7 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
assert org_2_report["rows_synced_in_period"] == 0
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestDWHStorageUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -3248,7 +3248,7 @@ class TestDWHStorageUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhou
assert org_2_report["dwh_mat_views_storage_in_s3_in_mib"] == 0
-@freeze_time("2022-01-10T00:01:00Z")
+@time_machine.travel("2022-01-10T00:01:00Z", tick=False)
class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -3697,7 +3697,7 @@ class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, Clickh
assert team_1_report[field] == value, field
-@freeze_time("2022-01-10T10:00:00Z")
+@time_machine.travel("2022-01-10T10:00:00Z", tick=False)
class TestErrorTrackingUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -3810,7 +3810,7 @@ class TestAICreditsRegionHandling(SimpleTestCase):
)
-@freeze_time("2022-01-10T10:00:00Z")
+@time_machine.travel("2022-01-10T10:00:00Z", tick=False)
class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
Team.objects.all().delete()
@@ -5322,7 +5322,7 @@ class TestSendUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest
}
}
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("ee.sqs.SQSProducer.get_sqs_producer")
def test_send_usage(self, mock_get_sqs_producer: MagicMock, mock_client: MagicMock) -> None:
@@ -5356,7 +5356,7 @@ class TestSendUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest
# timestamp=None,
# )
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("ee.sqs.SQSProducer.get_sqs_producer")
def test_send_usage_cloud(self, mock_get_sqs_producer: MagicMock, mock_client: MagicMock) -> None:
@@ -5452,7 +5452,7 @@ class TestSendNoUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTe
super().setUp()
materialize("events", "$exception_values")
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("requests.post")
def test_usage_not_sent_if_zero(self, mock_post: MagicMock, mock_client: MagicMock) -> None:
@@ -5469,7 +5469,7 @@ class TestSendUsageNoLicense(APIBaseTest):
super().setUp()
materialize("events", "$exception_values")
- @freeze_time("2021-10-10T23:01:00Z")
+ @time_machine.travel("2021-10-10T23:01:00Z", tick=False)
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("requests.post")
def test_no_license(self, mock_post: MagicMock, mock_client: MagicMock) -> None:
@@ -5528,7 +5528,7 @@ class TestSendUsageNoLicense(APIBaseTest):
_ = team.organization.for_internal_metrics
-@freeze_time("2021-10-10T23:01:00Z")
+@time_machine.travel("2021-10-10T23:01:00Z", tick=False)
class TestOrganizationFiltering(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest):
"""Test organization_ids filtering for send_all_org_usage_reports"""
diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
index 0754daaf99b0..3e7aa444b3a1 100644
--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from temporalio import activity
from temporalio.exceptions import ApplicationError
@@ -639,8 +639,12 @@ class TestRunAggregateEvaluationWorkflow:
assert elapsed < timedelta(hours=1)
-@freeze_time("2026-07-23T12:00:00Z")
class TestCheckTraceSettledActivity:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-23T12:00:00Z", tick=False):
+ yield
+
@pytest.mark.django_db(transaction=True)
def test_settled_when_quiet_beyond_margin(self, setup_data):
team = setup_data["team"]
@@ -714,8 +718,12 @@ class TestCheckTraceSettledActivity:
assert "trace active" in err.value.message
-@freeze_time("2026-07-23T12:00:00Z")
class TestCheckSessionSettledActivity:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-23T12:00:00Z", tick=False):
+ yield
+
@pytest.mark.django_db(transaction=True)
def test_settled_when_quiet_beyond_margin(self, setup_data):
team = setup_data["team"]
diff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.py
index 2ef71116e560..b2124663ffbc 100644
--- a/posthog/temporal/ai_observability/test_run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py
@@ -2,7 +2,7 @@ import uuid
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import Mock, patch
from asgiref.sync import async_to_sync
@@ -142,7 +142,6 @@ class TestFormatSessionForJudge:
assert "t-beta" in rendered
-@freeze_time(FROZEN_NOW)
class TestCountSessionEvents:
def test_the_count_stays_an_ungrouped_aggregate(self):
"""An ungrouped aggregate always returns exactly one row, so `query_ai_events`'s
@@ -173,7 +172,7 @@ class TestCountSessionEvents:
"posthog.temporal.ai_observability.run_session_evaluation.query_ai_events",
return_value=Mock(results=[[7, first_seen]]),
) as mock_query_ai_events:
- result = _count_session_events(Mock(), "s-1", datetime.now(UTC), datetime.now(UTC))
+ result = _count_session_events(Mock(), "s-1", FROZEN_NOW, FROZEN_NOW)
assert result.event_count == 7
assert result.first_seen == first_seen
@@ -214,7 +213,7 @@ class TestFetchSessionForEvaluation:
window_start = datetime(2026, 7, 20, tzinfo=UTC)
now = datetime(2026, 7, 21, tzinfo=UTC)
with (
- freeze_time(now),
+ time_machine.travel(now, tick=False),
patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
patch(
"posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",
@@ -368,7 +367,6 @@ class TestFetchSessionForEvaluation:
assert outcome.skip_reason == "session_truncated"
-@freeze_time(FROZEN_NOW)
class TestExecuteSessionActivities:
@pytest.mark.parametrize(
"skip_reason",
@@ -388,7 +386,7 @@ class TestExecuteSessionActivities:
},
team_id=1,
session_id="s-1",
- window_start=datetime.now(UTC).isoformat(),
+ window_start=FROZEN_NOW.isoformat(),
)
)
assert result["skipped"] is True
@@ -402,7 +400,7 @@ class TestExecuteSessionActivities:
evaluation={"evaluation_type": "hog", "output_type": "boolean"},
team_id=1,
session_id="s-1",
- window_start=datetime.now(UTC).isoformat(),
+ window_start=FROZEN_NOW.isoformat(),
)
)
@@ -424,7 +422,7 @@ class TestExecuteSessionActivities:
},
team_id=1,
session_id="s-1",
- window_start=datetime.now(UTC).isoformat(),
+ window_start=FROZEN_NOW.isoformat(),
)
)
assert result["skipped"] is True
@@ -454,7 +452,7 @@ class TestExecuteSessionActivities:
},
team_id=1,
session_id="s-1",
- window_start=datetime.now(UTC).isoformat(),
+ window_start=FROZEN_NOW.isoformat(),
)
)
assert result["skipped"] is True
@@ -490,6 +488,6 @@ class TestExecuteSessionActivities:
},
team_id=1,
session_id="s-1",
- window_start=datetime.now(UTC).isoformat(),
+ window_start=FROZEN_NOW.isoformat(),
)
)
diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
index 816186a0ebd7..14f9a18b7388 100644
--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from asgiref.sync import async_to_sync
@@ -292,7 +292,7 @@ class TestFetchTraceForEvaluation:
trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "q", "$ai_output": "a"})])
with (
- freeze_time(FROZEN_NOW),
+ time_machine.travel(FROZEN_NOW, tick=False),
patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=1),
patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,
):
@@ -331,7 +331,7 @@ class TestFetchTraceForEvaluation:
# bounded runner can return a trace row with no transcript to grade. A live run keeps
# whatever it did with that row before, so only the backfilled run skips.
with (
- freeze_time(FROZEN_NOW),
+ time_machine.travel(FROZEN_NOW, tick=False),
patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=2),
patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,
):
@@ -386,7 +386,7 @@ class TestRunHogEvalOverRecentTraces:
rewritten_condition = where_clause.exprs[-1]
assert rewritten_condition.left.chain == ["input"]
- @freeze_time(FROZEN_NOW)
+ @time_machine.travel(FROZEN_NOW, tick=False)
def test_uses_the_sampled_trigger_and_configured_aggregation_window(self):
team = MagicMock(spec=Team)
trigger_timestamp = FROZEN_NOW - timedelta(hours=2)
@@ -660,7 +660,7 @@ class TestEmitTraceEvaluationEventActivity:
}
with (
- freeze_time(FROZEN_NOW),
+ time_machine.travel(FROZEN_NOW, tick=False),
patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token),
patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture,
):
@@ -741,7 +741,6 @@ class TestEmitTraceEvaluationEventActivity:
await emit_trace_evaluation_event_activity(inputs)
-@freeze_time(FROZEN_NOW)
class TestEmitSessionEvaluationEvent:
@pytest.mark.parametrize(
"target,ai_session_id,expected_target_type,expected_target_id",
@@ -777,7 +776,7 @@ class TestEmitSessionEvaluationEvent:
distinct_id="user-1",
session_id="ph-session-1",
result={"verdict": True, "reasoning": "", "result_type": "boolean"},
- start_time=datetime.now(UTC),
+ start_time=FROZEN_NOW,
target=target,
ai_session_id=ai_session_id,
)
@@ -814,7 +813,7 @@ class TestEmitSessionEvaluationEvent:
distinct_id="user-1",
session_id=None,
result={"verdict": True, "reasoning": "", "result_type": "boolean"},
- start_time=datetime.now(UTC),
+ start_time=FROZEN_NOW,
target="session",
ai_session_id="session-abc",
)
diff --git a/posthog/temporal/experiments/test_cache_warming.py b/posthog/temporal/experiments/test_cache_warming.py
index 9b3a520ff10b..3ccaa99b3d0f 100644
--- a/posthog/temporal/experiments/test_cache_warming.py
+++ b/posthog/temporal/experiments/test_cache_warming.py
@@ -1,7 +1,7 @@
from datetime import datetime
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
@@ -29,7 +29,7 @@ from products.experiments.backend.models.experiment import (
@override_settings(IN_UNIT_TESTING=True)
class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
def test_regular_metric_activity_pins_runner_to_stored_query_to(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -59,7 +59,7 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):
result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])
assert result_row.query_to == expected_query_to
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
def test_saved_metric_activity_pins_runner_to_stored_query_to(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -99,7 +99,7 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):
result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])
assert result_row.query_to == expected_query_to
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
def test_temporal_activity_warms_query_cache(self):
"""
After the daily Temporal recalc activity runs, a frontend /query
@@ -176,7 +176,7 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):
assert isinstance(warm_response, CachedExperimentQueryResponse)
self.assertTrue(warm_response.is_cached)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
def test_temporal_activity_warms_query_cache_for_saved_metric(self):
"""
Saved metrics go through two backend-side transformations before /query
diff --git a/posthog/temporal/proxy_service/test/monitor_test.py b/posthog/temporal/proxy_service/test/monitor_test.py
index e5f76af0b123..f008eedd45c8 100644
--- a/posthog/temporal/proxy_service/test/monitor_test.py
+++ b/posthog/temporal/proxy_service/test/monitor_test.py
@@ -2,7 +2,7 @@ import json
import ipaddress
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, Mock, patch
from django.test import TestCase
@@ -47,7 +47,7 @@ class TestCheckProxyIsLive(TestCase):
self.assertEqual(result.warnings, [])
@pytest.mark.asyncio
- @freeze_time("2024-01-16 10:00:00") # Frozen at Jan 16, cert expires Feb 15 (30 days later)
+ @time_machine.travel("2024-01-16 10:00:00", tick=False) # Frozen at Jan 16, cert expires Feb 15 (30 days later)
@patch("posthog.temporal.proxy_service.monitor.socket.create_connection")
@patch("posthog.temporal.proxy_service.monitor.ssl.create_default_context")
@patch("posthog.temporal.proxy_service.monitor.requests.post")
@@ -159,7 +159,7 @@ class TestCheckProxyIsLive(TestCase):
mock_create_connection.assert_not_called()
@pytest.mark.asyncio
- @freeze_time("2024-01-16 10:00:00")
+ @time_machine.travel("2024-01-16 10:00:00", tick=False)
@patch("posthog.temporal.proxy_service.monitor.validate_url_and_pin_ips")
@patch("posthog.temporal.proxy_service.monitor.socket.create_connection")
@patch("posthog.temporal.proxy_service.monitor.ssl.create_default_context")
@@ -244,7 +244,9 @@ class TestCheckProxyIsLive(TestCase):
self.assertEqual(result.warnings, [])
@pytest.mark.asyncio
- @freeze_time("2024-01-16 10:00:00") # Frozen at Jan 16, cert expires Jan 25 (9 days later, < 14 day threshold)
+ @time_machine.travel(
+ "2024-01-16 10:00:00", tick=False
+ ) # Frozen at Jan 16, cert expires Jan 25 (9 days later, < 14 day threshold)
@patch("posthog.temporal.proxy_service.monitor.socket.create_connection")
@patch("posthog.temporal.proxy_service.monitor.ssl.create_default_context")
@patch("posthog.temporal.proxy_service.monitor.requests.post")
diff --git a/posthog/temporal/tests/common/test_health_server.py b/posthog/temporal/tests/common/test_health_server.py
index 7ad7702b5cc1..acd4625b2801 100644
--- a/posthog/temporal/tests/common/test_health_server.py
+++ b/posthog/temporal/tests/common/test_health_server.py
@@ -3,7 +3,7 @@ from contextlib import asynccontextmanager
from datetime import timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from aiohttp import ClientSession
@@ -39,7 +39,7 @@ class TestHealthCheckServer:
assert data["idle_seconds"] < 1.0
assert data["max_idle_seconds"] == 2.0
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
async def test_healthz_returns_unhealthy_when_idle_too_long(self):
"""Test that /healthz returns 503 when idle time exceeds threshold."""
@@ -157,14 +157,14 @@ class TestHealthCheckServer:
async def test_idle_time_accuracy(self):
"""Test that idle_time is calculated accurately."""
- with freeze_time("2024-01-01 12:00:00") as frozen_time:
+ with time_machine.travel("2024-01-01 12:00:00", tick=False) as frozen_time:
tracker = LivenessTracker()
async with create_server(tracker):
# Record activity at t=0
tracker.record_activity_execution()
# Move time forward 0.5 seconds
- frozen_time.tick(timedelta(seconds=0.5))
+ frozen_time.shift(timedelta(seconds=0.5))
async with ClientSession() as session:
async with session.get("http://localhost:18001/healthz") as response:
@@ -175,7 +175,7 @@ class TestHealthCheckServer:
async def test_healthz_transition_from_healthy_to_unhealthy(self):
"""Test that health status changes as time passes."""
- with freeze_time("2024-01-01 12:00:00") as frozen_time:
+ with time_machine.travel("2024-01-01 12:00:00", tick=False) as frozen_time:
tracker = LivenessTracker()
async with create_server(tracker):
tracker.record_activity_execution()
@@ -186,7 +186,7 @@ class TestHealthCheckServer:
assert response.status == 200
# Move time forward past threshold (2 seconds + buffer)
- frozen_time.tick(timedelta(seconds=2.5))
+ frozen_time.shift(timedelta(seconds=2.5))
# Should now be unhealthy
async with ClientSession() as session:
diff --git a/posthog/temporal/tests/common/test_logger.py b/posthog/temporal/tests/common/test_logger.py
index f7ddf3e8dc26..e3af904eb2c9 100644
--- a/posthog/temporal/tests/common/test_logger.py
+++ b/posthog/temporal/tests/common/test_logger.py
@@ -8,7 +8,7 @@ import dataclasses
from typing import cast
import pytest
-import freezegun
+import time_machine
from django.conf import settings
from django.test import override_settings
@@ -410,7 +410,7 @@ async def test_logger_binds_activity_context(
assert info_dict["workflow_run_id"] == activity_environment.info.workflow_run_id
[email protected]_time("2023-11-02 10:00:00.123123")
+@time_machine.travel("2023-11-02 10:00:00.123123", tick=False)
@pytest.mark.parametrize(
"activity_environment",
ACTIVITY_INFOS,
@@ -553,7 +553,7 @@ async def test_logger_produces_to_kafka_from_activity(activity_environment, prod
)
for activity in activities:
- with freezegun.freeze_time("2024-01-01 00:00:00", real_asyncio=True):
+ with time_machine.travel("2024-01-01 00:00:00", tick=False):
if fut := activity_environment.run(activity):
await fut
@@ -636,7 +636,7 @@ class TestWorkflow:
)
[email protected]_time("2023-11-02 10:00:00.123123")
+@time_machine.travel("2023-11-02 10:00:00.123123", tick=False)
@pytest.mark.parametrize("log_capture", [False], indirect=True)
async def test_logger_produces_to_log_queue_from_workflow(queue):
"""Test whether our logger produces into a queue for async processing."""
@@ -708,7 +708,7 @@ async def test_logger_produces_to_kafka_from_workflow(producer, queue, log_entri
activities=[],
workflow_runner=UnsandboxedWorkflowRunner(),
):
- with freezegun.freeze_time("2024-01-01 00:00:00", real_asyncio=True):
+ with time_machine.travel("2024-01-01 00:00:00", tick=False):
await workflow_environment.client.execute_workflow(
TestWorkflow.run,
id=workflow_id,
diff --git a/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py b/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py
index 1d57f9d79154..2da64c3e2d9c 100644
--- a/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py
+++ b/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py
@@ -2,7 +2,7 @@ import json
import random
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
from unittest.mock import MagicMock, patch
@@ -283,7 +283,7 @@ class TestRecordingsThatMatchPlaylistFilters(APIBaseTest, QueryMatchingTest):
def test_sorts_nulls_first_and_then_least_recently_counted(
self, _mock_list_recordings_from_query: MagicMock, mock_capture_exception: MagicMock
):
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
playlist1 = SessionRecordingPlaylist.objects.create(
team=self.team,
name="test1",
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index d4d917dd6fe2..2553184d99dd 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -3,7 +3,7 @@ import contextlib
from datetime import UTC, datetime
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
import pytest_asyncio
@@ -278,7 +278,7 @@ class TestPrepareAlert:
expected_reason: SkipReason,
advances_next_check_at: bool,
) -> None:
- ctx = freeze_time(frozen_time) if frozen_time else contextlib.nullcontext()
+ ctx = time_machine.travel(frozen_time, tick=False) if frozen_time else contextlib.nullcontext()
with ctx:
a = await _create_alert(ateam, **setup_kwargs)
env = ActivityEnvironment()
@@ -297,7 +297,7 @@ class TestPrepareAlert:
# Non-advancing skip branches must leave next_check_at untouched.
assert refreshed.next_check_at == setup_kwargs.get("next_check_at")
- @freeze_time("2024-06-03T10:00:00Z")
+ @time_machine.travel("2024-06-03T10:00:00Z", tick=False)
async def test_snoozed_future_preserves_snoozed_until(self, ateam) -> None:
# Separate from the parameterized set because it asserts a DB field is UNCHANGED,
# which doesn't fit the generic "next_check_at advanced" pattern.
@@ -310,7 +310,7 @@ class TestPrepareAlert:
refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=a.pk)
assert refreshed.snoozed_until == snoozed
- @freeze_time("2024-06-03T10:00:00Z")
+ @time_machine.travel("2024-06-03T10:00:00Z", tick=False)
async def test_snoozed_until_in_past_is_cleared_and_evaluation_proceeds(self, ateam) -> None:
past = datetime(2024, 6, 3, 9, 0, tzinfo=UTC)
a = await _create_alert(ateam, snoozed_until=past, state=AlertState.SNOOZED)
diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.py
index 72f7b4939772..1dc4a30b009e 100644
--- a/posthog/temporal/tests/test_alerts_investigation.py
+++ b/posthog/temporal/tests/test_alerts_investigation.py
@@ -7,7 +7,7 @@ the helpers directly so they're independent of Temporal harnessing.
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -50,7 +50,7 @@ class InvestigationTestCase(BaseTest):
investigation_status: str | None = None,
investigation_verdict: str | None = None,
) -> AlertCheck:
- with freeze_time(at):
+ with time_machine.travel(at, tick=False):
return AlertCheck.objects.create(
alert_configuration=self.alert,
state=state,
@@ -219,7 +219,7 @@ class TestInvestigationCooldown(InvestigationTestCase):
self._make_check(at=_EPISODE_START, investigation_status=InvestigationStatus.DONE)
check = self._make_check(at=_EPISODE_START + timedelta(hours=1))
- with freeze_time(_EPISODE_START + timedelta(hours=1)):
+ with time_machine.travel(_EPISODE_START + timedelta(hours=1), tick=False):
assert claim_investigation_slot(self.alert, check)
@@ -227,7 +227,7 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
def test_claims_when_no_recent_investigation(self) -> None:
check = self._make_check(at=_EPISODE_START)
- with freeze_time(_EPISODE_START):
+ with time_machine.travel(_EPISODE_START, tick=False):
assert claim_investigation_slot(self.alert, check)
check.refresh_from_db()
@@ -238,7 +238,7 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
self._make_check(at=now - timedelta(minutes=10), investigation_status=InvestigationStatus.DONE)
new_check = self._make_check(at=now)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert not claim_investigation_slot(self.alert, new_check)
new_check.refresh_from_db()
@@ -249,7 +249,7 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
self._make_check(at=now - timedelta(hours=2), investigation_status=InvestigationStatus.DONE)
new_check = self._make_check(at=now)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert claim_investigation_slot(self.alert, new_check)
new_check.refresh_from_db()
@@ -267,7 +267,7 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
self._make_check(at=now - timedelta(minutes=10), investigation_status=blocking_status)
new_check = self._make_check(at=now)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert not claim_investigation_slot(self.alert, new_check)
@parameterized.expand(
@@ -281,7 +281,7 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
self._make_check(at=now - timedelta(minutes=10), investigation_status=terminal_status)
new_check = self._make_check(at=now)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert claim_investigation_slot(self.alert, new_check)
@parameterized.expand(
@@ -299,7 +299,7 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
self._make_check(at=now - timedelta(minutes=30), investigation_status=in_flight_status)
new_check = self._make_check(at=now)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert not claim_investigation_slot(self.alert, new_check)
new_check.refresh_from_db()
@@ -321,5 +321,5 @@ class TestClaimInvestigationSlot(InvestigationTestCase):
)
new_check = self._make_check(at=now)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert claim_investigation_slot(self.alert, new_check)
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index e4d581e7b5fe..f1471c68c235 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -7,7 +7,7 @@ from typing import Any, cast
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
@@ -285,7 +285,7 @@ async def subscriptions_worker(temporal_client: Client):
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_subscription_delivery_scheduling(
mock_send_email: MagicMock,
@@ -316,7 +316,7 @@ async def test_subscription_delivery_scheduling(
await sync_to_async(set_instance_setting)("EMAIL_HOST", "fake_host")
await sync_to_async(set_instance_setting)("EMAIL_ENABLED", True)
- with freeze_time("2022-02-02T08:30:00.000Z"):
+ with time_machine.travel("2022-02-02T08:30:00.000Z", tick=False):
subscriptions = [
await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user),
await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user),
@@ -364,7 +364,7 @@ async def test_subscription_delivery_scheduling(
"products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team", return_value=None
)
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_does_not_schedule_subscription_if_item_is_deleted(
mock_send_email: MagicMock,
@@ -653,7 +653,7 @@ async def test_deliver_subscription_report_teams(
@patch(
"products.exports.backend.temporal.subscriptions.delivery_common.get_slack_integration_for_team", return_value=None
)
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_process_subscription_records_missing_slack_integration_failure(
mock_get_slack: MagicMock,
@@ -1101,7 +1101,7 @@ async def test_deliver_subscription_handles_slack_api_errors(team, user, slack_e
@patch("posthog.slo.events.posthoganalytics")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_creates_exported_assets(
mock_analytics: MagicMock,
@@ -1149,7 +1149,7 @@ async def test_create_export_assets_creates_exported_assets(
@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")
@patch("posthog.slo.events.posthoganalytics")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_persists_insight_snapshots_to_delivery_content(
mock_analytics: MagicMock,
@@ -1198,7 +1198,7 @@ async def test_create_export_assets_persists_insight_snapshots_to_delivery_conte
mock_analytics.capture.assert_not_called()
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_delivery_record_persists_row_and_idempotency_key_dedupes(team, user):
insight = await sync_to_async(Insight.objects.create)(team=team, short_id="delrec01", name="Delivery record")
@@ -1242,7 +1242,7 @@ async def test_create_delivery_record_persists_row_and_idempotency_key_dedupes(t
assert row_after.temporal_workflow_id == "wf-delivery-1"
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_update_delivery_record_patches_status_and_results_without_touching_content(team, user):
# update_delivery_record is the observability finalizer; create_export_assets
@@ -1288,7 +1288,7 @@ async def test_update_delivery_record_patches_status_and_results_without_touchin
assert row.finished_at is not None
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_update_delivery_record_none_omits_collection_fields(team, user):
insight = await sync_to_async(Insight.objects.create)(team=team, short_id="omit01", name="Omit fields")
@@ -1334,7 +1334,7 @@ async def test_update_delivery_record_none_omits_collection_fields(team, user):
assert row.recipient_results == [{"recipient": "[email protected]", "status": "success"}]
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_update_delivery_record_empty_lists_persist(team, user):
insight = await sync_to_async(Insight.objects.create)(team=team, short_id="empty01", name="Empty lists")
@@ -1381,7 +1381,7 @@ async def test_update_delivery_record_empty_lists_persist(team, user):
@patch("posthog.slo.events.posthoganalytics")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_dashboard_with_multiple_insights(
mock_analytics: MagicMock,
@@ -1424,7 +1424,7 @@ async def test_create_export_assets_dashboard_with_multiple_insights(
@patch("posthog.slo.events.posthoganalytics")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
@patch("products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_stale_dashboard_selection_fails_without_retrying(
mock_capture_delivery_failed: MagicMock,
@@ -1501,7 +1501,7 @@ async def test_stale_dashboard_selection_fails_without_retrying(
assert properties["reason"] == NoExportableInsightsReason.SELECTED_INSIGHTS_NO_LONGER_AVAILABLE
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_excludes_deleted_insights(team, user):
dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="With deleted", created_by=user)
@@ -1523,7 +1523,7 @@ async def test_create_export_assets_excludes_deleted_insights(team, user):
assert result.total_insight_count == 2
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_classifies_missing_resource(team, user):
subscription = await sync_to_async(create_subscription)(team=team, created_by=user)
@@ -1572,7 +1572,7 @@ async def test_resolve_exportable_insights_filters_explicit_dashboard_selection(
assert result.no_exportable_reason is None
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_respects_max_asset_count(team, user):
dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Big dashboard", created_by=user)
@@ -1599,7 +1599,7 @@ async def test_create_export_assets_rejects_non_positive_max_asset_count():
)
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_empty_dashboard(team, user):
dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Empty", created_by=user)
@@ -1617,7 +1617,7 @@ async def test_create_export_assets_empty_dashboard(team, user):
assert result.failure_context["reason"] == NoExportableInsightsReason.EMPTY_DASHBOARD
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_create_export_assets_excludes_deleted_standalone_insight(team, user):
insight = await sync_to_async(Insight.objects.create)(team=team, short_id="deleted01", deleted=True)
@@ -1635,7 +1635,7 @@ async def test_create_export_assets_excludes_deleted_standalone_insight(team, us
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_deliver_subscription_legacy_false_sends_all_recipients(
mock_send_email: MagicMock,
@@ -1673,7 +1673,7 @@ async def test_deliver_subscription_legacy_false_sends_all_recipients(
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_deliver_subscription_workflow_end_to_end(
mock_send_email: MagicMock,
@@ -1874,7 +1874,7 @@ async def test_manual_send_uses_regular_template_not_invite(
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_scheduled_delivery_updates_next_delivery_date(
mock_send_email: MagicMock,
@@ -1962,7 +1962,7 @@ def _make_export_counter(fail_count: int, error_factory):
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_export_error_slo_outcome(
mock_send_email: MagicMock,
@@ -2068,7 +2068,7 @@ async def test_export_error_slo_outcome(
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_partial_export_failure_delivers_successful_assets(
mock_send_email: MagicMock,
@@ -2176,7 +2176,7 @@ async def test_partial_export_failure_delivers_successful_assets(
@patch("posthog.slo.events.posthoganalytics")
@patch("ee.tasks.subscriptions.get_metric_meter")
@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_delivery_failure_replaces_partial_export_slo_attribution(
mock_send_email: MagicMock,
@@ -2384,7 +2384,7 @@ async def test_fetch_due_subscriptions_excludes_disabled(team, user):
)
@patch("posthog.temporal.exports.activities.exporter")
@patch("posthog.slo.events.posthoganalytics")
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_deliver_subscription_emits_success_slo_when_disabling(
mock_slo_analytics: MagicMock,
@@ -2889,7 +2889,7 @@ async def test_skip_helper_falls_back_when_billing_period_unsynced(team, user):
@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")
@patch(_GENERATE_REPORT)
@patch(_IS_OVER_BUDGET, return_value=True)
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_schedule_ai_subscription_over_credit_budget_lands_skipped(
mock_over_budget: MagicMock,
@@ -2945,7 +2945,7 @@ async def test_schedule_ai_subscription_over_credit_budget_lands_skipped(
"products.exports.backend.temporal.subscriptions.ai_subscription.activities.build_ai_subscription_report",
return_value=AiReportResult(markdown="# AI Report", diagnostics=(), window_end_utc="2026-06-25T12:00:00+00:00"),
)
-@freeze_time("2022-02-02T08:55:00.000Z")
+@time_machine.travel("2022-02-02T08:55:00.000Z", tick=False)
@pytest.mark.asyncio
async def test_schedule_routes_ai_subscription_through_full_workflow(
mock_generate: MagicMock,
diff --git a/posthog/test/activity_logging/test_organization_domain_activity_logging.py b/posthog/test/activity_logging/test_organization_domain_activity_logging.py
index 5f39816ac05f..baef9c77e5e8 100644
--- a/posthog/test/activity_logging/test_organization_domain_activity_logging.py
+++ b/posthog/test/activity_logging/test_organization_domain_activity_logging.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -152,7 +152,7 @@ class TestOrganizationDomainActivityLogging(APIBaseTest):
]
)
- with freeze_time("2024-01-15T12:00:00Z"):
+ with time_machine.travel("2024-01-15T12:00:00Z", tick=False):
response = self.client.post(f"/api/organizations/@current/domains/{domain.id}/verify")
self.assertEqual(response.status_code, 200)
self.assertTrue(response.json()["is_verified"])
diff --git a/posthog/test/activity_logging/test_retention.py b/posthog/test/activity_logging/test_retention.py
index ccaa0f01ef97..b92f1d7b4497 100644
--- a/posthog/test/activity_logging/test_retention.py
+++ b/posthog/test/activity_logging/test_retention.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from django.test import SimpleTestCase
@@ -30,7 +30,7 @@ class TestActivityLogLookbackWindow(SimpleTestCase):
def test_window_for_entitlement(self, _name: str, feature: dict, expected_days: int):
organization = Organization(available_product_features=[{"key": "audit_logs", **feature}])
- with freeze_time(NOW):
+ with time_machine.travel(NOW, tick=False):
restriction = get_activity_log_lookback_restriction(organization)
assert restriction is not None
diff --git a/posthog/test/assert_faster_than.py b/posthog/test/assert_faster_than.py
index fcf8ee63b15f..72eab35905d3 100644
--- a/posthog/test/assert_faster_than.py
+++ b/posthog/test/assert_faster_than.py
@@ -4,9 +4,9 @@ from contextlib import contextmanager
@contextmanager
def assert_faster_than(duration_ms: float):
- start = time.time()
+ start = time.monotonic()
yield
- actual_duration = (time.time() - start) * 1000.0
+ actual_duration = (time.monotonic() - start) * 1000.0
assert actual_duration < duration_ms, (
f"Execution took {actual_duration}ms which was not faster than {duration_ms}ms"
)
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 112f52089c6d..6455a565ea53 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -15,7 +15,6 @@ from typing import Any, Optional, Union, cast
import pytest
import unittest
-import freezegun
from unittest.mock import patch
from django.apps import apps
@@ -27,9 +26,6 @@ from django.db.migrations.executor import MigrationExecutor
from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings
from django.test.utils import CaptureQueriesContext
-# we have to import pendulum for the side effect of importing it
-# freezegun.FakeDateTime and pendulum don't play nicely otherwise
-import pendulum # noqa F401
import sqlparse
from clickhouse_pool import ChPool
from clickhouse_pool.pool import TooManyConnections
@@ -244,12 +240,6 @@ from products.event_definitions.backend.models.property_definition import (
)
from products.product_analytics.backend.facade.models import Insight
-# Make sure freezegun ignores our utils class that times functions, and heavy optional
-# deps (e.g. transformers) that can break when freezegun walks sys.modules.
-cast(Any, freezegun).configure(
- extend_ignore_list=["posthog.test.assert_faster_than", "transformers"],
-)
-
events_cache_tests: list[dict[str, Any]] = []
from posthog.test.persons import stage_person_for_bulk_create # noqa: E402
@@ -1778,7 +1768,7 @@ def _create_event(**kwargs):
stored with timestamp `2022-11-24T19:00:00` - because America/Pheonix is UTC-7, and Phoenix noon occurs at 7 PM UTC.
If a `timestamp` WITH an explicit timezone is provided (in the case of ISO strings, this can be the "Z" suffix
signifying UTC), we use that timezone instead of the project timezone.
- If NO `timestamp` is provided, we use the current system time (which can be mocked with `freeze_time()`)
+ If NO `timestamp` is provided, we use the current system time (which can be mocked with `time_machine.travel()`)
and treat that as local to the project.
NOTE: All events get batched and only created when sync_execute is called.
diff --git a/posthog/test/persons.py b/posthog/test/persons.py
index 8af87954e34e..86c74d9c66ed 100644
--- a/posthog/test/persons.py
+++ b/posthog/test/persons.py
@@ -17,6 +17,8 @@ from __future__ import annotations
import datetime as dt
from typing import TYPE_CHECKING, Any
+import time_machine
+
from django.utils.timezone import now
from posthog.models import signals
@@ -281,7 +283,7 @@ def create_people_bulk(specs: list[dict[str, Any]]) -> list[Person]:
Each spec is a create_person() kwargs dict (team/team_id, distinct_ids, uuid, ...). Row values
mirror what create_person writes via posthog.models.person.util.create_person /
create_person_distinct_id — only batched. Note: distinct-id rows use Python-side
- (freezegun-frozen) time for _timestamp rather than ClickHouse server now(); harmless because
+ (time-machine-frozen) time for _timestamp rather than ClickHouse server now(); harmless because
pdi2 dedup uses version, not _timestamp. The persons-DB-layer path (fake off) falls back to
per-person create_person.
"""
@@ -479,9 +481,7 @@ def stage_person_for_bulk_create(*args: Any, **kwargs: Any) -> Person:
else:
_next_deterministic_uuid()
- if kwargs.get("immediate") or (
- hasattr(dt.datetime.now(), "__module__") and dt.datetime.now().__module__ == "freezegun.api"
- ):
+ if kwargs.get("immediate") or time_machine.escape_hatch.is_travelling():
kwargs.pop("immediate", None)
return create_person(**kwargs)
diff --git a/posthog/test/test_database_healthcheck.py b/posthog/test/test_database_healthcheck.py
index da1889006ad0..c30a1ac7b4eb 100644
--- a/posthog/test/test_database_healthcheck.py
+++ b/posthog/test/test_database_healthcheck.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from django.test import TestCase
@@ -14,7 +14,7 @@ class TestDatabaseHealthcheck(TestCase):
def test_healthcheck(self):
self.healthcheck.is_postgres_connected_check = mock.MagicMock(return_value=True) # type: ignore
- with freeze_time("2021-01-01T00:00:00Z") as frozen_time:
+ with time_machine.travel("2021-01-01T00:00:00Z", tick=False) as frozen_time:
self.assertTrue(self.healthcheck.is_connected())
self.assertEqual(self.healthcheck.hits, 0)
self.assertEqual(self.healthcheck.misses, 1)
@@ -34,7 +34,7 @@ class TestDatabaseHealthcheck(TestCase):
self.healthcheck.is_postgres_connected_check.reset_mock()
# 30 seconds later
- frozen_time.tick(delta=30)
+ frozen_time.shift(30)
self.assertTrue(self.healthcheck.is_connected())
self.healthcheck.is_postgres_connected_check.assert_called_once()
@@ -43,7 +43,7 @@ class TestDatabaseHealthcheck(TestCase):
self.assertEqual(self.healthcheck.last_check, 53648641)
# 30 seconds later
- frozen_time.tick(delta=30)
+ frozen_time.shift(30)
self.healthcheck.is_postgres_connected_check = mock.MagicMock(return_value=False) # type: ignore
self.assertFalse(self.healthcheck.is_connected())
@@ -54,7 +54,7 @@ class TestDatabaseHealthcheck(TestCase):
def test_set_is_connected(self):
self.healthcheck.is_postgres_connected_check = mock.MagicMock(return_value=True) # type: ignore
- with freeze_time("2021-01-01T00:00:00Z") as frozen_time:
+ with time_machine.travel("2021-01-01T00:00:00Z", tick=False) as frozen_time:
self.healthcheck.set_connection(True)
self.assertTrue(self.healthcheck.is_connected())
@@ -72,7 +72,7 @@ class TestDatabaseHealthcheck(TestCase):
self.assertEqual(self.healthcheck.last_check, 53648640)
# 30 seconds later
- frozen_time.tick(delta=30)
+ frozen_time.shift(30)
self.assertTrue(self.healthcheck.is_connected())
self.healthcheck.is_postgres_connected_check.assert_called_once()
diff --git a/posthog/test/test_email.py b/posthog/test/test_email.py
index d4767c442c4c..dc4d84775623 100644
--- a/posthog/test/test_email.py
+++ b/posthog/test/test_email.py
@@ -7,7 +7,7 @@ from typing import Any
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -85,7 +85,7 @@ class TestEmail(BaseTest):
add_test_distinct_id(person=person, distinct_id=base_distinct_id)
return person
- @freeze_time("2020-09-21")
+ @time_machine.travel("2020-09-21", tick=False)
def setUp(self):
super().setUp()
self.organization = Organization.objects.create()
diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.py
index 37c6aaca18f9..f64de495a53d 100644
--- a/posthog/test/test_feature_flag_analytics.py
+++ b/posthog/test/test_feature_flag_analytics.py
@@ -3,7 +3,7 @@ import datetime
import concurrent.futures
import pytest
-from freezegun import config, configure, freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
BaseTest,
@@ -43,10 +43,6 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
maxDiff = None
- def tearDown(self):
- configure(default_ignore_list=config.DEFAULT_IGNORE_LIST)
- return super().tearDown()
-
def setUp(self):
# delete all keys in redis
r = redis.get_client()
@@ -59,7 +55,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
team_id = 3
other_team_id = 1243
- with freeze_time("2022-05-07 12:23:07") as frozen_datetime:
+ with time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime:
for _ in range(10):
# 10 requests in first bucket
increment_request_count(team_id)
@@ -67,7 +63,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 7 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
@@ -93,7 +89,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
def test_increment_request_count_remote_config_uses_own_bucket(self):
team_id = 3
- with freeze_time("2022-05-07 12:23:07"):
+ with time_machine.travel("2022-05-07 12:23:07", tick=False):
for _ in range(4):
increment_request_count(team_id)
for _ in range(6):
@@ -121,7 +117,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
other_team_uuid = "other-team-uuid"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
for _ in range(10):
@@ -133,7 +129,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 7 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
@@ -144,7 +140,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 3 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
for _ in range(5):
# 5 requests in third bucket
@@ -219,7 +215,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
team_uuid = "team-uuid"
other_team_uuid = "other-team-uuid"
- with freeze_time("2022-05-07 12:23:07") as frozen_datetime:
+ with time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime:
for _ in range(10):
# 10 requests in first bucket
increment_request_count(team_id)
@@ -227,7 +223,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 7 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
@@ -236,7 +232,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 3 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
for _ in range(5):
# 5 requests in third bucket
@@ -290,7 +286,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
id=other_team_id, organization=self.organization, api_token=f"token:::{other_team_id}", uuid=other_team_uuid
)
- with freeze_time("2022-05-07 12:23:07") as frozen_datetime:
+ with time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime:
for _ in range(10):
# 10 requests in first bucket
increment_request_count(team_id)
@@ -298,7 +294,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 7 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
@@ -307,7 +303,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 3 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
for _ in range(5):
# 5 requests in third bucket
@@ -345,13 +341,10 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
assert mock_capture.capture.call_count == 2
@pytest.mark.skip(
- reason="This works locally, but causes issues in CI because the freeze_time applies to threads as well in unrelated tests, causing timeouts."
+ reason="This works locally, but causes issues in CI because the frozen clock applies to threads as well in unrelated tests, causing timeouts."
)
@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
def test_no_interference_between_different_types_of_new_incoming_increments(self):
- # we want freezetime to apply to threads too.
- # However, the list can't be empty, so we need to add something.
- configure(default_ignore_list=["tensorflow"])
mock_capture = MagicMock()
team_id = 3
@@ -359,7 +352,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
team_uuid = "team-uuid"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
for _ in range(10):
@@ -367,21 +360,21 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
increment_request_count(team_id)
increment_request_count(team_id, 1, FlagRequestType.LOCAL_EVALUATION)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
increment_request_count(team_id)
increment_request_count(team_id, 1, FlagRequestType.LOCAL_EVALUATION)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
for _ in range(3):
# 3 requests in third bucket
increment_request_count(team_id)
increment_request_count(team_id, 1, FlagRequestType.LOCAL_EVALUATION)
- frozen_datetime.tick(datetime.timedelta(seconds=2))
+ frozen_datetime.shift(datetime.timedelta(seconds=2))
with concurrent.futures.ThreadPoolExecutor(max_workers=15) as executor:
future_to_index = {executor.submit(increment_request_count, team_id): index for index in range(5, 10)}
@@ -446,13 +439,10 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
self.assertEqual(client.hgetall(f"posthog:local_evaluation_requests:{other_team_id}"), {})
@pytest.mark.skip(
- reason="This works locally, but causes issues in CI because the freeze_time applies to threads as well in unrelated tests, causing timeouts."
+ reason="This works locally, but causes issues in CI because the frozen clock applies to threads as well in unrelated tests, causing timeouts."
)
@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
def test_locking_works_for_capture_team_decide_usage(self):
- # we want freezetime to apply to threads too.
- # However, the list can't be empty, so we need to add something.
- configure(default_ignore_list=["tensorflow"])
mock_capture = MagicMock()
team_id = 3
@@ -461,7 +451,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
other_team_uuid = "other-team-uuid"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
for _ in range(10):
@@ -471,7 +461,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 7 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
@@ -480,14 +470,14 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# 3 requests for other team
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
for _ in range(5):
# 5 requests in third bucket
increment_request_count(team_id)
increment_request_count(other_team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_index = {
@@ -537,13 +527,10 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
# TODO: Figure out a way to run these tests in CI
@pytest.mark.skip(
- reason="This works locally, but causes issues in CI because the freeze_time applies to threads as well in unrelated tests, causing timeouts."
+ reason="This works locally, but causes issues in CI because the frozen clock applies to threads as well in unrelated tests, causing timeouts."
)
@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)
def test_locking_in_redis_doesnt_block_new_incoming_increments(self):
- # we want freezetime to apply to threads too.
- # However, the list can't be empty, so we need to add something.
- configure(default_ignore_list=["tensorflow"])
mock_capture = MagicMock()
team_id = 3
@@ -551,26 +538,26 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):
team_uuid = "team-uuid"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
for _ in range(10):
# 10 requests in first bucket
increment_request_count(team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=5))
+ frozen_datetime.shift(datetime.timedelta(seconds=5))
for _ in range(5):
# 5 requests in second bucket
increment_request_count(team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
for _ in range(3):
# 3 requests in third bucket
increment_request_count(team_id)
- frozen_datetime.tick(datetime.timedelta(seconds=2))
+ frozen_datetime.shift(datetime.timedelta(seconds=2))
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_index = {
@@ -675,7 +662,7 @@ class TestSdkBreakdown(BaseTest):
client = redis.get_client()
team_id = 999
- with freeze_time("2022-05-07 12:23:07"):
+ with time_machine.travel("2022-05-07 12:23:07", tick=False):
result = _extract_sdk_breakdown_from_redis(client, team_id, FlagRequestType.DECIDE)
self.assertEqual(result, {})
@@ -684,20 +671,20 @@ class TestSdkBreakdown(BaseTest):
client = redis.get_client()
team_id = 888
- with freeze_time("2022-05-07 12:23:07") as frozen_datetime:
+ with time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime:
# Set up SDK-specific data in Redis in first bucket
time_bucket_1 = "165192618"
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-js", time_bucket_1, 100)
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-node", time_bucket_1, 50)
# Move to second bucket - each SDK key needs 2+ buckets for extraction
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
time_bucket_2 = "165192619"
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-js", time_bucket_2, 10)
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-node", time_bucket_2, 5)
# Move time forward so bucket 2 is no longer "current"
- frozen_datetime.tick(datetime.timedelta(seconds=15))
+ frozen_datetime.shift(datetime.timedelta(seconds=15))
result = _extract_sdk_breakdown_from_redis(client, team_id, FlagRequestType.DECIDE)
# Only bucket 1 should be extracted (bucket 2 is skipped as it's most recent)
@@ -720,7 +707,7 @@ class TestSdkBreakdown(BaseTest):
team_uuid = "team-uuid-777"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
client = redis.get_client()
@@ -734,14 +721,14 @@ class TestSdkBreakdown(BaseTest):
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-node", time_bucket_1, 50)
# Move to second bucket - each key needs 2+ buckets for extraction
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
time_bucket_2 = "165192619"
client.hincrby(f"posthog:decide_requests:{team_id}", time_bucket_2, 1)
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-js", time_bucket_2, 1)
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:posthog-node", time_bucket_2, 1)
# Move time forward so bucket 2 is no longer "current"
- frozen_datetime.tick(datetime.timedelta(seconds=15))
+ frozen_datetime.shift(datetime.timedelta(seconds=15))
capture_team_decide_usage(mock_capture, team_id, team_uuid)
@@ -766,7 +753,7 @@ class TestSdkBreakdown(BaseTest):
team_uuid = "team-uuid-666"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
client = redis.get_client()
@@ -776,11 +763,11 @@ class TestSdkBreakdown(BaseTest):
client.hincrby(f"posthog:decide_requests:{team_id}", time_bucket_1, 100)
# Move to second bucket (extraction requires 2+ buckets)
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
time_bucket_2 = "165192619"
client.hincrby(f"posthog:decide_requests:{team_id}", time_bucket_2, 1)
- frozen_datetime.tick(datetime.timedelta(seconds=15))
+ frozen_datetime.shift(datetime.timedelta(seconds=15))
capture_team_decide_usage(mock_capture, team_id, team_uuid)
@@ -805,7 +792,7 @@ class TestSdkBreakdown(BaseTest):
team_uuid = "team-uuid-555"
with (
- freeze_time("2022-05-07 12:23:07") as frozen_datetime,
+ time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime,
self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="token"),
):
client = redis.get_client()
@@ -817,13 +804,13 @@ class TestSdkBreakdown(BaseTest):
client.hincrby(f"posthog:local_evaluation_requests:sdk:{team_id}:posthog-node", time_bucket_1, 30)
# Move to second bucket - each key needs 2+ buckets for extraction
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
time_bucket_2 = "165192619"
client.hincrby(f"posthog:local_evaluation_requests:{team_id}", time_bucket_2, 1)
client.hincrby(f"posthog:local_evaluation_requests:sdk:{team_id}:posthog-python", time_bucket_2, 1)
client.hincrby(f"posthog:local_evaluation_requests:sdk:{team_id}:posthog-node", time_bucket_2, 1)
- frozen_datetime.tick(datetime.timedelta(seconds=15))
+ frozen_datetime.shift(datetime.timedelta(seconds=15))
capture_team_decide_usage(mock_capture, team_id, team_uuid)
@@ -852,7 +839,7 @@ class TestSdkBreakdown(BaseTest):
client = redis.get_client()
team_id = 444
- with freeze_time("2022-05-07 12:23:07") as frozen_datetime:
+ with time_machine.travel("2022-05-07 12:23:07", tick=False) as frozen_datetime:
time_bucket_1 = "165192618"
# Set up data for multiple SDKs (simulating real-world usage)
@@ -869,14 +856,14 @@ class TestSdkBreakdown(BaseTest):
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:{sdk}", time_bucket_1, count)
# Move to second bucket - extraction requires 2+ buckets
- frozen_datetime.tick(datetime.timedelta(seconds=10))
+ frozen_datetime.shift(datetime.timedelta(seconds=10))
time_bucket_2 = "165192619"
for sdk in test_sdks:
client.hincrby(f"posthog:decide_requests:sdk:{team_id}:{sdk}", time_bucket_2, 1)
# Move time forward so bucket 2 is no longer "current"
- frozen_datetime.tick(datetime.timedelta(seconds=15))
+ frozen_datetime.shift(datetime.timedelta(seconds=15))
result = _extract_sdk_breakdown_from_redis(client, team_id, FlagRequestType.DECIDE)
@@ -896,7 +883,7 @@ class TestSdkBreakdown(BaseTest):
client = redis.get_client()
team_id = 333
- with freeze_time("2022-05-07 12:23:07"):
+ with time_machine.travel("2022-05-07 12:23:07", tick=False):
time_bucket = "165192618"
# Set up data with only one bucket per SDK
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index eaf3006d50f7..d129be27d324 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, FuzzyInt, override_settings
from unittest.mock import MagicMock, patch
@@ -601,7 +601,7 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
def test_after_idle_timeout_api_requests_401(self):
now = datetime(2024, 1, 1, 12, 0, 0)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
res = self.client.get("/api/users/@me")
assert res.status_code == 200
@@ -611,7 +611,7 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
# Move forward by 19
now = now + timedelta(seconds=19)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.get("/api/users/@me")
assert res.status_code == 200
assert res.json()["email"] == "[email protected]"
@@ -620,13 +620,13 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
# Past idle timeout
now = now + timedelta(seconds=21)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.get("/api/users/@me")
assert res.status_code == 401
def test_after_total_timeout_api_requests_401(self):
now = datetime(2024, 1, 1, 12, 0, 0)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
res = self.client.get("/api/users/@me")
assert res.status_code == 200
@@ -637,7 +637,7 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
for _ in range(4):
# Move forward by 19 seconds 4 times for a total of 76 seconds
now = now + timedelta(seconds=19)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.get("/api/users/@me")
assert res.status_code == 200
assert res.json()["email"] == "[email protected]"
@@ -647,7 +647,7 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
)
now = now + timedelta(seconds=19)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.get("/api/users/@me")
assert res.status_code == 200
assert res.json()["email"] == "[email protected]"
@@ -657,17 +657,17 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
# Now even less than the idle time will take us past the total timeout
now = now + timedelta(seconds=10)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
res = self.client.get("/api/users/@me")
assert res.status_code == 401
def test_after_timeout_non_admin_page_redirects_to_admin(self):
"""When session times out on a non-admin page, redirect to /admin/."""
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
- with freeze_time(now + timedelta(seconds=35)):
+ with time_machine.travel(now + timedelta(seconds=35), tick=False):
res = self.client.get("/dashboards")
assert res.status_code == 302
assert res.headers["Location"] == "/admin/"
@@ -682,10 +682,10 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
third_user = User.objects.create_and_join(self.organization, email="[email protected]", password="123456")
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
- with freeze_time(now + timedelta(seconds=35)):
+ with time_machine.travel(now + timedelta(seconds=35), tick=False):
# Navigate to a different user's admin page
res = self.client.get(f"/admin/posthog/user/{third_user.id}/change/")
assert res.status_code == 302
@@ -700,7 +700,7 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
def test_explicit_logout_redirects_to_impersonated_user_admin(self):
"""When explicitly logging out via /logout, redirect to impersonated user's admin page."""
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
# Explicit logout via the main logout endpoint
@@ -727,7 +727,7 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
def test_loginas_logout_redirect(self, _name, query_suffix, expected_location):
"""The loginas logout endpoint redirects to a safe `next` when given, otherwise to the admin change page."""
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
res = self.client.get(f"/admin/logout/{query_suffix}")
@@ -743,10 +743,10 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
"""Even when the session has expired server-side, `next` survives the middleware
bounce so staff still land back in the PostHog app."""
now = datetime.now()
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
self.login_as_other_user()
- with freeze_time(now + timedelta(seconds=35)):
+ with time_machine.travel(now + timedelta(seconds=35), tick=False):
# First hit: the auto-logout middleware restores the original login and
# bounces back to the same path, preserving ?next=/.
res = self.client.get("/admin/logout/?next=/")
@@ -1632,7 +1632,7 @@ class TestSessionAgeMiddleware(APIBaseTest):
# Ensure any remaining patches are stopped
self.time_patcher.stop()
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
@patch("time.time", return_value=1704110400.0) # 2024-01-01 12:00:00
def test_session_continues_when_not_expired(self, mock_time):
# Initial request sets session creation time
@@ -1648,7 +1648,7 @@ class TestSessionAgeMiddleware(APIBaseTest):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
@patch("time.time", return_value=1704110400.0) # 2024-01-01 12:00:00
def test_session_expires_after_total_time(self, mock_time):
# Initial request sets session creation time
@@ -1669,7 +1669,7 @@ class TestSessionAgeMiddleware(APIBaseTest):
"/login?message=Your%20session%20has%20expired.%20Please%20log%20in%20again.",
)
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
@patch("time.time", return_value=1704110400.0) # 2024-01-01 12:00:00
def test_org_specific_session_timeout_from_cache(self, mock_time):
# Set org-specific timeout in cache
@@ -1693,7 +1693,7 @@ class TestSessionAgeMiddleware(APIBaseTest):
"/login?message=Your%20session%20has%20expired.%20Please%20log%20in%20again.",
)
- @freeze_time("2024-01-01 12:00:00")
+ @time_machine.travel("2024-01-01 12:00:00", tick=False)
@patch("time.time", return_value=1704110400.0) # 2024-01-01 12:00:00
def test_session_timeout_after_switching_org_with_cache(self, mock_time):
# Create another org with different timeout
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index 6a25a2cc09c2..ca3391e1040a 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -2,7 +2,7 @@ import json
from datetime import timedelta
from urllib.parse import quote
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, Mock, call, patch
@@ -241,7 +241,7 @@ class TestUserAPI(APIBaseTest):
def test_default_sustained_rate_limit(self, rate_limit_enabled_mock, incr_mock):
base_time = now()
for _ in range(5):
- with freeze_time(base_time):
+ with time_machine.travel(base_time, tick=False):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags",
headers={"authorization": f"Bearer {self.personal_api_key}"},
@@ -249,7 +249,7 @@ class TestUserAPI(APIBaseTest):
base_time += timedelta(seconds=61)
self.assertEqual(response.status_code, status.HTTP_200_OK)
- with freeze_time(base_time):
+ with time_machine.travel(base_time, tick=False):
for _ in range(2):
response = self.client.get(
f"/api/projects/{self.team.pk}/feature_flags",
@@ -514,7 +514,7 @@ class TestUserAPI(APIBaseTest):
@patch("posthog.rate_limit.statsd.incr")
@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
def test_does_not_call_get_instance_setting_for_every_request(self, rate_limit_enabled_mock, incr_mock):
- with freeze_time("2022-04-01 12:34:45") as frozen_time:
+ with time_machine.travel("2022-04-01 12:34:45", tick=False) as frozen_time:
with override_instance_config("RATE_LIMITING_ALLOW_LIST_TEAMS", f"{self.team.pk}"):
with patch.object(
rate_limit,
@@ -529,7 +529,7 @@ class TestUserAPI(APIBaseTest):
assert wrapped_get_instance_setting.call_count == 1
- frozen_time.tick(delta=timedelta(seconds=65))
+ frozen_time.shift(timedelta(seconds=65))
for _ in range(10):
self.client.get(
f"/api/projects/{self.team.pk}/feature_flags",
@@ -541,7 +541,7 @@ class TestUserAPI(APIBaseTest):
@patch("posthog.rate_limit.statsd.incr")
@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
def test_allow_list_works_as_expected(self, rate_limit_enabled_mock, incr_mock):
- with freeze_time("2022-04-01 12:34:45"):
+ with time_machine.travel("2022-04-01 12:34:45", tick=False):
with override_instance_config("RATE_LIMITING_ALLOW_LIST_TEAMS", f"{self.team.pk}"):
for _ in range(10):
response = self.client.get(
diff --git a/posthog/test/test_token_bucket.py b/posthog/test/test_token_bucket.py
index ff7a8d644ec1..b18e649e5ad2 100644
--- a/posthog/test/test_token_bucket.py
+++ b/posthog/test/test_token_bucket.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
@@ -21,7 +21,7 @@ class TestTokenBucket(SimpleTestCase):
self.addCleanup(TEST_reset_scripts)
def test_burst_then_deny_with_accurate_retry_after(self) -> None:
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
for _ in range(ONE_PER_SECOND.burst):
decision = consume("bucket:burst", ONE_PER_SECOND)
assert isinstance(decision, BucketDecision)
@@ -35,24 +35,24 @@ class TestTokenBucket(SimpleTestCase):
assert denied.reset == ONE_PER_SECOND.burst
def test_continuous_refill_and_burst_cap(self) -> None:
- with freeze_time("2026-01-01 00:00:00") as frozen:
+ with time_machine.travel("2026-01-01 00:00:00", tick=False) as frozen:
for _ in range(ONE_PER_SECOND.burst):
consume("bucket:refill", ONE_PER_SECOND)
- frozen.tick(5)
+ frozen.shift(5)
decision = consume("bucket:refill", ONE_PER_SECOND)
assert isinstance(decision, BucketDecision)
assert decision.allowed
assert decision.remaining == 4
# A long idle refills to capacity, never beyond it.
- frozen.tick(100_000)
+ frozen.shift(100_000)
decision = consume("bucket:refill", ONE_PER_SECOND)
assert isinstance(decision, BucketDecision)
assert decision.remaining == ONE_PER_SECOND.burst - 1
def test_refund_returns_tokens_capped_at_capacity(self) -> None:
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
for _ in range(3):
consume("bucket:refund", ONE_PER_SECOND)
assert refund("bucket:refund", ONE_PER_SECOND) == 8
@@ -61,7 +61,7 @@ class TestTokenBucket(SimpleTestCase):
assert refund("bucket:never-charged", ONE_PER_SECOND) == ONE_PER_SECOND.burst
def test_peek_reads_without_charging(self) -> None:
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
fresh = peek("bucket:peek", ONE_PER_SECOND)
assert isinstance(fresh, BucketDecision)
assert fresh.allowed
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 4f215b3e3c6c..f81aba1e013e 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any, cast
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import call, patch
@@ -333,7 +333,7 @@ class TestGeneralUtils(TestCase):
class TestRelativeDateParse(TestCase):
- @freeze_time("2020-01-31T12:22:23")
+ @time_machine.travel("2020-01-31T12:22:23", tick=False)
def test_hour(self):
self.assertEqual(
relative_date_parse("-24h", ZoneInfo("UTC")).isoformat(),
@@ -344,7 +344,7 @@ class TestRelativeDateParse(TestCase):
"2020-01-29T12:22:23+00:00",
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_day(self):
self.assertEqual(
relative_date_parse("dStart", ZoneInfo("UTC")).strftime("%Y-%m-%d"),
@@ -368,7 +368,7 @@ class TestRelativeDateParse(TestCase):
"2020-01-30T23:59:59.999999+00:00",
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_month(self):
self.assertEqual(
relative_date_parse("-1m", ZoneInfo("UTC")).strftime("%Y-%m-%d"),
@@ -413,21 +413,21 @@ class TestRelativeDateParse(TestCase):
("minus_two_end", "-2qEnd", "2019-09-30"),
]
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_quarter(self, _name, input, expected_date):
self.assertEqual(
relative_date_parse(input, ZoneInfo("UTC")).strftime("%Y-%m-%d"),
expected_date,
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_quarter_human_friendly_comparison_periods_keeps_week_alignment(self):
self.assertEqual(
relative_date_parse("-1q", ZoneInfo("UTC"), human_friendly_comparison_periods=True).strftime("%Y-%m-%d"),
"2019-11-01",
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_year(self):
self.assertEqual(
relative_date_parse("-1y", ZoneInfo("UTC")).strftime("%Y-%m-%d"),
@@ -456,14 +456,14 @@ class TestRelativeDateParse(TestCase):
("monday_start", 1, "2020-01-27"),
]
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_week_start(self, _name, week_start_day, expected_date):
self.assertEqual(
relative_date_parse("wStart", ZoneInfo("UTC"), team_week_start_day=week_start_day).strftime("%Y-%m-%d"),
expected_date,
)
- @freeze_time("2020-01-31")
+ @time_machine.travel("2020-01-31", tick=False)
def test_normal_date(self):
self.assertEqual(
relative_date_parse("2019-12-31", ZoneInfo("UTC")).strftime("%Y-%m-%d"),
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index 3e0aab3a9787..fecc6141ffe5 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -185,7 +185,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(Action.objects.count(), count)
- @freeze_time("2021-12-12")
+ @time_machine.travel("2021-12-12", tick=False)
@patch("products.actions.backend.api.action.report_user_action")
def test_update_action(self, patch_capture, *args):
user = self._create_user("test_user_update")
@@ -318,7 +318,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
action = Action.objects.get(pk=response.json()["id"])
assert action.steps[0].event == "test_event "
- @freeze_time("2021-12-12")
+ @time_machine.travel("2021-12-12", tick=False)
def test_listing_actions_is_not_nplus1(self) -> None:
# Pre-query to cache things like instance settings
self.client.get(f"/api/projects/{self.team.id}/actions/")
diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.py
index 548cddd8fad9..b2badd2acf2e 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py
@@ -1,7 +1,7 @@
import uuid
import datetime as dt
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -267,7 +267,7 @@ class TestEvaluationReportApi(APIBaseTest):
def test_list_reports(self):
report_with_runs = self._create_report(rrule="FREQ=DAILY", timezone_name="UTC")
report_without_runs = self._create_report(evaluation=self._create_boolean_evaluation())
- with freeze_time("2026-08-10T12:00:00Z"):
+ with time_machine.travel("2026-08-10T12:00:00Z", tick=False):
EvaluationReportRun.objects.create(
report=report_with_runs,
content={},
@@ -275,7 +275,7 @@ class TestEvaluationReportApi(APIBaseTest):
period_start=timezone.now() - dt.timedelta(hours=1),
period_end=timezone.now(),
)
- with freeze_time("2026-08-11T12:00:00Z"):
+ with time_machine.travel("2026-08-11T12:00:00Z", tick=False):
EvaluationReportRun.objects.create(
report=report_with_runs,
content={},
@@ -523,7 +523,7 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertEqual(response.json().get("attr"), "rrule")
def test_create_scheduled_defaults_starts_at(self):
- with freeze_time("2026-01-15T16:37:42Z"):
+ with time_machine.travel("2026-01-15T16:37:42Z", tick=False):
response = self.client.post(self.base_url, self._scheduled_payload(), format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
report = EvaluationReport.objects.get()
@@ -712,7 +712,7 @@ class TestEvaluationReportApi(APIBaseTest):
def test_update_report(self):
report = self._create_report()
- with freeze_time("2026-01-15T16:37:42Z"):
+ with time_machine.travel("2026-01-15T16:37:42Z", tick=False):
response = self.client.patch(
f"{self.base_url}{report.id}/",
{"frequency": "scheduled", "rrule": "FREQ=WEEKLY;BYDAY=MO"},
diff --git a/products/ai_observability/backend/api/test/test_personal_spend.py b/products/ai_observability/backend/api/test/test_personal_spend.py
index 88a0d97505a1..23d7b25eea78 100644
--- a/products/ai_observability/backend/api/test/test_personal_spend.py
+++ b/products/ai_observability/backend/api/test/test_personal_spend.py
@@ -6,7 +6,7 @@ import json
import time
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -270,7 +270,7 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
# The endpoint derives its window from now, and this test snapshots the SQL, so a live
# clock writes the current microsecond into the snapshot. This test creates no events,
# so pinning the clock ages nothing against ClickHouse retention.
- @freeze_time("2026-01-15T12:00:00Z")
+ @time_machine.travel("2026-01-15T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_empty_result_when_no_events(self) -> None:
response = self.client.get(ENDPOINT_OK)
diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
index c95b46f47d57..5011f045a255 100644
--- a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from posthog.api.services.query import ExecutionMode
@@ -34,7 +34,7 @@ class TestHogQLExtractorFiltersPlaceholder(APIBaseTest, ClickhouseDestroyTablesM
return result.series[0].points[result.series[0].current_index].value
def test_filters_placeholder_with_and_without_saved_filters(self) -> None:
- with freeze_time("2026-06-12T12:00:00Z"):
+ with time_machine.travel("2026-06-12T12:00:00Z", tick=False):
for i in range(3):
_create_event(
team=self.team, event="signup", distinct_id=f"recent_{i}", timestamp="2026-06-11T12:00:00Z"
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index 0757fd413f7c..314eb45318d9 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -2,7 +2,7 @@ from copy import deepcopy
from datetime import UTC, datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest import mock
@@ -1199,7 +1199,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
("monthly", "monthly", "2026-04-01T09:35:00+00:00"),
]
)
- @freeze_time("2026-03-18T09:30:00Z")
+ @time_machine.travel("2026-03-18T09:30:00Z", tick=False)
def test_create_alert_with_schedule_start_time(
self, _name: str, calculation_interval: str, expected_next_check_at: str
) -> None:
@@ -1239,7 +1239,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
("monthly", "monthly"),
]
)
- @freeze_time("2026-03-18T09:00:00Z")
+ @time_machine.travel("2026-03-18T09:00:00Z", tick=False)
def test_patch_schedule_start_time_keeps_the_current_next_check(
self, _name: str, calculation_interval: str
) -> None:
@@ -1275,7 +1275,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.json()["schedule_start_time"] == "08:35"
assert datetime.fromisoformat(response.json()["next_check_at"].replace("Z", "+00:00")) == scheduled_check
- @freeze_time("2026-03-18T09:00:00Z")
+ @time_machine.travel("2026-03-18T09:00:00Z", tick=False)
def test_patch_schedule_start_time_with_schedule_restriction_keeps_the_current_next_check(self) -> None:
alert = self.client.post(
f"/api/projects/{self.team.id}/alerts",
@@ -1351,7 +1351,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
"name": "snap next",
"calculation_interval": "hourly",
}
- with freeze_time("2026-04-06T14:00:00Z"):
+ with time_machine.travel("2026-04-06T14:00:00Z", tick=False):
alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request, format="json").json()
AlertConfiguration.objects.filter(pk=alert["id"]).update(
next_check_at=datetime(2026, 4, 6, 15, 30, tzinfo=UTC),
diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
index 2a025f352c42..f9a0aa16d29f 100644
--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
@@ -2,7 +2,7 @@ import time as time_mod
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
from unittest.mock import patch
@@ -2204,7 +2204,7 @@ class TestComputationExecutorExecute(BaseTest):
schedule = TtlSchedule(rules=[], default_ttl_seconds=3600, default_ttl_jitter_seconds=14 * 24 * 60 * 60)
executor = LazyComputationExecutor(ttl_schedule=schedule)
- with freeze_time("2026-01-15T12:00:00Z") as frozen:
+ with time_machine.travel("2026-01-15T12:00:00Z", tick=False) as frozen:
start = datetime(2026, 1, 5, tzinfo=UTC)
end = datetime(2026, 1, 6, tzinfo=UTC)
result = executor.execute(
@@ -2217,7 +2217,7 @@ class TestComputationExecutorExecute(BaseTest):
# This window's deterministic offset is nonzero, so the job outlives the base TTL
assert jittered_ttl > 3600
- frozen.tick(timedelta(seconds=(3600 + jittered_ttl) / 2))
+ frozen.shift(timedelta(seconds=(3600 + jittered_ttl) / 2))
result = executor.execute(
team=self.team, query_info=query_info, start=start, end=end, run_insert=lambda t, j: None
)
diff --git a/products/batch_exports/backend/tests/api/backfills/test_create.py b/products/batch_exports/backend/tests/api/backfills/test_create.py
index 3234675acf25..edde2dc2d073 100644
--- a/products/batch_exports/backend/tests/api/backfills/test_create.py
+++ b/products/batch_exports/backend/tests/api/backfills/test_create.py
@@ -1,7 +1,7 @@
import datetime as dt
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.test import override_settings
@@ -272,7 +272,7 @@ def test_batch_export_backfill_with_end_at_in_the_future(
batch_export_id = batch_export["id"]
- with freeze_time(test_time):
+ with time_machine.travel(test_time, tick=False):
response = backfill_batch_export(
client,
team.pk,
diff --git a/products/batch_exports/backend/tests/api/backfills/test_get.py b/products/batch_exports/backend/tests/api/backfills/test_get.py
index b03f0f2249e7..3e2bd49fa398 100644
--- a/products/batch_exports/backend/tests/api/backfills/test_get.py
+++ b/products/batch_exports/backend/tests/api/backfills/test_get.py
@@ -1,15 +1,10 @@
import datetime as dt
import pytest
-from freezegun import freeze_time
+import time_machine
from django.test.client import Client as HttpClient
-# Pre-import pydantic.v1.types so that pydantic.v1.types.ConstrainedDate is created against the real
-# datetime.date class. Otherwise, when Django lazily resolves URLs inside a freeze_time() block below,
-# pydantic.v1.modules get imported with freezegun's FakeDate in place and pydantic's
-# `class ConstrainedDate(date, metaclass=ConstrainedNumberMeta)` raises a metaclass conflict.
-import pydantic.v1.types # noqa: F401
from rest_framework import status
from products.batch_exports.backend.models.batch_export import BatchExportBackfill, BatchExportRun
@@ -169,7 +164,7 @@ def test_can_get_backfills_for_your_organizations(
# Freeze time so that BatchExportBackfill.total_expected_runs (which uses datetime.now() for RUNNING backfills
# without end_at) yields deterministic results. TEST_TIME is captured at module import, and without this the
# asserted total_runs can drift as other tests in the same shard run before this one.
- with freeze_time(TEST_TIME):
+ with time_machine.travel(TEST_TIME, tick=False):
backfill_data = get_batch_export_backfill_ok(client, team.pk, batch_export.id, backfill.id)
# as long as the created_at and last_updated_at are strings, we don't care about their exact values
diff --git a/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py b/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py
index 1a0b4b2c73e7..ec0f5c53a906 100644
--- a/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py
+++ b/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py
@@ -5,7 +5,7 @@ from uuid import uuid4
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from django.conf import settings
from django.core.management import call_command
@@ -116,8 +116,12 @@ class TestGetBatchExports:
assert get_batch_exports(batch_export_id=str(uuid4())) == []
-@freeze_time("2026-03-15 12:00:00")
class TestFindMissingIntervals:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-03-15 12:00:00", tick=False):
+ yield
+
def test_no_exports_returns_empty(self, team):
assert find_missing_intervals([], *lookback(24)) == []
diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
index d3d341bed98a..6fc20b465157 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py
@@ -6,7 +6,7 @@ import datetime as dt
from urllib.parse import urlsplit
import pytest
-import freezegun
+import time_machine
import unittest.mock
from django.conf import settings
@@ -97,7 +97,7 @@ async def test_get_file_download_for_run(team, data_interval_start, data_interva
assert index_file == id_file == file_downloads[index]
+@time_machine.travel(None, tick=False)
async def test_calculate_expiration_for_file_download(ateam):
"""Test calculating the expiration time given a file download."""
destination = BatchExportDestination(type=BatchExportDestination.Destination.FILE_DOWNLOAD, config={})
diff --git a/products/billing_alerts/backend/test/test_activities.py b/products/billing_alerts/backend/test/test_activities.py
index 7e2e34704018..72130a06d837 100644
--- a/products/billing_alerts/backend/test/test_activities.py
+++ b/products/billing_alerts/backend/test/test_activities.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from decimal import Decimal
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -52,7 +52,7 @@ class TestBillingAlertActivities(BaseTest):
defaults.update(overrides)
return BillingAlertConfiguration.objects.create(**defaults)
- @freeze_time("2026-06-23T12:00:00Z")
+ @time_machine.travel("2026-06-23T12:00:00Z", tick=False)
@patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
def test_fetch_failure_records_alert_failures_and_continues_batch(self, mock_fetch_billing_data) -> None:
failed_alert = self._alert(name="Spend alert")
@@ -143,7 +143,7 @@ class TestBillingAlertActivities(BaseTest):
assert _group_key(first, now) != _group_key(second, now)
- @freeze_time("2026-06-23T12:00:00Z")
+ @time_machine.travel("2026-06-23T12:00:00Z", tick=False)
@patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
def test_retry_skips_alert_already_rescheduled_by_prior_attempt(self, mock_fetch_billing_data) -> None:
alert = self._alert(next_check_at=datetime(2026, 6, 24, 12, tzinfo=UTC))
@@ -152,7 +152,7 @@ class TestBillingAlertActivities(BaseTest):
mock_fetch_billing_data.assert_not_called()
- @freeze_time("2026-06-23T12:00:00Z")
+ @time_machine.travel("2026-06-23T12:00:00Z", tick=False)
@patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
def test_completed_claim_advances_a_still_due_alert(self, mock_fetch_billing_data) -> None:
now = datetime(2026, 6, 23, 12, tzinfo=UTC)
@@ -172,7 +172,7 @@ class TestBillingAlertActivities(BaseTest):
assert alert.pending_evaluation_date is None
mock_fetch_billing_data.assert_called_once()
- @freeze_time("2026-06-23T12:00:00Z")
+ @time_machine.travel("2026-06-23T12:00:00Z", tick=False)
@patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
@patch("products.billing_alerts.backend.temporal.activities.commit_pending_billing_alert_dispatches")
@patch("products.billing_alerts.backend.temporal.activities.prepare_billing_alert_dispatch")
@@ -193,7 +193,7 @@ class TestBillingAlertActivities(BaseTest):
assert mock_prepare_dispatch.call_count == 1
mock_commit_dispatch.assert_not_called()
- @freeze_time("2026-06-23T12:00:00Z")
+ @time_machine.travel("2026-06-23T12:00:00Z", tick=False)
@patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
def test_transient_fetch_failure_retries_before_recording_an_event(self, mock_fetch_billing_data) -> None:
alert = self._alert()
@@ -207,7 +207,7 @@ class TestBillingAlertActivities(BaseTest):
assert BillingAlertEvent.objects.filter(claim__alert=alert).exists() is False
- @freeze_time("2026-06-23T12:00:00Z")
+ @time_machine.travel("2026-06-23T12:00:00Z", tick=False)
@patch("products.billing_alerts.backend.temporal.activities.fetch_billing_data")
def test_transient_fetch_failure_commits_groups_already_prepared(self, mock_fetch_billing_data) -> None:
first_alert = self._alert(name="Spend alert")
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index dd3a499a3ddf..50f0004841d2 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -1,7 +1,7 @@
import json
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from unittest.mock import ANY, MagicMock, patch
@@ -939,7 +939,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
}
}
# Fernet encryption is deterministic, but has a temporal component and utilizes os.urandom() for the IV
- with freeze_time("2024-01-01T00:01:00Z"):
+ with time_machine.travel("2024-01-01T00:01:00Z", tick=False):
with patch("os.urandom", return_value=b"\x00" * 16):
res = self.client.post(f"/api/projects/{self.team.id}/hog_functions/", data={**payload})
assert res.status_code == status.HTTP_201_CREATED, res.json()
@@ -2157,7 +2157,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def test_list_hog_functions_ordered_by_execution_order_and_updated_at(self):
# Create functions with different execution orders and update times
# First create all functions with the same timestamp
- with freeze_time("2024-01-01T00:00:00Z"):
+ with time_machine.travel("2024-01-01T00:00:00Z", tick=False):
self.client.post(
f"/api/projects/{self.team.id}/hog_functions/",
data={
diff --git a/products/cdp/backend/api/test/test_plugin.py b/products/cdp/backend/api/test/test_plugin.py
index 1ee2c2fa9a79..76daed665cc5 100644
--- a/products/cdp/backend/api/test/test_plugin.py
+++ b/products/cdp/backend/api/test/test_plugin.py
@@ -6,7 +6,7 @@ from typing import Any, Optional, cast
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
from unittest.mock import patch
@@ -86,7 +86,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
assert response.status_code == expected_status, response.json()
return response.json()
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_create_plugin_auth(self, mock_get, mock_reload):
repo_url = "https://github.com/PostHog/helloworldplugin"
@@ -368,7 +368,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
self.assertNotEqual(plugin.updated_at, fake_date)
- with freeze_time(fake_date.isoformat()):
+ with time_machine.travel(fake_date.isoformat(), tick=False):
api_url = f"/api/organizations/@current/plugins/{response.json()['id']}/upgrade"
response = self.client.post(api_url, {"url": repo_url})
self.assertEqual(response.status_code, 200)
@@ -387,12 +387,12 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
self.assertEqual(mock_sync_from_plugin_archive.call_count, 2) # Not extracted on auth failure
def test_delete_plugin_auth(self, mock_get, mock_reload):
- with freeze_time("2021-08-25T22:09:14.252Z"):
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False):
repo_url = "https://github.com/PostHog/helloworldplugin"
response = self.client.post("/api/organizations/@current/plugins/", {"url": repo_url})
self.assertEqual(response.status_code, 201)
- with freeze_time("2021-08-25T22:09:14.253Z"):
+ with time_machine.travel("2021-08-25T22:09:14.253Z", tick=False):
plugin_id = response.json()["id"]
api_url = "/api/organizations/@current/plugins/{}".format(response.json()["id"])
@@ -913,7 +913,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
)
fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
- with freeze_time(fake_date.isoformat()):
+ with time_machine.travel(fake_date.isoformat(), tick=False):
response = self.client.post(
f"/api/organizations/{my_org.id}/plugins/",
{"url": "https://github.com/PostHog/helloworldplugin"},
@@ -1056,7 +1056,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"count": 0, "next": None, "previous": None, "results": []})
- @freeze_time("2021-12-05T13:23:00Z")
+ @time_machine.travel("2021-12-05T13:23:00Z", tick=False)
def test_plugin_config_list(self, mock_get, mock_reload):
plugin = Plugin.objects.create(organization=self.organization)
plugin_config1 = PluginConfig.objects.create(plugin=plugin, team=self.team, enabled=True, order=1)
@@ -1195,7 +1195,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
self.assertNotEqual(plugin.latest_tag_checked_at, fake_date)
- with freeze_time(fake_date.isoformat()):
+ with time_machine.travel(fake_date.isoformat(), tick=False):
response = self.client.get(f"/api/organizations/@current/plugins/{plugin_id}/check_for_updates")
plugin.refresh_from_db()
diff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
index 4e99d1a78792..b35567a28c44 100644
--- a/products/conversations/backend/api/tests/test_customer_email_ingestion.py
+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
@@ -3,7 +3,7 @@ from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -242,7 +242,7 @@ class TestCustomerEmailIngestion(BaseTest):
assert message.comment.content == "Can you help?"
def test_pending_channel_rejects_expired_signed_challenge(self) -> None:
- with freeze_time("2026-01-01 00:00:00"):
+ with time_machine.travel("2026-01-01 00:00:00", tick=False):
setup = self._start_google_setup(expires_at=timezone.now() + timedelta(hours=48))
challenge = create_forwarding_challenge(
team_id=self.team.id,
@@ -250,7 +250,7 @@ class TestCustomerEmailIngestion(BaseTest):
setup_id=setup.id,
)
- with freeze_time("2026-01-02 00:00:01"):
+ with time_machine.travel("2026-01-02 00:00:01", tick=False):
response = self._post_email(
message_id="<[email protected]>",
**{FORWARDING_CHALLENGE_HEADER: challenge.token},
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.py
index 7e6763388c32..a9ae01c68dcd 100644
--- a/products/conversations/backend/api/tests/test_events.py
+++ b/products/conversations/backend/api/tests/test_events.py
@@ -1,7 +1,7 @@
import uuid
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import Mock, patch
@@ -210,7 +210,7 @@ class TestConversationEvents(BaseTest):
def test_capture_message_sent_stamps_sla_state(self, _name, sla_due_at, expected, mock_capture):
self.ticket.sla_due_at = datetime.fromisoformat(sla_due_at) if sla_due_at else None
- with freeze_time("2026-01-01T12:00:00Z"):
+ with time_machine.travel("2026-01-01T12:00:00Z", tick=False):
capture_message_sent(self.ticket, "msg-123", "Hello customer", author=self.user)
properties = mock_capture.call_args.kwargs["properties"]
diff --git a/products/conversations/backend/tests/test_inbound_event_processing.py b/products/conversations/backend/tests/test_inbound_event_processing.py
index 02e318543bd3..a2b3680cc6ee 100644
--- a/products/conversations/backend/tests/test_inbound_event_processing.py
+++ b/products/conversations/backend/tests/test_inbound_event_processing.py
@@ -4,7 +4,7 @@ from datetime import timedelta
from typing import Any
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -411,7 +411,7 @@ class TestInboundEventProcessing(BaseTest):
@patch("products.conversations.backend.tasks.slack.wake_inbound_event")
def test_sweeper_measures_expired_lease_age_from_lease_expiry(self, mock_wake: MagicMock) -> None:
- with freeze_time("2026-09-10 12:00:00"):
+ with time_machine.travel("2026-09-10 12:00:00", tick=False):
self._create_pending(source_id="Ev-old-ready")
ConversationInboundEvent.objects.unscoped().filter(source_id="Ev-old-ready").update(
status=ConversationInboundEvent.Status.PROCESSING,
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
index acb4a450318c..1a6952144c28 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import patch
@@ -71,7 +71,7 @@ from products.customer_analytics.backend.test.factories import create_account, c
from products.notebooks.backend.models import Notebook, ResourceNotebook
-@freeze_time("2026-01-15T12:00:00Z")
+@time_machine.travel("2026-01-15T12:00:00Z", tick=False)
class TestAccountsTableQueryRunner(BaseTest):
def _run(self, query: AccountsTableQuery) -> AccountsTableQueryResponse:
return AccountsTableQueryRunner(query=query, team=self.team, user=self.user).calculate()
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_usage_metrics_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_usage_metrics_query_runner.py
index fcbe78d0ba52..6439898a0d05 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_usage_metrics_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_usage_metrics_query_runner.py
@@ -3,7 +3,7 @@ from pathlib import Path
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -132,7 +132,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ValueError, match="UsageMetricsQuery must have either group_key or person_id"):
UsageMetricsQueryRunner(team=self.team, query=query)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_person_metric(self):
metric = GroupUsageMetric.objects.create(
@@ -198,7 +198,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[1]["id"], str(another_metric.id))
self.assertEqual(results[1]["value"], 5.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_complex_event_filter(self):
metric = GroupUsageMetric.objects.create(
@@ -239,7 +239,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["id"], str(metric.id))
self.assertEqual(results[0]["value"], 3.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_metric_interval(self):
metric = GroupUsageMetric.objects.create(
@@ -255,7 +255,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time(timezone.now() - timedelta(days=8)):
+ with time_machine.travel(timezone.now() - timedelta(days=8), tick=False):
# These should not count in `value`, but should count in `previous`
for _ in range(3):
_create_event(
@@ -265,7 +265,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
distinct_id=self.person_distinct_id,
)
- with freeze_time(timezone.now() - timedelta(days=7)):
+ with time_machine.travel(timezone.now() - timedelta(days=7), tick=False):
# These should count in `value` only, as date_from check is gte and `previous` check is lt
for _ in range(2):
_create_event(
@@ -275,7 +275,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
distinct_id=self.person_distinct_id,
)
- with freeze_time(timezone.now()):
+ with time_machine.travel(timezone.now(), tick=False):
# These should count, as date_to check is lte
for _ in range(2):
_create_event(
@@ -296,7 +296,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["previous"], 3.0)
self.assertEqual(results[0]["change_from_previous_pct"], 33.33333333333333)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_handles_failed_metric_gracefully(self):
GroupUsageMetric.objects.create(
@@ -325,7 +325,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
results = query_result["results"]
self.assertEqual(len(results), 0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_no_metrics(self):
for _ in range(3):
@@ -342,7 +342,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
results = query_result["results"]
self.assertEqual(len(results), 0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_group_metric(self):
group_key = "test_group"
@@ -407,7 +407,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[1]["id"], str(another_metric.id))
self.assertEqual(results[1]["value"], 5.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_sum_math_aggregation(self):
GroupUsageMetric.objects.create(
@@ -452,7 +452,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["name"], "Revenue")
self.assertEqual(results[0]["value"], 350.5)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_sum_math_with_missing_property_returns_zero(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -481,7 +481,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["value"], 0.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_sum_math_with_null_math_property_returns_zero(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -509,7 +509,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
results = query_result["results"]
self.assertEqual(len(results), 0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_sum_math_previous_period_comparison(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -524,7 +524,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
math_property="amount",
)
- with freeze_time(timezone.now() - timedelta(days=8)):
+ with time_machine.travel(timezone.now() - timedelta(days=8), tick=False):
_create_event(
event="purchase",
team=self.team,
@@ -533,7 +533,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
properties={"amount": 200},
)
- with freeze_time(timezone.now()):
+ with time_machine.travel(timezone.now(), tick=False):
_create_event(
event="purchase",
team=self.team,
@@ -552,7 +552,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["previous"], 200.0)
self.assertEqual(results[0]["change_from_previous_pct"], 50.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_count_and_sum_metrics_together(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -600,7 +600,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results_by_name["Revenue"]["value"], 300.0)
self.assertEqual(results_by_name["Purchases"]["value"], 2.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_cache_invalidates_when_metric_created(self):
_create_event(
event="metric_event",
@@ -642,7 +642,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response2.results[0].name, "Test metric")
self.assertEqual(response2.results[0].value, 1.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_cache_invalidates_when_metric_deleted(self):
_create_event(
event="metric_event",
@@ -684,7 +684,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(response2.is_cached)
self.assertEqual(len(response2.results), 0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_usage_metrics_fetched_once_per_runner(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -708,7 +708,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(filter_spy.call_count, 1)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_datetime_now_shared_between_query_build_and_post_process(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -720,18 +720,27 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
display=GroupUsageMetric.Display.NUMBER,
filters={"events": [{"id": "metric_event", "type": "events", "order": 0}]},
)
+ # Inside the 7-day window measured from 12:11, but on the day that drops out of the
+ # window if `now` is read a second time later in the same run.
_create_event(
event="metric_event",
team=self.team,
person_id=str(self.person.uuid),
distinct_id=self.person_distinct_id,
+ timestamp=datetime(2025, 10, 2, 13, 0, 0, tzinfo=ZoneInfo("UTC")),
)
flush_persons_and_events()
fake_now = datetime(2025, 10, 9, 12, 11, 0, tzinfo=ZoneInfo("UTC"))
call_log: list[datetime] = []
- class TimeDriftingDatetime(datetime):
+ class DriftingDatetimeMeta(type):
+ # The runner asks isinstance(row_value, datetime) to normalize ClickHouse rows.
+ # This stand-in replaces that name, so it has to answer for real datetimes too.
+ def __instancecheck__(cls, obj: object) -> bool:
+ return isinstance(obj, datetime)
+
+ class TimeDriftingDatetime(datetime, metaclass=DriftingDatetimeMeta):
@classmethod
def now(cls, tz=None):
# Each call advances by 12 hours to simulate worst-case drift across the day boundary
@@ -749,12 +758,11 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
query_result = runner.calculate().model_dump()
- self.assertEqual(len(call_log), 1)
results = query_result["results"]
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["value"], 1.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_sparkline_returns_timeseries(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -766,14 +774,14 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
display=GroupUsageMetric.Display.SPARKLINE,
filters={"events": [{"id": "metric_event", "type": "events", "order": 0}]},
)
- with freeze_time(timezone.now() - timedelta(days=2)):
+ with time_machine.travel(timezone.now() - timedelta(days=2), tick=False):
_create_event(
event="metric_event",
team=self.team,
person_id=str(self.person.uuid),
distinct_id=self.person_distinct_id,
)
- with freeze_time(timezone.now()):
+ with time_machine.travel(timezone.now(), tick=False):
for _ in range(3):
_create_event(
event="metric_event",
@@ -795,7 +803,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(result["timeseries"]), len(result["timeseries_labels"]))
self.assertEqual(sum(result["timeseries"]), 4.0)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_number_metric_no_timeseries(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -822,7 +830,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIsNone(results[0]["timeseries"])
self.assertIsNone(results[0]["timeseries_labels"])
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_sparkline_gap_filling(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -834,14 +842,14 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
display=GroupUsageMetric.Display.SPARKLINE,
filters={"events": [{"id": "metric_event", "type": "events", "order": 0}]},
)
- with freeze_time(timezone.now() - timedelta(days=5)):
+ with time_machine.travel(timezone.now() - timedelta(days=5), tick=False):
_create_event(
event="metric_event",
team=self.team,
person_id=str(self.person.uuid),
distinct_id=self.person_distinct_id,
)
- with freeze_time(timezone.now() - timedelta(days=1)):
+ with time_machine.travel(timezone.now() - timedelta(days=1), tick=False):
_create_event(
event="metric_event",
team=self.team,
@@ -860,7 +868,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
zero_count = sum(1 for v in timeseries if v == 0.0)
self.assertEqual(zero_count, len(timeseries) - 2)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_sparkline_sum_aggregation(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -899,7 +907,7 @@ class TestUsageMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIsNotNone(result["timeseries"])
self.assertEqual(sum(result["timeseries"]), 350.5)
- @freeze_time("2025-10-09T12:11:00")
+ @time_machine.travel("2025-10-09T12:11:00", tick=False)
def test_mixed_display_types(self):
GroupUsageMetric.objects.create(
id=self.test_metric_id,
@@ -1018,7 +1026,7 @@ class TestUsageMetricsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest)
math=GroupUsageMetric.Math.COUNT,
)
- with freeze_time("2025-10-09T12:11:00"):
+ with time_machine.travel("2025-10-09T12:11:00", tick=False):
results = self._calculate(group_key=self.group_key)["results"]
assert len(results) == 1
@@ -1047,7 +1055,7 @@ class TestUsageMetricsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest)
math_property="amount",
)
- with freeze_time("2025-10-09T12:11:00"):
+ with time_machine.travel("2025-10-09T12:11:00", tick=False):
results = self._calculate(group_key=self.group_key)["results"]
assert len(results) == 1
@@ -1073,7 +1081,7 @@ class TestUsageMetricsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest)
},
)
- with freeze_time("2025-10-09T12:11:00"):
+ with time_machine.travel("2025-10-09T12:11:00", tick=False):
results = self._calculate(group_key="nobody")["results"]
assert len(results) == 1
@@ -1109,7 +1117,7 @@ class TestUsageMetricsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest)
"key_field": "customer_id",
},
)
- with freeze_time("2025-10-09T12:11:00"):
+ with time_machine.travel("2025-10-09T12:11:00", tick=False):
for _ in range(2):
_create_event(
event="metric_event",
@@ -1145,7 +1153,7 @@ class TestUsageMetricsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest)
},
)
- with freeze_time("2025-10-09T12:11:00"):
+ with time_machine.travel("2025-10-09T12:11:00", tick=False):
results = self._calculate(person_id=str(person.uuid))["results"]
assert results == []
diff --git a/products/customer_analytics/backend/test/test_account_track_rules.py b/products/customer_analytics/backend/test/test_account_track_rules.py
index 6b0bb20df74f..f655a960da9f 100644
--- a/products/customer_analytics/backend/test/test_account_track_rules.py
+++ b/products/customer_analytics/backend/test/test_account_track_rules.py
@@ -6,7 +6,7 @@ from types import SimpleNamespace
from uuid import uuid4
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -123,7 +123,7 @@ async def test_workflow_marks_the_run_failed_when_cancelled() -> None:
assert execute_activity.await_args_list[1].args[0] is account_track_rule_fail_run_activity
-@freeze_time("2026-08-20T12:00:00Z")
+@time_machine.travel("2026-08-20T12:00:00Z", tick=False)
@pytest.mark.parametrize(
("enabled_at", "expected_overdue", "expected_age_seconds"),
[
@@ -378,7 +378,7 @@ class AccountTrackRulesTestMixin:
TeamCustomerAnalyticsConfig.objects.filter(team_id=self.team.id).update(account_track_rules=config)
-@freeze_time("2026-08-20T12:00:00Z")
+@time_machine.travel("2026-08-20T12:00:00Z", tick=False)
class TestAccountTrackRuleLogic(AccountTrackRulesTestMixin, BaseTest):
def test_config_defaults_to_a_disabled_empty_version(self) -> None:
config = TeamCustomerAnalyticsConfig.objects.get(team_id=self.team.id).account_track_rules
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 6a1b8b07c54f..86df445dbdfa 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -2,7 +2,7 @@ from datetime import timedelta
from uuid import uuid4
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -1177,9 +1177,9 @@ class TestAccountNotebookViewSet(APIBaseTest):
self.assertEqual(short_ids, {by_title.short_id, by_content.short_id})
def test_list_orders_by_created_at(self):
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
older = self._link_internal_notebook(title="Older", content={})
- with freeze_time("2024-01-02"):
+ with time_machine.travel("2024-01-02", tick=False):
newer = self._link_internal_notebook(title="Newer", content={})
default_order = [n["short_id"] for n in self.client.get(self.endpoint_base).json()["results"]]
@@ -2738,9 +2738,9 @@ class TestAccountNotesViewSet(APIBaseTest):
self.assertEqual(titles, ["Mine"])
def test_list_orders_by_last_modified_desc_and_paginates(self):
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
older = self._link_note(title="Older")
- with freeze_time("2024-01-02"):
+ with time_machine.travel("2024-01-02", tick=False):
newer = self._link_note(title="Newer")
first_page = self.client.get(f"{self.endpoint_base}?limit=1").json()
@@ -3365,7 +3365,7 @@ class TestCalendarSyncViewSet(APIBaseTest):
workflow_kwargs = mock_connect.return_value.start_workflow.call_args.kwargs
self.assertEqual(workflow_kwargs["id"], f"google-calendar-sync-{integration.id}")
- @freeze_time("2026-04-10T12:00:00Z")
+ @time_machine.travel("2026-04-10T12:00:00Z", tick=False)
def test_backfill_starts_both_sources_for_an_inclusive_date_range(self) -> None:
self._become_admin()
integration = self._create_syncable_integration()
@@ -3404,7 +3404,7 @@ class TestCalendarSyncViewSet(APIBaseTest):
("reversed", "2026-04-10", "2026-04-09"),
]
)
- @freeze_time("2026-04-10T12:00:00Z")
+ @time_machine.travel("2026-04-10T12:00:00Z", tick=False)
def test_backfill_rejects_dates_outside_the_allowed_range(self, _name: str, start_date: str, end_date: str) -> None:
self._become_admin()
integration = self._create_syncable_integration()
diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.py
index c00f9a798064..ce0ec1b6cae5 100644
--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py
+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py
@@ -1,6 +1,6 @@
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, PropertyMock, patch
@@ -52,7 +52,7 @@ class TestDashboardWidgets(APIBaseTest):
for patcher in self._widgets_flag_patchers:
patcher.start()
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_can_create_widget_tile(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
@@ -484,7 +484,7 @@ class TestDashboardWidgets(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert Dashboard.objects.filter(team_id=self.team.id, deleted=False).count() == 0
- @freeze_time("2022-04-01 12:45")
+ @time_machine.travel("2022-04-01 12:45", tick=False)
@override_settings(IN_UNIT_TESTING=True)
def test_widget_create_and_update_writes_activity_log(self) -> None:
ActivityLog.objects.filter(team_id=self.team.id, scope="DashboardWidget").delete()
diff --git a/products/dashboards/backend/widgets/test_conversations_recent_tickets.py b/products/dashboards/backend/widgets/test_conversations_recent_tickets.py
index 19cf2c697843..d600bcfb159d 100644
--- a/products/dashboards/backend/widgets/test_conversations_recent_tickets.py
+++ b/products/dashboards/backend/widgets/test_conversations_recent_tickets.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from django.utils import timezone
@@ -14,7 +14,7 @@ from products.dashboards.backend.widget_availability import get_widget_feature_e
from products.dashboards.backend.widget_specs.registry import get_widget_registry_entry, validate_widget_config
-@freeze_time("2026-08-10 12:00:00")
+@time_machine.travel("2026-08-10 12:00:00", tick=False)
class TestConversationsRecentTicketsWidget(BaseTest):
@parameterized.expand(
[
diff --git a/products/data_modeling/backend/test/test_cycle_detection.py b/products/data_modeling/backend/test/test_cycle_detection.py
index 9edb9ea6e8c2..05942406547d 100644
--- a/products/data_modeling/backend/test/test_cycle_detection.py
+++ b/products/data_modeling/backend/test/test_cycle_detection.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -20,7 +20,7 @@ class LinkedListCycleDetectionTest(BaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- with freeze_time("2025-01-01T12:00:00.000Z"):
+ with time_machine.travel("2025-01-01T12:00:00.000Z", tick=False):
cls.ll_dag = DAG.objects.create(team=cls.team, name=LINKED_LIST_DAG_ID)
ll_queries = [
DataWarehouseSavedQuery.objects.create(
@@ -73,7 +73,7 @@ class TreeCycleDetectionTest(BaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- with freeze_time("2025-01-01T12:00:00.000Z"):
+ with time_machine.travel("2025-01-01T12:00:00.000Z", tick=False):
cls.bt_dag = DAG.objects.create(team=cls.team, name=BALANCED_TREE_DAG_ID)
bt_root = [
DataWarehouseSavedQuery.objects.create(
diff --git a/products/data_modeling/backend/test/test_dag_mismatch.py b/products/data_modeling/backend/test/test_dag_mismatch.py
index 1bdaaaf9ac5c..952afae344bc 100644
--- a/products/data_modeling/backend/test/test_dag_mismatch.py
+++ b/products/data_modeling/backend/test/test_dag_mismatch.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -22,7 +22,7 @@ class DagMismatchTest(BaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- with freeze_time("2025-01-01T12:00:00.000Z"):
+ with time_machine.travel("2025-01-01T12:00:00.000Z", tick=False):
cls.dag_a = DAG.objects.create(team=cls.team, name=A_DAG_ID)
cls.dag_b = DAG.objects.create(team=cls.team, name=B_DAG_ID)
a1_query = DataWarehouseSavedQuery.objects.create(
diff --git a/products/data_warehouse/backend/logic/data_load/test/test_source_templates.py b/products/data_warehouse/backend/logic/data_load/test/test_source_templates.py
index 878052292fec..7b07e9319210 100644
--- a/products/data_warehouse/backend/logic/data_load/test/test_source_templates.py
+++ b/products/data_warehouse/backend/logic/data_load/test/test_source_templates.py
@@ -1,5 +1,5 @@
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, _create_person
from parameterized import parameterized
@@ -110,7 +110,7 @@ class TestCustomerRevenueViewPersonsJoin(RevenueAnalyticsTestBase):
database_operations(self.team.pk, self.source.prefix or "")
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select(
f"SELECT id, persons.properties.marker FROM {self.view_name}"
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index 2d202649dac3..588959fe51ad 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -2,7 +2,7 @@ import uuid
from datetime import timedelta
from typing import Any, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest import mock
from unittest.mock import AsyncMock, patch
@@ -2162,9 +2162,9 @@ class TestSavedQuery(APIBaseTest):
)
for i in range(2)
]
- with freeze_time("2026-07-01T00:00:00Z"):
+ with time_machine.travel("2026-07-01T00:00:00Z", tick=False):
mark_node_suspended(nodes[0], engine="clickhouse", reason="first failure", job_id="job-1")
- with freeze_time("2026-07-02T00:00:00Z"):
+ with time_machine.travel("2026-07-02T00:00:00Z", tick=False):
mark_node_suspended(nodes[1], engine="clickhouse", reason="later failure", job_id="job-2")
for node in nodes:
node.save()
diff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
index 244bf595616f..e2a23e3f7f86 100644
--- a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime, timedelta
from typing import cast
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from django.db.models import QuerySet
from django.test import SimpleTestCase, TestCase
@@ -87,7 +87,7 @@ class TestSourceTableReadiness(SimpleTestCase):
assert readiness == "waiting"
-@freeze_time("2026-07-13")
+@time_machine.travel("2026-07-13", tick=False)
class TestDatasetStatus(SimpleTestCase):
def _partition(
self,
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index a903125248ed..7b3dad272a23 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest import TestCase, mock
@@ -1048,7 +1048,7 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2025-01-01 12:00:00")
+ @time_machine.travel("2025-01-01 12:00:00", tick=False)
def test_custom_data_freshness_behavior(
self, name, query, data_freshness_seconds, time_within_freshness_min, time_past_freshness_min
):
@@ -1080,7 +1080,7 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
# Move time forward (still within freshness window)
hours_within = time_within_freshness_min // 60
mins_within = time_within_freshness_min % 60
- with freeze_time(f"2025-01-01 {12 + hours_within:02d}:{mins_within:02d}:00"):
+ with time_machine.travel(f"2025-01-01 {12 + hours_within:02d}:{mins_within:02d}:00", tick=False):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()
@@ -1092,7 +1092,7 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
# Move time forward (past freshness window) - should recalculate
hours_past = time_past_freshness_min // 60
mins_past = time_past_freshness_min % 60
- with freeze_time(f"2025-01-01 {12 + hours_past:02d}:{mins_past:02d}:00"):
+ with time_machine.travel(f"2025-01-01 {12 + hours_past:02d}:{mins_past:02d}:00", tick=False):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()
@@ -1101,7 +1101,7 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
f"Should recalculate after {time_past_freshness_min} minutes",
)
- @freeze_time("2025-01-01 12:00:00")
+ @time_machine.travel("2025-01-01 12:00:00", tick=False)
def test_default_data_freshness(self):
endpoint = create_endpoint_with_version(
name="default_freshness",
@@ -1118,7 +1118,7 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):
cache_key = response_data.get("cache_key")
# Move time forward 5 minutes - should still use cache (default is 24 hours)
- with freeze_time("2025-01-01 12:05:00"):
+ with time_machine.travel("2025-01-01 12:05:00", tick=False):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()
diff --git a/products/endpoints/backend/tests/test_endpoint_logs.py b/products/endpoints/backend/tests/test_endpoint_logs.py
index 287ca9d73534..c264a198bf33 100644
--- a/products/endpoints/backend/tests/test_endpoint_logs.py
+++ b/products/endpoints/backend/tests/test_endpoint_logs.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest import mock
@@ -194,7 +194,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
self.assertIn("Endpoint execution failed", kwargs["message"])
self.assertIn("refresh", kwargs["message"])
- @freeze_time("2026-01-02 12:00:00")
+ @time_machine.travel("2026-01-02 12:00:00", tick=False)
def test_logs_action_returns_endpoint_entries(self):
endpoint = self._create_hogql_endpoint("logs_read", "SELECT 1")
create_log_entry(
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index fa19dd0e714d..06843f14626a 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -2,7 +2,7 @@ from datetime import timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest import mock
@@ -1826,7 +1826,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
"interval": "day",
}
- with freeze_time("2026-04-20T12:00:00Z"):
+ with time_machine.travel("2026-04-20T12:00:00Z", tick=False):
endpoint = create_endpoint_with_version(
name="relative_dates_stay_fresh",
team=self.team,
@@ -1848,7 +1848,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
assert saved_query is not None
self.assertIn("2026-04-20", saved_query.query["query"])
- with freeze_time("2026-04-30T12:00:00Z"):
+ with time_machine.travel("2026-04-30T12:00:00Z", tick=False):
prepare_executable_query(saved_query)
saved_query.refresh_from_db()
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index d94717670d15..0984d39b2225 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -80,8 +80,8 @@ def _ago(days: int) -> str:
def _ago_with_duration(days: int, duration_seconds: int) -> tuple[str, str]:
- # Seed dates relative to real time: HogQL now() runs server-side and ignores
- # freezegun, so window/age assertions must share the clock the query uses.
+ # Seed dates relative to real time: HogQL now() runs server-side and ignores the
+ # frozen clock, so window/age assertions must share the clock the query uses.
started_at = _seed_now() - timedelta(days=days)
updated_at = started_at + timedelta(seconds=duration_seconds)
fmt = "%Y-%m-%d %H:%M:%S"
diff --git a/products/engineering_analytics/backend/tests/test_ci_signals.py b/products/engineering_analytics/backend/tests/test_ci_signals.py
index 61bb2671e983..478d8b7472d5 100644
--- a/products/engineering_analytics/backend/tests/test_ci_signals.py
+++ b/products/engineering_analytics/backend/tests/test_ci_signals.py
@@ -5,7 +5,7 @@ from pathlib import Path
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest import mock
@@ -796,7 +796,7 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):
]
# Both detector calls must read one clock: each keys its source_id on the observation
# week, so two real-clock reads straddling Monday 00:00 UTC would fail the equality below.
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
findings = detect_broken_default_branch(self._curated_over_runs(rows, pr_rows=prs), min_runs=2)
assert {f.extra["workflow_name"] for f in findings} == {"red-ci"}
assert findings[0].source_type == SOURCE_TYPE_BROKEN_DEFAULT_BRANCH
diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.py
index 1a70052638bd..0b9bfcfbfca3 100644
--- a/products/engineering_analytics/backend/tests/test_quarantine.py
+++ b/products/engineering_analytics/backend/tests/test_quarantine.py
@@ -5,13 +5,12 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest
from unittest import TestCase, mock
from django.core.cache import cache
from django.test import SimpleTestCase, override_settings
-from django.urls import resolve
import requests
from parameterized import parameterized
@@ -234,7 +233,7 @@ class TestQuarantineBuild(BaseTest):
super().setUp()
cache.clear()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_fetches_and_parses_remote_file(self) -> None:
with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))) as get:
result = build_quarantine(team=self.team, repo="PostHog/posthog")
@@ -249,7 +248,7 @@ class TestQuarantineBuild(BaseTest):
"https://raw.githubusercontent.com/PostHog/posthog/HEAD/.test_quarantine.json", timeout=3, stream=True
)
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_404_means_unavailable_without_errors(self) -> None:
with mock.patch(_REQUESTS_GET, return_value=_response(404)):
result = build_quarantine(team=self.team, repo="PostHog/posthog")
@@ -265,7 +264,7 @@ class TestQuarantineBuild(BaseTest):
("server_error", 500),
]
)
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_fetch_failure_reported_as_single_parse_error(self, _name: str, failure: Exception | int) -> None:
kwargs: dict[str, Any] = (
{"side_effect": failure} if isinstance(failure, Exception) else {"return_value": _response(failure)}
@@ -277,7 +276,7 @@ class TestQuarantineBuild(BaseTest):
assert len(result.parse_errors) == 1 and "could not fetch" in result.parse_errors[0]
@parameterized.expand(["PostHog", "Post Hog/repo", "PostHog/po$thog", "-bad/repo", "a/b/c", "PostHog/"])
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_invalid_repo_rejected_before_fetch(self, repo: str) -> None:
with mock.patch(_REQUESTS_GET) as get:
result = build_quarantine(team=self.team, repo=repo)
@@ -286,7 +285,7 @@ class TestQuarantineBuild(BaseTest):
assert len(result.parse_errors) == 1 and "invalid repo" in result.parse_errors[0]
get.assert_not_called()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_caches_fetched_text(self) -> None:
with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))) as get:
build_quarantine(team=self.team, repo="PostHog/posthog")
@@ -295,7 +294,7 @@ class TestQuarantineBuild(BaseTest):
assert get.call_count == 1
assert result.available is True and len(result.entries) == 1
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_oversized_streamed_body_rejected_and_not_cached(self) -> None:
# No Content-Length header: the cap must hold on the streamed bytes, and a
# hostile oversize response must not poison the cache for the next caller.
@@ -308,7 +307,7 @@ class TestQuarantineBuild(BaseTest):
assert second.available is False
assert get.call_count == 2
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_oversized_content_length_rejected_before_reading_body(self) -> None:
response = _response(200, _text(_entry()), headers={"Content-Length": str(10 * 1024 * 1024)})
with mock.patch(_REQUESTS_GET, return_value=response):
@@ -317,7 +316,7 @@ class TestQuarantineBuild(BaseTest):
assert result.available is False and "exceeds" in result.parse_errors[0]
response.iter_content.assert_not_called()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_resolves_most_active_repo_from_workflow_runs(self) -> None:
source = _curated_source([("PostHog", "posthog.com")])
with (
@@ -329,7 +328,7 @@ class TestQuarantineBuild(BaseTest):
assert result.repo == contracts.RepoRef(provider="github", owner="PostHog", name="posthog.com")
assert source.run.call_args.kwargs["query_type"] == "engineering_analytics.quarantine_repo"
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_no_recent_runs_means_unavailable(self) -> None:
with (
mock.patch(_FOR_TEAM, return_value=_curated_source([])),
@@ -341,7 +340,7 @@ class TestQuarantineBuild(BaseTest):
assert len(result.parse_errors) == 1 and "could not determine a repository" in result.parse_errors[0]
get.assert_not_called()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_no_connected_source_is_fail_open(self) -> None:
with (
mock.patch(_FOR_TEAM, side_effect=contracts.GitHubSourceNotConnectedError("no GitHub source connected")),
@@ -353,7 +352,7 @@ class TestQuarantineBuild(BaseTest):
assert "pass ?repo=owner/name" in result.parse_errors[0]
get.assert_not_called()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_debug_reads_local_checkout(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / QUARANTINE_FILENAME).write_text(_text(_entry()))
@@ -370,14 +369,11 @@ class TestQuarantineAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
cache.clear()
- # Warm the lazy API router before any frozen clock: the process's first resolution builds
- # the view classes, and building them under freezegun raises a metaclass conflict.
- resolve(self._url())
def _url(self) -> str:
return f"/api/projects/{self.team.id}/engineering_analytics/quarantine/"
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_quarantine_serializes(self) -> None:
with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))):
response = self.client.get(self._url(), {"repo": "PostHog/posthog"})
@@ -537,7 +533,7 @@ class TestQuarantineRequest(BaseTest):
integration_cls.objects.filter.return_value.first.return_value = object() if has_integration else None
return github
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_quarantine_opens_issue_then_pr_and_writes_canonical_entry(self) -> None:
github = self._install(_github_mock())
result = request_quarantine(team=self.team, request=_request())
@@ -566,14 +562,14 @@ class TestQuarantineRequest(BaseTest):
("jest_runner", {"runner": contracts.QuarantineRunner.JEST}, "runner", "jest"),
]
)
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_request_field_is_persisted(self, _name: str, overrides: dict[str, Any], key: str, expected: str) -> None:
github = self._install(_github_mock())
request_quarantine(team=self.team, request=_request(**overrides))
entry = json.loads(github.update_file.call_args.args[2])["entries"][0]
assert entry[key] == expected
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_extend_reuses_existing_issue_and_files_no_new_one(self) -> None:
existing = _text(_entry(expires="2026-06-15", issue="https://github.com/PostHog/posthog/issues/7"))
github = self._install(_github_mock(get_file_contents={"content": existing, "sha": "s"}))
@@ -592,7 +588,7 @@ class TestQuarantineRequest(BaseTest):
assert entry["expires"] == "2026-06-25"
assert entry["issue"] == "https://github.com/PostHog/posthog/issues/7"
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_remove_drops_the_entry_without_an_issue(self) -> None:
github = self._install(_github_mock(get_file_contents={"content": _text(_entry()), "sha": "s"}))
result = request_quarantine(
@@ -603,7 +599,7 @@ class TestQuarantineRequest(BaseTest):
assert result.issue_url == "" and result.branch.startswith("unquarantine/")
assert json.loads(github.update_file.call_args.args[2])["entries"] == []
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_remove_of_absent_entry_is_a_clear_error(self) -> None:
github = self._install(_github_mock(get_file_contents={"content": _text(), "sha": "s"}))
with self.assertRaises(contracts.QuarantineWriteError):
@@ -613,19 +609,19 @@ class TestQuarantineRequest(BaseTest):
)
github.create_branch.assert_not_called()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_no_github_integration_is_a_clear_error(self) -> None:
self._install(_github_mock(), has_integration=False)
with self.assertRaises(contracts.QuarantineWriteError):
request_quarantine(team=self.team, request=_request())
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_app_installed_on_wrong_org_is_rejected(self) -> None:
self._install(_github_mock(organization="SomeoneElse"))
with self.assertRaises(contracts.QuarantineWriteError):
request_quarantine(team=self.team, request=_request())
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_explicit_repo_outside_the_team_is_rejected_before_any_write(self) -> None:
# A client-supplied repo the team hasn't connected as a GitHub source must not get the
# App's write token, even when it sits in the install's org.
@@ -641,7 +637,7 @@ class TestQuarantineRequest(BaseTest):
("api_failure", Exception("Failed to get default branch: HTTP 404")),
]
)
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_github_failure_becomes_a_user_safe_error_not_a_500(self, _name: str, failure: Exception) -> None:
# get_default_branch raises plain ValueError/Exception, not QuarantineWriteError; without
# translation those escape as a 500 instead of the user-safe 400 the rest of the path gives.
@@ -651,7 +647,7 @@ class TestQuarantineRequest(BaseTest):
request_quarantine(team=self.team, request=_request())
github.create_branch.assert_not_called()
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_malformed_existing_file_aborts_without_writing(self) -> None:
github = self._install(_github_mock(get_file_contents={"content": "{ not json", "sha": "s"}))
with self.assertRaises(contracts.QuarantineWriteError):
@@ -664,14 +660,14 @@ class TestQuarantineRequest(BaseTest):
("too_far", date(2026, 8, 1)),
]
)
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_expiry_bounds_are_enforced(self, _name: str, expires: date) -> None:
self._install(_github_mock())
with self.assertRaises(contracts.QuarantineWriteError):
request_quarantine(team=self.team, request=_request(expires=expires))
@parameterized.expand([("reason", {"reason": ""}), ("owner", {"owner": ""})])
- @freeze_time("2026-06-12")
+ @time_machine.travel("2026-06-12", tick=False)
def test_quarantine_requires_reason_and_owner(self, _name: str, overrides: dict[str, Any]) -> None:
self._install(_github_mock())
with self.assertRaises(contracts.QuarantineWriteError):
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py
index 1fcbb82ac6e7..3a80a3b26cfb 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_breakdowns_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -52,7 +52,7 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):
properties={**base_properties, **properties},
)
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_breakdown_with_limit(self):
self.create_issue(self.issue_id, self.fingerprint)
@@ -89,7 +89,7 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert browser_data.values[2].value == "C"
assert browser_data.values[2].count == 6
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
def test_breakdown_with_special_character_property_name(self):
self.create_issue(self.issue_id, self.fingerprint)
self.create_exception_event("user_1", {"completion%": "50%"})
@@ -124,7 +124,7 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):
),
)
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_multiple_breakdown_properties(self):
self.create_issue(self.issue_id, self.fingerprint)
@@ -167,7 +167,7 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):
os_data.values, key=lambda x: x.value
)
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
def test_breakdown_respects_property_filters(self) -> None:
self.create_issue(self.issue_id, self.fingerprint)
@@ -210,7 +210,7 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results["$os"].total_count == 5
assert response.results["$os"].values == [BreakdownValue(value="Windows", count=5)]
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_breakdown_with_null_values(self):
self.create_issue(self.issue_id, self.fingerprint)
@@ -245,13 +245,13 @@ class TestErrorTrackingBreakdownsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert browser_data.values[1].value == "$$_posthog_breakdown_null_$$"
assert browser_data.values[1].count == 3
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_breakdown_respects_date_range(self):
self.create_issue(self.issue_id, self.fingerprint)
# outside range
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
for _ in range(10):
self.create_exception_event("user_old", {"$browser": "OldBrowser"})
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_issue_correlation_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_issue_correlation_query_runner.py
index 5ba71dd71e03..332412c66405 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_issue_correlation_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_issue_correlation_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from posthog.schema import ErrorTrackingIssueCorrelationQuery
@@ -24,7 +24,7 @@ class TestErrorTrackingIssueCorrelationQueryRunner(ClickhouseTestMixin, APIBaseT
.model_dump()
)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_column_names(self):
columns = self._calculate()["columns"]
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
index e879d7574bba..79661d367177 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
ClickhouseTestMixin,
NonAtomicBaseTestKeepIdentities,
@@ -117,7 +117,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
person_id=None,
):
if timestamp:
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
self.create_issue(issue_id, fingerprint, name=issue_name)
else:
self.create_issue(issue_id, fingerprint, name=issue_name)
@@ -173,7 +173,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
def setUp(self):
super().setUp()
- with freeze_time("2020-01-10 12:11:00"):
+ with time_machine.travel("2020-01-10 12:11:00", tick=False):
_create_person(
team=self.team,
distinct_ids=[self.distinct_id_one],
@@ -346,12 +346,12 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
),
]
)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_column_names(self, _name, kwargs, expected_columns):
columns = self._calculate(**kwargs)["columns"]
self.assertEqual(columns, expected_columns)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_date_range_resolution(self):
date_from = ErrorTrackingQueryRunner.parse_relative_date_from("-1d", self.team.timezone_info)
date_to = ErrorTrackingQueryRunner.parse_relative_date_to("+1d")
@@ -377,7 +377,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertFalse(runner.query.withLastEvent)
self.assertTrue(runner.query.withAggregations)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_cache_payload_keeps_latest_issue_state_watermark_after_overlay_expiry(self):
query = ErrorTrackingQuery(
kind="ErrorTrackingQuery",
@@ -394,7 +394,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
mutated_payload = ErrorTrackingQueryRunner(
team=self.team, query=query.model_copy(deep=True)
).get_cache_payload()
- with freeze_time("2022-01-10T12:13:00"):
+ with time_machine.travel("2022-01-10T12:13:00", tick=False):
expired_payload = ErrorTrackingQueryRunner(
team=self.team, query=query.model_copy(deep=True)
).get_cache_payload()
@@ -423,13 +423,13 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(payload["error_tracking_issue_state_watermark"], "unavailable")
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_missing_date_from_defaults_to_seven_days(self):
# A missing date_from must default to a bounded 7-day window, not all-time.
date_from = ErrorTrackingQueryRunner.parse_relative_date_from(None, self.team.timezone_info)
self.assertEqual(date_from, datetime(2022, 1, 3, 12, 11, 0, tzinfo=ZoneInfo(key="UTC")))
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_date_to_only_window_ends_at_date_to(self):
# date_to-only queries must anchor the default window to date_to, not to now.
runner = ErrorTrackingQueryRunner(
@@ -443,7 +443,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
)
self.assertEqual(runner.date_from, runner.date_to - timedelta(days=7))
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_issue_grouping(self):
results = self._calculate(issueId=self.issue_id_one, withAggregations=True)["results"]
@@ -452,7 +452,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(results[0]["id"], self.issue_id_one)
self.assertEqual(results[0]["aggregations"]["occurrences"], 2)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_search_query(self):
self.create_events_and_issue(
@@ -499,13 +499,13 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(results[1]["aggregations"]["sessions"], 0)
self.assertEqual(results[1]["aggregations"]["users"], 1)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_empty_search_query(self):
results = self._calculate(searchQuery="probs not found")["results"]
self.assertEqual(len(results), 0)
- @freeze_time("2022-01-10 12:11:00")
+ @time_machine.travel("2022-01-10 12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_search_query_with_multiple_search_items(self):
self.create_events_and_issue(
@@ -541,7 +541,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(results[0]["aggregations"]["sessions"], 0)
self.assertEqual(results[0]["aggregations"]["users"], 1)
- @freeze_time("2022-01-10 12:11:00")
+ @time_machine.travel("2022-01-10 12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_search_person_properties(self):
distinct_id = "[email protected]"
@@ -564,7 +564,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["id"], "684bd8ae-498f-4548-bc05-e621b5b5b9aa")
- @freeze_time("2020-01-10 12:11:00")
+ @time_machine.travel("2020-01-10 12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_only_returns_exception_events(self):
_create_event(
@@ -578,7 +578,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate()["results"]
self.assertEqual(len(results), 3)
- @freeze_time("2022-01-10 12:11:00")
+ @time_machine.travel("2022-01-10 12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_correctly_counts_session_ids(self):
common_properties = {
@@ -611,14 +611,14 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
# only includes valid session ids
self.assertEqual(results[0]["aggregations"]["sessions"], 2)
- @freeze_time("2022-01-10 12:11:00")
+ @time_machine.travel("2022-01-10 12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_correctly_counts_persons(self):
results = self._calculate(issueId=self.issue_id_one, withAggregations=True)["results"]
self.assertEqual(results[0]["id"], self.issue_id_one)
self.assertEqual(results[0]["aggregations"]["users"], 2)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_hogql_filters(self):
results = self._calculate(
@@ -639,7 +639,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
# two errors exist for person with distinct_id_two
self.assertEqual(len(results), 2)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_ordering(self):
results = self._calculate(orderBy="last_seen")["results"]
@@ -648,7 +648,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate(orderBy="first_seen")["results"]
self.assertEqual([r["id"] for r in results], [self.issue_id_one, self.issue_id_two, self.issue_id_three])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_status(self):
resolved_issue = ErrorTrackingIssue.objects.get(id=self.issue_id_one)
resolved_issue.status = ErrorTrackingIssue.Status.RESOLVED
@@ -684,7 +684,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate(status="all")["results"]
self.assertEqual([r["id"] for r in results], [self.issue_id_three, self.issue_id_two, self.issue_id_one])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_expired_postgres_state_uses_clickhouse_state(self):
ErrorTrackingIssue.objects.filter(id=self.issue_id_one).update(
status=ErrorTrackingIssue.Status.RESOLVED,
@@ -698,7 +698,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
resolved_results = self._calculate(status="resolved")["results"]
self.assertNotIn(self.issue_id_one, [result["id"] for result in resolved_results])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_recent_issue_state_is_scoped_to_team(self):
ErrorTrackingIssue.objects.filter(id=self.issue_id_one).update(state_updated_at=now())
other_team = Team.objects.create(organization=self.organization, name="Other team")
@@ -716,7 +716,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
)
self.assertNotIn(other_issue.id, [state.issue_id for state in recent_states])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_recent_issue_state_skips_overlay_when_bound_exceeded(self):
ErrorTrackingIssue.objects.bulk_create(
ErrorTrackingIssue(team=self.team, status=ErrorTrackingIssue.Status.RESOLVED, state_updated_at=now())
@@ -729,7 +729,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
)
self.assertEqual(load_recent_issue_states(self.team.pk), [])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_recent_issue_state_applies_to_more_than_fifty_fingerprints(self):
for index in range(50):
fingerprint = f"additional-fingerprint-{index}"
@@ -756,7 +756,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual([result["id"] for result in results], [self.issue_id_one])
self.assertEqual(results[0]["aggregations"]["occurrences"], 52)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_overrides_aggregation(self):
self.override_fingerprint(self.issue_three_fingerprint, self.issue_id_one)
@@ -791,7 +791,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(response.results, [(issue_id, issue_id)])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_user_assignee(self):
issue_id = "e9ac529f-ac1c-4a96-bd3a-107034368d64"
self.create_events_and_issue(
@@ -806,13 +806,13 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate(assignee={"type": "user", "id": self.user.pk})["results"]
self.assertEqual([x["id"] for x in results], [issue_id])
- with freeze_time("2022-01-10T12:11:05"):
+ with time_machine.travel("2022-01-10T12:11:05", tick=False):
sync_issues_to_clickhouse(issue_ids=[issue_id], team_id=self.team.pk)
ErrorTrackingIssue.objects.filter(id=issue_id).update(state_updated_at=now() - timedelta(seconds=61))
results = self._calculate(assignee={"type": "user", "id": self.user.pk})["results"]
self.assertEqual([x["id"] for x in results], [issue_id])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_role_assignee(self):
issue_id = "e9ac529f-ac1c-4a96-bd3a-107034368d64"
self.create_events_and_issue(
@@ -828,13 +828,13 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate(assignee={"type": "role", "id": str(role.id)})["results"]
self.assertEqual([x["id"] for x in results], [issue_id])
- with freeze_time("2022-01-10T12:11:05"):
+ with time_machine.travel("2022-01-10T12:11:05", tick=False):
sync_issues_to_clickhouse(issue_ids=[issue_id], team_id=self.team.pk)
ErrorTrackingIssue.objects.filter(id=issue_id).update(state_updated_at=now() - timedelta(seconds=61))
results = self._calculate(assignee={"type": "role", "id": str(role.id)})["results"]
self.assertEqual([x["id"] for x in results], [issue_id])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_unassignment_clears_assignee(self):
issue_id = "e9ac529f-ac1c-4a96-bd3a-107034368d64"
self.create_events_and_issue(
@@ -843,10 +843,10 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
flush_persons_and_events()
assignment = ErrorTrackingIssueAssignment.objects.create(issue_id=issue_id, user=self.user, team=self.team)
- with freeze_time("2022-01-10T12:11:01"):
+ with time_machine.travel("2022-01-10T12:11:01", tick=False):
sync_issues_to_clickhouse(issue_ids=[issue_id], team_id=self.team.pk)
- with freeze_time("2022-01-10T12:11:02"):
+ with time_machine.travel("2022-01-10T12:11:02", tick=False):
assignment.delete()
ErrorTrackingIssue.objects.filter(id=issue_id).update(state_updated_at=now())
@@ -855,7 +855,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(len(matching), 1)
self.assertIsNone(matching[0]["assignee"])
- with freeze_time("2022-01-10T12:11:03"):
+ with time_machine.travel("2022-01-10T12:11:03", tick=False):
sync_issues_to_clickhouse(issue_ids=[issue_id], team_id=self.team.pk)
ErrorTrackingIssue.objects.filter(id=issue_id).update(state_updated_at=now() - timedelta(seconds=61))
results = self._calculate()["results"]
@@ -863,7 +863,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(len(matching), 1)
self.assertIsNone(matching[0]["assignee"])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_issue_filters(self):
results = self._calculate(
@@ -883,7 +883,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
)["results"]
self.assertEqual(len(results), 1)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_recent_issue_state_applies_before_issue_filters(self):
ErrorTrackingIssue.objects.filter(id=self.issue_id_one).update(
name="Updated TypeError",
@@ -914,7 +914,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual([result["id"] for result in results], [self.issue_id_one])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_recent_issue_state_keeps_legacy_events_without_fingerprint_state(self):
issue_id = "01936e80-f594-7a2e-8545-7bcb491aa620"
ErrorTrackingIssue.objects.create(
@@ -962,7 +962,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
("is_not_set", PropertyOperator.IS_NOT_SET, True, (issue_id_two, issue_id_three)),
]
)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_issue_severity_filter(self, _name, operator, value, expected_ids):
ErrorTrackingIssue.objects.filter(id=self.issue_id_one).update(severity=ErrorTrackingIssue.Severity.HIGH)
sync_issues_to_clickhouse(issue_ids=[self.issue_id_one], team_id=self.team.pk)
@@ -1000,7 +1000,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
),
]
)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_filter_group_operator(self, _name, operator: FilterLogicalOperator, expected_membership: list[bool]):
results = self._calculate(
filterGroup=PropertyGroupFilter(
@@ -1030,7 +1030,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
}
self.assertEqual(result_ids, expected_ids)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_nested_filter_group_routes_issue_filters_to_issue_fields(self):
filter_group = PropertyGroupFilter(
type=FilterLogicalOperator.AND_,
@@ -1077,7 +1077,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate(filterGroup=filter_group)["results"]
self.assertEqual([r["id"] for r in results], [self.issue_id_one])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
def test_event_filter_group_operator(self):
firefox_issue_id = "01936e80-aa51-746f-aec4-cdf16a5c5333"
chrome_issue_id = "01936e80-aa51-746f-aec4-cdf16a5c5334"
@@ -1123,7 +1123,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
)["results"]
self.assertEqual([result["id"] for result in and_results], [])
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_person_id_filter(self):
person = _create_person(
@@ -1150,7 +1150,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["id"], issue_id)
- @freeze_time("2022-01-10T12:11:00")
+ @time_machine.travel("2022-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_group_key_filter(self):
group_a_id = "org:acme"
@@ -1196,7 +1196,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
results = self._calculate(groupKey="nonexistent", groupTypeIndex=0)["results"]
self.assertEqual(len(results), 0)
- @freeze_time("2020-01-10T12:11:00")
+ @time_machine.travel("2020-01-10T12:11:00", tick=False)
@snapshot_clickhouse_queries
def test_first_seen_filters(self):
cutoff_time = now() - relativedelta(hours=2)
@@ -1237,7 +1237,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(len(results), 1)
self.assertEqual([r["id"] for r in results], [self.issue_id_one])
- @freeze_time("2020-01-12")
+ @time_machine.travel("2020-01-12", tick=False)
@snapshot_clickhouse_queries
def test_volume_aggregation_simple(self):
results = self._calculate(
@@ -1254,7 +1254,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
first_aggregations = results[0]["aggregations"]
self.assertEqual(first_aggregations["volumeRange"], [0, 1, 0])
- @freeze_time("2020-01-12")
+ @time_machine.travel("2020-01-12", tick=False)
def test_volume_aggregation_counts_only(self):
# Regression test: volumeResolution=0 (counts only) used to build
# intDiv(..., 0) bin expressions and fail with an illegal division.
@@ -1269,7 +1269,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
self.assertEqual(aggregations["volume_buckets"], [])
self.assertGreaterEqual(aggregations["occurrences"], 1)
- @freeze_time("2025-05-05")
+ @time_machine.travel("2025-05-05", tick=False)
@snapshot_clickhouse_queries
def test_volume_aggregation_advanced(self):
issue_id = "e9ac529f-ac1c-4a96-bd3a-102334368d64"
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_releases_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_releases_query_runner.py
index 6056cc838c8f..c7fe23112043 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_releases_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_releases_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from parameterized import parameterized
@@ -61,7 +61,7 @@ class TestErrorTrackingReleasesQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
return ErrorTrackingReleasesQueryRunner(team=self.team, query=query).calculate()
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
def test_folds_releases_across_merged_fingerprints(self) -> None:
self.create_issue(ISSUE_ID, ["fp-a", "fp-b"])
self.create_issue(OTHER_ISSUE_ID, ["fp-other"])
@@ -102,7 +102,7 @@ class TestErrorTrackingReleasesQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.namespaces == ["com.example.android", "com.example.ios"]
assert response.total == 7
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
def test_app_namespace_filter_and_occurrence_order(self) -> None:
self.create_issue(ISSUE_ID, ["fp-a"])
for release, count in [
@@ -123,7 +123,7 @@ class TestErrorTrackingReleasesQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.namespaces == ["com.example.android", "com.example.ios"]
assert response.total == 4
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
def test_latest_orders_by_first_seen_then_version(self) -> None:
self.create_issue(ISSUE_ID, ["fp-a"])
for day, release in [
@@ -142,7 +142,7 @@ class TestErrorTrackingReleasesQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Releases that share a first bucket order by version number. Unversioned releases sort last.
assert [r.version for r in response.results] == ["2.8.0", "3a1b2c", "3.0.0", "2.9.0", None]
- @freeze_time("2024-01-10T12:00:00Z")
+ @time_machine.travel("2024-01-10T12:00:00Z", tick=False)
def test_counts_an_event_at_the_inclusive_range_end(self) -> None:
self.create_issue(ISSUE_ID, ["fp-a"])
self.create_exception("fp-a", "2024-01-08T00:00:00Z", ("com.example.ios", "3.0.0", "1600"))
diff --git a/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup.py b/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup.py
index 265e5eceb0b8..4f92acb66983 100644
--- a/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup.py
+++ b/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup.py
@@ -2,7 +2,7 @@ import uuid
from datetime import timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -85,7 +85,7 @@ async def _run_workflow_with_mock_activity(
class TestSpikeEventCleanupWorkflow:
- @freeze_time("2026-01-31T00:00:00Z")
+ @time_machine.travel("2026-01-31T00:00:00Z", tick=False)
def test_parse_defaults_match_dagster_config(self) -> None:
assert ErrorTrackingSpikeEventCleanupWorkflow.parse_inputs([]) == SpikeEventCleanupInputs(days_old=30)
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py
index 6f4a1fa37c6e..494597972725 100644
--- a/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py
@@ -3,7 +3,7 @@ from collections.abc import Callable
from datetime import timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, call, patch
@@ -320,7 +320,7 @@ async def _run_workflow_with_mock_activity(
class TestSymbolSetCleanupWorkflow:
- @freeze_time("2026-01-31T00:00:00Z")
+ @time_machine.travel("2026-01-31T00:00:00Z", tick=False)
def test_parse_defaults_match_dagster_config(self) -> None:
assert ErrorTrackingSymbolSetCleanupWorkflow.parse_inputs([]) == SymbolSetCleanupInputs(
days_old=30,
diff --git a/products/error_tracking/backend/test/test_error_tracking.py b/products/error_tracking/backend/test/test_error_tracking.py
index 0bcb3e2e6a77..f4b69b2785f5 100644
--- a/products/error_tracking/backend/test/test_error_tracking.py
+++ b/products/error_tracking/backend/test/test_error_tracking.py
@@ -4,7 +4,7 @@ from threading import Barrier
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, NonAtomicBaseTest
from unittest.mock import patch
@@ -67,7 +67,7 @@ class TestErrorTracking(ErrorTrackingIssueTestMixin, BaseTest):
ErrorTrackingIssue.objects.filter(id=source.id).update(state_updated_at=source_stamp)
assert latest_issue_state_watermark(self.team.id) == source_stamp
- with freeze_time("2022-01-10T12:05:00"):
+ with time_machine.travel("2022-01-10T12:05:00", tick=False):
assert target.merge(issue_ids=[source.id])[0] == ErrorTrackingIssueMergeResult.MERGED
target.refresh_from_db()
@@ -336,7 +336,7 @@ class TestErrorTracking(ErrorTrackingIssueTestMixin, BaseTest):
assert assignment is not None
assert assignment.user_id == users[expected_key].id
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
def test_error_tracking_issue_first_seen_earliest_fingerprint(self):
issue = self.create_issue(["fingerprint_one"])
@@ -354,11 +354,11 @@ class TestErrorTracking(ErrorTrackingIssueTestMixin, BaseTest):
def test_list_issues_created_since_filters_and_orders(self):
from products.error_tracking.backend.facade import api
- with freeze_time("2020-01-01T00:00:00Z"):
+ with time_machine.travel("2020-01-01T00:00:00Z", tick=False):
ErrorTrackingIssue.objects.create(team=self.team, name="old")
- with freeze_time("2026-01-02T00:00:00Z"):
+ with time_machine.travel("2026-01-02T00:00:00Z", tick=False):
recent_a = ErrorTrackingIssue.objects.create(team=self.team, name="a")
- with freeze_time("2026-01-03T00:00:00Z"):
+ with time_machine.travel("2026-01-03T00:00:00Z", tick=False):
recent_b = ErrorTrackingIssue.objects.create(team=self.team, name="b")
previews = api.list_issues_created_since(team_id=self.team.id, since=datetime(2026, 1, 1, tzinfo=UTC), limit=10)
@@ -369,7 +369,7 @@ class TestErrorTracking(ErrorTrackingIssueTestMixin, BaseTest):
def test_list_issues_created_since_respects_limit(self):
from products.error_tracking.backend.facade import api
- with freeze_time("2026-01-02T00:00:00Z"):
+ with time_machine.travel("2026-01-02T00:00:00Z", tick=False):
for index in range(3):
ErrorTrackingIssue.objects.create(team=self.team, name=f"issue_{index}")
@@ -379,9 +379,9 @@ class TestErrorTracking(ErrorTrackingIssueTestMixin, BaseTest):
def test_list_first_fingerprints_returns_earliest_per_issue(self):
from products.error_tracking.backend.facade import api
- with freeze_time("2026-01-02T00:00:00Z"):
+ with time_machine.travel("2026-01-02T00:00:00Z", tick=False):
issue_one = self.create_issue(["fp_one_later"])
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
ErrorTrackingIssueFingerprintV2.objects.create(team=self.team, issue=issue_one, fingerprint="fp_one_early")
issue_two = self.create_issue(["fp_two"])
self.create_issue(["fp_other"])
diff --git a/products/error_tracking/backend/test/test_search_issues.py b/products/error_tracking/backend/test/test_search_issues.py
index 1e9d9b931afe..0757a216d0d0 100644
--- a/products/error_tracking/backend/test/test_search_issues.py
+++ b/products/error_tracking/backend/test/test_search_issues.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
ClickhouseTestMixin,
NonAtomicBaseTest,
@@ -34,7 +34,7 @@ from ee.hogai.utils.types import AssistantState
from ee.hogai.utils.types.base import NodePath
-@freeze_time("2025-01-15T12:00:00Z")
+@time_machine.travel("2025-01-15T12:00:00Z", tick=False)
class TestSearchErrorTrackingIssuesTool(ClickhouseTestMixin, NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -102,7 +102,7 @@ class TestSearchErrorTrackingIssuesTool(ClickhouseTestMixin, NonAtomicBaseTest):
status=ErrorTrackingIssue.Status.ACTIVE,
):
if timestamp:
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
self.create_issue(issue_id, fingerprint, name=issue_name, status=status)
else:
self.create_issue(issue_id, fingerprint, name=issue_name, status=status)
diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.py
index b584d8318dd7..3a83a0161877 100644
--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py
+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py
@@ -2,7 +2,7 @@ import os
import json
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, Mock, patch
@@ -136,7 +136,7 @@ class TestErrorTracking(APIBaseTest):
assert response.status_code == 200
assert response.json().get("id") == str(issue.id)
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
def test_issue_fetch(self):
issue = self.create_issue(["fingerprint"])
@@ -221,7 +221,7 @@ class TestErrorTracking(APIBaseTest):
assert assignee == {"id": expected_id, "type": assignee_type}
assert isinstance(assignee["id"], expected_python_type)
- @freeze_time("2025-01-01")
+ @time_machine.travel("2025-01-01", tick=False)
def test_issue_update(self):
issue = self.create_issue(["fingerprint"])
@@ -289,7 +289,7 @@ class TestErrorTracking(APIBaseTest):
("description", {"description": "Updated description"}),
]
)
- @freeze_time("2025-01-02")
+ @time_machine.travel("2025-01-02", tick=False)
def test_issue_update_stamps_clickhouse_visible_fields(self, _name: str, fields: dict[str, str]) -> None:
issue = self.create_issue(["fingerprint"])
@@ -302,7 +302,7 @@ class TestErrorTracking(APIBaseTest):
issue.refresh_from_db()
assert issue.state_updated_at == datetime(2025, 1, 2, tzinfo=UTC)
- @freeze_time("2025-01-02")
+ @time_machine.travel("2025-01-02", tick=False)
def test_issue_update_does_not_stamp_unchanged_state(self) -> None:
issue = self.create_issue(["fingerprint"])
diff --git a/products/error_tracking/backend/tests/api/test_query_api.py b/products/error_tracking/backend/tests/api/test_query_api.py
index dc1c44ffe1cc..0379e43f3fd3 100644
--- a/products/error_tracking/backend/tests/api/test_query_api.py
+++ b/products/error_tracking/backend/tests/api/test_query_api.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
@@ -122,7 +122,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
timestamp=now() - relativedelta(hours=1),
)
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issues_list_accepts_typed_filters_and_matches_release_precisely(self) -> None:
self.create_issue()
self.create_exception_event(
@@ -172,7 +172,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert project_response.status_code == 200
assert project_response.json()["results"] == []
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_queries_return_severity(self) -> None:
self.create_issue(severity=ErrorTrackingIssue.Severity.HIGH)
self.create_exception_event()
@@ -228,13 +228,13 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert list_response.status_code == 400
assert detail_response.status_code == 400
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issues_list_filters_by_assignee(self) -> None:
self.create_issue()
self.create_exception_event()
ErrorTrackingIssueAssignment.objects.create(issue_id=self.issue_id, user=self.user, team=self.team)
# re-sync with a strictly newer version so the assignment wins argMax over the create-time row
- with freeze_time(now() + timedelta(seconds=1)):
+ with time_machine.travel(now() + timedelta(seconds=1), tick=False):
sync_issues_to_clickhouse(issue_ids=[self.issue_id], team_id=self.team.pk)
flush_persons_and_events()
@@ -401,7 +401,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 200
assert observed_filter_groups == [None]
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_detail_returns_impact_top_frame_and_latest_release(self) -> None:
self.create_issue()
self.create_exception_event(
@@ -462,7 +462,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert data["latest_release"]["version"] == "2026.04.24"
assert data["latest_release"]["commit_id"] == "commit-123"
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_detail_returns_without_context_when_context_query_fails(self) -> None:
self.create_issue()
self.create_exception_event()
@@ -480,7 +480,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert response.json()["id"] == self.issue_id
assert "top_in_app_frame" not in response.json()
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_detail_distinguishes_missing_issue_from_empty_date_range(self) -> None:
self.create_issue(severity=ErrorTrackingIssue.Severity.HIGH)
@@ -536,7 +536,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 200
assert observed_tags == [(Product.ERROR_TRACKING, Feature.QUERY)]
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_events_matches_by_fingerprint(self) -> None:
self.create_issue()
self.create_exception_event(
@@ -554,7 +554,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 200
assert response.json()["results"][0]["properties"]["$session_id"] == "session-id-1"
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_events_matches_events_without_issue_id(self) -> None:
self.create_issue()
self.create_exception_event(include_issue_id=False, properties={"$session_id": "session-id-1"})
@@ -569,7 +569,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 200
assert response.json()["results"][0]["properties"]["$session_id"] == "session-id-1"
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_events_without_fingerprints_returns_empty(self) -> None:
ErrorTrackingIssue.objects.create(id=self.issue_id, team=self.team, name="TypeError")
@@ -609,7 +609,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 400
assert "Access to property '$referrer' is restricted" in str(response.json())
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_events_returns_plural_exception_arrays_and_truncates_summary_text(self) -> None:
long_text = "x" * 1200
self.create_issue()
@@ -634,7 +634,7 @@ class TestErrorTrackingQueryAPI(ClickhouseTestMixin, APIBaseTest):
assert "[truncated from 1200 chars]" in summary_event["properties"]["$exception_list"][0]["value"]
assert summary_event["properties"]["$session_id"] == "session-id-1"
- @freeze_time("2026-04-24T12:00:00Z")
+ @time_machine.travel("2026-04-24T12:00:00Z", tick=False)
def test_issue_events_returns_only_requested_context_groups(self) -> None:
self.create_issue()
self.create_exception_event(
diff --git a/products/error_tracking/backend/tests/api/test_recommendations.py b/products/error_tracking/backend/tests/api/test_recommendations.py
index b80c0826ba9a..f12af2e0c6f3 100644
--- a/products/error_tracking/backend/tests/api/test_recommendations.py
+++ b/products/error_tracking/backend/tests/api/test_recommendations.py
@@ -1,7 +1,7 @@
from datetime import timedelta
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -101,7 +101,6 @@ class TestRecommendationsAPI(ClickhouseTestMixin, APIBaseTest):
alerts = next(r for r in response.json()["results"] if r["type"] == "alerts")
self.assertEqual(alerts["meta"], MOCK_ALERTS_META_UPDATED)
- @freeze_time("2026-01-01T00:00:00Z", as_kwarg="frozen_time")
@patch(
"products.error_tracking.backend.logic.recommendations.long_running_issues.LongRunningIssuesRecommendation.compute",
)
@@ -109,19 +108,20 @@ class TestRecommendationsAPI(ClickhouseTestMixin, APIBaseTest):
"products.error_tracking.backend.logic.recommendations.alerts.AlertsRecommendation.compute",
return_value=MOCK_ALERTS_META,
)
- def test_long_running_is_cached_until_interval_elapses(self, mock_alerts, mock_long_running, frozen_time):
- mock_long_running.return_value = {"issues": []}
- self._list()
- self.assertEqual(mock_long_running.call_count, 1)
-
- # Re-listing within the same refresh window doesn't recompute.
- self._list()
- self.assertEqual(mock_long_running.call_count, 1)
-
- # A full refresh_interval always crosses into the next window — recompute, regardless of phase.
- frozen_time.tick(LongRunningIssuesRecommendation.refresh_interval)
- self._list()
- self.assertEqual(mock_long_running.call_count, 2)
+ def test_long_running_is_cached_until_interval_elapses(self, mock_alerts, mock_long_running):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen_time:
+ mock_long_running.return_value = {"issues": []}
+ self._list()
+ self.assertEqual(mock_long_running.call_count, 1)
+
+ # Re-listing within the same refresh window doesn't recompute.
+ self._list()
+ self.assertEqual(mock_long_running.call_count, 1)
+
+ # A full refresh_interval always crosses into the next window — recompute, regardless of phase.
+ frozen_time.shift(LongRunningIssuesRecommendation.refresh_interval)
+ self._list()
+ self.assertEqual(mock_long_running.call_count, 2)
@patch(
"products.error_tracking.backend.logic.recommendations.long_running_issues.LongRunningIssuesRecommendation.compute",
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
index 28935b216e60..f8e5e9b0d781 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
@@ -56,7 +56,7 @@ class ExperimentQueryRunnerBaseTest(ClickhouseTestMixin, APIBaseTest):
if use_precomputation:
self._clean_preaggregation_data()
# Disable TTL merges so ClickHouse 26.3 doesn't immediately drop
- # rows whose expires_at is in the past (due to freeze_time).
+ # rows whose expires_at is in the past (due to the frozen clock).
for table_name in (
SHARDED_EXPERIMENT_EXPOSURES_TABLE(),
SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE(),
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_activation_config.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_activation_config.py
index 660fb1f44fd0..9471ff4735d2 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_activation_config.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_activation_config.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.forms.models import model_to_dict
@@ -116,7 +116,7 @@ class TestExperimentActivationConfig(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.sum, 3)
self.assertEqual(test_variant.sum, 6)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_anchors_exposure_on_activation_event(self):
feature_flag = self.create_feature_flag()
@@ -129,7 +129,7 @@ class TestExperimentActivationConfig(ExperimentQueryRunnerBaseTest):
self._seed_mean_scenario(feature_flag)
self._assert_mean_scenario_results(experiment, metric)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
def test_team_precomputation_does_not_change_activation_results(self):
self._setup_precomputation_test(True)
@@ -147,7 +147,7 @@ class TestExperimentActivationConfig(ExperimentQueryRunnerBaseTest):
self._assert_mean_scenario_results(experiment, metric)
self.assertEqual(PreaggregationJob.objects.count(), 0)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_counts_conversions_after_activation_only(self):
feature_flag = self.create_feature_flag()
@@ -188,7 +188,7 @@ class TestExperimentActivationConfig(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.sum, 1) # success_count
self.assertEqual(test_variant.sum, 1) # success_count
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposures_timeseries_counts_users_on_activation_day(self):
feature_flag = self.create_feature_flag()
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_add_missing_variants.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_add_missing_variants.py
index ca2283363ab5..6a9f7f5b37a4 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_add_missing_variants.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_add_missing_variants.py
@@ -1,6 +1,6 @@
from typing import cast
-from freezegun import freeze_time
+import time_machine
from django.test import override_settings
@@ -29,7 +29,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
self.feature_flag = self.create_feature_flag()
self.experiment = self.create_experiment(feature_flag=self.feature_flag)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_no_missing_variants(self):
"""When all variants are present, should return unchanged."""
metric = ExperimentMeanMetric(
@@ -49,7 +49,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert len(result) == 2
assert result == variants
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_missing_variant_without_breakdown(self):
"""Should add missing variant with None breakdown."""
metric = ExperimentMeanMetric(
@@ -73,7 +73,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert result[1][1].sum == 0
assert result[1][1].sum_squares == 0
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_multiple_missing_variants_without_breakdown(self):
"""Should add all missing variants when multiple are missing."""
# Create feature flag with 3 variants
@@ -103,7 +103,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert "test" in keys
assert "test-2" in keys
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_missing_variant_with_single_breakdown(self):
"""Should add missing variant for each breakdown value."""
metric = ExperimentMeanMetric(
@@ -133,7 +133,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert stats.number_of_samples == 0
assert stats.sum == 0
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_missing_variant_with_multiple_breakdowns(self):
"""Should add missing variant for each breakdown combination."""
metric = ExperimentMeanMetric(
@@ -170,7 +170,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
("with_breakdown", BreakdownFilter(breakdowns=[Breakdown(property="$browser")])),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_empty_variants_list(self, _name, breakdown_filter):
"""Should add all configured variants when input is empty."""
metric = ExperimentMeanMetric(
@@ -193,7 +193,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert breakdown is None
assert stats.number_of_samples == 0
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_preserves_existing_variants(self):
"""Should not modify existing variant data."""
metric = ExperimentMeanMetric(
@@ -215,7 +215,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert result[0][1].number_of_samples == 100
assert result[0][1].sum == 250.0
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_creates_unique_objects_per_breakdown(self):
"""Verifies that each breakdown gets a unique ExperimentStatsBase object (regression test)."""
metric = ExperimentMeanMetric(
@@ -244,7 +244,7 @@ class TestAddMissingVariants(ExperimentQueryRunnerBaseTest):
assert objects[0] is not objects[2]
assert objects[1] is not objects[2]
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_with_holdout_variant(self):
from products.experiments.backend.models.experiment import ExperimentHoldout
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py
index 528f691c77ca..611bd5897e42 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from unittest.mock import patch
@@ -64,7 +64,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(builder_class.call_args.kwargs["feature_flag_key"], original_key)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_includes_date_range(self):
feature_flag = self.create_feature_flag()
@@ -170,7 +170,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 10)
self.assertEqual(test_variant.number_of_samples, 10)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_includes_event_property_filters(self):
feature_flag = self.create_feature_flag()
@@ -250,7 +250,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 11)
self.assertEqual(test_variant.number_of_samples, 11)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_using_action(self):
feature_flag = self.create_feature_flag()
@@ -311,7 +311,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 10)
self.assertEqual(test_variant.number_of_samples, 10)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_group_aggregation_mean_metric(self):
feature_flag = self.create_feature_flag()
@@ -351,7 +351,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.sum, 6)
self.assertEqual(test_variant.sum, 8)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_group_aggregation_mean_property_sum_metric(self):
feature_flag = self.create_feature_flag()
@@ -391,7 +391,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.sum, 60)
self.assertEqual(test_variant.sum, 120)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_standard_flow_v2_stats(self):
feature_flag = self.create_feature_flag()
@@ -799,7 +799,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 3)
self.assertEqual(test_variant.number_of_samples, 4)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_without_feature_flag_property(self):
feature_flag = self.create_feature_flag()
@@ -850,7 +850,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 11)
self.assertEqual(test_variant.number_of_samples, 10)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_no_exposures(self):
feature_flag = self.create_feature_flag()
@@ -884,7 +884,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 0)
self.assertEqual(test_variant.number_of_samples, 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_no_variant_exposures(self):
feature_flag = self.create_feature_flag()
@@ -938,7 +938,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 10)
self.assertEqual(test_variant.number_of_samples, 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_no_control_variant(self):
feature_flag = self.create_feature_flag()
@@ -1307,7 +1307,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
],
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_time_window(self, time_window_name, time_window_hours, expected_results):
feature_flag = self.create_feature_flag()
@@ -1379,7 +1379,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.sum, expected_results["control_count"])
self.assertEqual(test_variant.sum, expected_results["test_count"])
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_excludes_multiple_variants(self):
feature_flag = self.create_feature_flag()
@@ -1524,7 +1524,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
],
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_multiple_variant_handling_options(
self, handling_name, multiple_variant_handling, expected_results
@@ -1722,7 +1722,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
f"Test exposure mismatch for {handling_name} handling",
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_none_event_filters_all_events(self):
"""Test that when event is None, all events are selected (no event name filter applied)."""
@@ -1830,7 +1830,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 5)
self.assertEqual(test_variant.number_of_samples, 5)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_hogql_aggregation_expressions(self):
"""Test that HogQL aggregation expressions work end-to-end."""
@@ -1919,7 +1919,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.sum, expected_test_sum)
self.assertEqual(test_variant.number_of_samples, 10)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_hogql_aggregation_end_to_end(self):
"""Test that HogQL aggregation expressions work end-to-end with the experiment query runner."""
@@ -1994,7 +1994,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 3)
self.assertEqual(test_variant.number_of_samples, 4)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_hogql_fallback_to_sum(self):
"""Test that HogQL expressions without aggregation functions default to sum."""
@@ -2077,7 +2077,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_unique_users_metric(self, name, use_precomputation):
"""Test that unique users metric correctly counts unique users, not total events."""
@@ -2196,7 +2196,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.sum, 4)
self.assertEqual(test_variant.number_of_samples, 4)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_unique_group_metric(self):
"""Test unique group metric counts unique groups that performed the target event."""
@@ -2248,7 +2248,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.sum, 3) # 3 unique groups with purchase events
self.assertEqual(test_variant.number_of_samples, 3) # 3 unique groups exposed to test
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_parametric_aggregation(self):
"""Test that parametric aggregations like quantile work in mean metrics.
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_breakdown.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_breakdown.py
index ad798978d054..4cb0d0a774a5 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_breakdown.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_breakdown.py
@@ -1,6 +1,6 @@
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -31,7 +31,7 @@ from products.experiments.backend.hogql_queries.test.experiment_query_runner.bas
@override_settings(IN_UNIT_TESTING=True)
class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_breakdown(self):
feature_flag = self.create_feature_flag()
@@ -143,7 +143,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(variant.number_of_samples)
@parameterized.expand([("new_query_builder", True)])
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_breakdown_with_changing_property_values(self, name, use_new_query_builder):
"""
@@ -284,7 +284,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertEqual(firefox_breakdown.baseline.sum, 50)
@parameterized.expand([("new_query_builder", True)])
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_breakdown(self, name, use_new_query_builder):
feature_flag = self.create_feature_flag()
@@ -388,7 +388,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(breakdown_result.variants)
self.assertGreater(len(breakdown_result.variants), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_with_breakdown(self):
feature_flag = self.create_feature_flag()
@@ -524,7 +524,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(breakdown_result.variants)
self.assertGreater(len(breakdown_result.variants), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_null_breakdown_values(self):
"""Test that NULL breakdown values are handled correctly"""
@@ -605,7 +605,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
# variants can be empty if no test variants exist for this breakdown
self.assertIsInstance(breakdown_result.variants, list)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_winsorization_and_breakdown(self):
"""Test that winsorization computes per-breakdown percentiles, not global percentiles"""
@@ -715,7 +715,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(breakdown_result.variants)
self.assertGreater(len(breakdown_result.variants), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_two_breakdowns(self):
"""Test mean metric calculations work correctly with 2 breakdown dimensions"""
@@ -846,7 +846,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(variant.number_of_samples)
self.assertEqual(variant.number_of_samples, 2) # 2 users per combination
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_two_breakdowns(self):
"""Test funnel metrics work with 2 breakdown dimensions"""
@@ -947,7 +947,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
assert result.breakdown_results is not None
self.assertEqual(len(result.breakdown_results), 4)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_funnel_metric_breakdown_query_builds_without_ambiguity_error(self):
"""
Regression test for ambiguous query error with UNORDERED funnel breakdowns.
@@ -982,7 +982,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
# If it does, that means the breakdown field references are not properly qualified
query_runner._evaluate_experiment_query()
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_with_two_breakdowns(self):
"""Test ratio metrics work with 2 breakdown dimensions"""
@@ -1126,7 +1126,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
# Verify error message mentions too many items
self.assertIn("at most 3 items", str(context.exception))
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_missing_variants_across_breakdown_combinations(self):
"""Verify correct handling when control has all breakdown combinations but test is missing some"""
@@ -1259,7 +1259,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertTrue(safari_mac_found, "Safari+Mac breakdown should exist")
@parameterized.expand([("new_query_builder", True)])
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_metric_with_breakdown(self, name, use_new_query_builder):
"""
@@ -1409,7 +1409,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(variant.sum)
@parameterized.expand([("new_query_builder", True)])
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_metric_with_two_breakdowns(self, name, use_new_query_builder):
"""
@@ -1557,7 +1557,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(breakdown_result.variants)
self.assertGreater(len(breakdown_result.variants), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_retention_metric_breakdown_with_missing_control_variant(self):
"""
Regression test: Retention metrics with breakdowns should handle cases where
@@ -1680,7 +1680,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(safari_breakdown.baseline)
self.assertEqual(safari_breakdown.baseline.number_of_samples, 0) # No control users with Safari
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_person_property_breakdown(self):
"""Test that mean metrics can be broken down by person properties"""
@@ -1788,7 +1788,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(variant.number_of_samples)
self.assertEqual(variant.number_of_samples, 2) # 2 users per country per variant
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_null_person_property_breakdown(self):
"""Test that NULL person properties are handled correctly with BREAKDOWN_NULL_STRING_LABEL"""
@@ -1882,7 +1882,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIn(["US"], breakdown_values)
self.assertIn([BREAKDOWN_NULL_STRING_LABEL], breakdown_values)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_person_property_breakdown(self):
"""Test that funnel metrics can be broken down by person properties"""
@@ -1962,7 +1962,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
# 1 out of 2 users converted in each country
self.assertEqual(breakdown_result.baseline.number_of_samples, 2)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_mean_metric_with_null_type_defaults_to_event_breakdown(self):
"""Test backward compatibility: type=None defaults to event property"""
@@ -2037,7 +2037,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
# Should have breakdown combinations for browser x url
self.assertGreater(len(result.breakdown_results), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_with_person_property_breakdown(self):
"""Test that ratio metrics can be broken down by person properties"""
@@ -2145,7 +2145,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(breakdown_result.variants)
self.assertGreater(len(breakdown_result.variants), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_metric_with_person_property_breakdown(self):
"""Test that retention metrics can be broken down by person properties"""
@@ -2259,7 +2259,7 @@ class TestExperimentBreakdown(ExperimentQueryRunnerBaseTest):
self.assertIsNotNone(breakdown_result.variants)
self.assertGreater(len(breakdown_result.variants), 0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_person_property_breakdown_attribution_at_exposure(self):
"""
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_funnel_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_funnel_metric.py
index 6c96f7624b3e..5318a22745c5 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_funnel_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_funnel_metric.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from django.test import override_settings
@@ -118,7 +118,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
if (i * 7) % 100 < threshold:
self._create_checkout(feature_flag, distinct_id, "2020-01-10T13:00:00Z")
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_disabled_cuped_does_not_collect_covariate_columns(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -149,7 +149,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertIsNone(result.baseline.covariate_sum)
self.assertIsNone(result.variant_results[0].covariate_sum)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_funnel_metric_collects_covariate_columns(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -204,7 +204,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
# Only the user that converted both pre and post contributes to the cross product.
self.assertEqual(test_variant.covariate_sum_product, 1)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_uses_pre_exposure_window_relative_to_first_exposure(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -248,7 +248,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.covariate_sum, 1)
self.assertEqual(test_variant.covariate_sum_product, 1)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_multi_step_funnel_uses_last_step_for_covariate(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -297,7 +297,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.covariate_sum, 0)
self.assertEqual(test_variant.covariate_sum_product, 0)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_query_uses_single_metric_events_scan(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -321,7 +321,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertNotIn("pre_metric_events", result.hogql)
self.assertNotIn("pre_base_events", result.hogql)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_unordered_funnel_disables_cuped(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -351,7 +351,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertIsNone(result.baseline.covariate_sum)
self.assertIsNone(result.variant_results[0].covariate_sum)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_handles_zero_pre_exposure_data(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -385,7 +385,7 @@ class TestExperimentFunnelMetricCuped(ExperimentQueryRunnerBaseTest):
("bayesian", "bayesian", "credible_interval"),
]
)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_adjusts_statistical_result(self, name, method, interval_attr):
metric = self._build_single_step_metric()
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_mean_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_mean_metric.py
index a0a5d3c80fdc..a54499e0be82 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_mean_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_cuped_mean_metric.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from django.test import override_settings
@@ -108,7 +108,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self._create_exposure(feature_flag, distinct_id, variant, "2020-01-10T12:00:00Z")
self._create_purchase(feature_flag, distinct_id, "2020-01-10T13:00:00Z", post_amount)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_disabled_cuped_does_not_collect_covariate_columns(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -139,7 +139,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertIsNone(result.baseline.covariate_sum)
self.assertIsNone(result.variant_results[0].covariate_sum)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_mean_metric_collects_covariate_columns(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -180,7 +180,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.covariate_sum_squares, 61)
self.assertEqual(test_variant.covariate_sum_product, 390)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_uses_pre_exposure_window_relative_to_first_exposure(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -221,7 +221,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_variant.covariate_sum, 6)
self.assertEqual(test_variant.covariate_sum_product, 48)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_respects_conversion_window_for_post_values(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -267,7 +267,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_works_with_precomputed_exposures(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -308,7 +308,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertEqual(result.baseline.covariate_sum, 3)
self.assertEqual(result.variant_results[0].covariate_sum, 5)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_query_uses_single_metric_events_scan(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -331,7 +331,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertNotIn("pre_metric_events", result.hogql)
self.assertEqual(result.hogql.count("metric_events AS"), 1)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_adjusts_statistical_result(self):
metric = self._build_sum_metric()
@@ -379,7 +379,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
cuped_interval_width = cuped_variant.confidence_interval[1] - cuped_variant.confidence_interval[0]
self.assertLess(cuped_interval_width, no_cuped_interval_width)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_adjusts_bayesian_statistical_result(self):
metric = self._build_sum_metric()
@@ -427,7 +427,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
cuped_interval_width = cuped_variant.credible_interval[1] - cuped_variant.credible_interval[0]
self.assertLess(cuped_interval_width, no_cuped_interval_width)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_handles_zero_pre_exposure_data(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -454,7 +454,7 @@ class TestExperimentMeanMetricCuped(ExperimentQueryRunnerBaseTest):
self.assertEqual(variant.covariate_sum_product, 0)
assert variant.p_value is not None
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
def test_cuped_unique_session_metric_collects_distinct_covariates(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py
index 7eab9df46364..7ba382cca5d3 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_data_warehouse_metric.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -112,7 +112,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -179,7 +179,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -246,7 +246,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-31"):
+ with time_machine.travel("2023-01-31", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -530,7 +530,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_result.number_of_samples, filter_expected["test_absolute_exposure"])
else:
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -565,7 +565,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
experiment.save()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -653,7 +653,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-10"):
+ with time_machine.travel("2023-01-10", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -759,7 +759,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -833,7 +833,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -955,7 +955,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-10"):
+ with time_machine.travel("2023-01-10", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -1102,7 +1102,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time(end_date):
+ with time_machine.travel(end_date, tick=False):
result = query_runner.calculate()
# Verify that precomputation was NOT used
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_excluded_variants.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_excluded_variants.py
index b6c702fa4a97..60d4bd129088 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_excluded_variants.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_excluded_variants.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from django.test import override_settings
@@ -34,7 +34,7 @@ class TestExcludedVariants(ExperimentQueryRunnerBaseTest):
("excluded_variants_naming_holdout_is_idempotent", [], True, [_HOLDOUT_KEY]),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_runner_variant_filtering(self, name, extra_variants, attach_holdout, excluded_variants):
feature_flag = self.create_feature_flag(key=f"{name.replace('_', '-')}-test")
for index, variant_key in enumerate(extra_variants):
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
index ff70ba93086b..673157bffb2e 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from unittest.mock import patch
@@ -86,7 +86,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertIn("not found", str(ctx.exception))
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
def test_exposure_query_resolves_soft_deleted_feature_flag_key(self):
# Exposure events are captured under the flag's original key.
original_key = self.feature_flag.key
@@ -162,7 +162,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
("query_window_starts_after_cutoff", True, -7, 14, 7, {"control": 2, "test": 1}),
]
)
- @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=30))
+ @time_machine.travel(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=30), tick=False)
def test_exposure_event_selected_relative_to_cutoff(
self,
_name,
@@ -237,7 +237,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures, expected_exposures)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_returns_correct_timeseries(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -396,7 +396,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures["test"], 5)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_counts_users_only_on_first_exposure(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -515,7 +515,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures["test"], 2)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_filters_test_accounts(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -721,7 +721,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
("feature_flag_called_precomputed", "$feature_flag_called", True),
]
)
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_with_custom_exposure(self, _name, exposure_event, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -845,7 +845,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures["test"], 5)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_without_feature_flag_property(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -983,7 +983,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures["test"], 5)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_with_multiple_variant_exposures(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1076,7 +1076,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures[MULTIPLE_VARIANT_KEY], 1)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_using_group_aggregation(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1114,7 +1114,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.total_exposures["test"], 3)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_multiple_variant_handling_first_seen(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1226,7 +1226,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertNotIn(MULTIPLE_VARIANT_KEY, response.total_exposures)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_exposure_query_with_action_as_exposure_criteria(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1339,7 +1339,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(test_series.exposure_counts[-1], 3)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
def test_srm_calculation_with_balanced_distribution(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
ff_property = f"$feature/{self.feature_flag.key}"
@@ -1403,7 +1403,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.sample_ratio_mismatch.expected["test"], 50.0)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
def test_srm_calculation_detects_significant_mismatch(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
ff_property = f"$feature/{self.feature_flag.key}"
@@ -1471,7 +1471,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
self.assertEqual(response.sample_ratio_mismatch.expected["test"], 50.0)
@parameterized.expand([("direct", False), ("precomputed", True)])
- @freeze_time("2024-01-07T12:00:00Z")
+ @time_machine.travel("2024-01-07T12:00:00Z", tick=False)
def test_srm_returns_none_when_insufficient_samples(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
ff_property = f"$feature/{self.feature_flag.key}"
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_frequentist_method.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_frequentist_method.py
index 46e3b586b6a7..845bf9aec230 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_frequentist_method.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_frequentist_method.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -23,7 +23,7 @@ from products.experiments.backend.hogql_queries.test.experiment_query_runner.bas
@override_settings(IN_UNIT_TESTING=True)
class TestFrequentistMethod(ExperimentQueryRunnerBaseTest):
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_frequentist_property_sum_metric(self):
feature_flag = self.create_feature_flag()
@@ -109,7 +109,7 @@ class TestFrequentistMethod(ExperimentQueryRunnerBaseTest):
query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)
return cast(ExperimentQueryResponse, ExperimentQueryRunner(query=query, team=self.team).calculate())
- @freeze_time("2020-01-03T12:00:00Z")
+ @time_machine.travel("2020-01-03T12:00:00Z", tick=False)
def test_sequential_testing_widens_ci_versus_fixed_horizon(self) -> None:
# Run identical data through fixed-horizon then sequential frequentist; verify
# the sequential CI is strictly wider end-to-end through the query runner.
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
index e048cf697c14..a5dc57bea3f9 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
@@ -2,7 +2,7 @@ import json
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
_create_event,
_create_person,
@@ -49,7 +49,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_funnel_metric(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -167,7 +167,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Skip precomputed - not yet supported (breakdowns/groups)
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_group_aggregation_funnel_metric(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -471,7 +471,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
]
)
@snapshot_clickhouse_queries
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_persons_on_events_mode(self, name, persons_on_events_mode, filters, expected_results):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -731,7 +731,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Test that UNION ALL query executes without error
# The snapshot will verify the correct query structure
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
# Verify query completed successfully
@@ -833,7 +833,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Execute query - should NOT fail with CHQueryErrorCannotInsertNullInOrdinaryColumn
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
# Verify query completed successfully without NULL errors
@@ -924,7 +924,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Execute query - should NOT fail even with all NULLs
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
# Verify query completed successfully
@@ -1076,7 +1076,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Execute query
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
# Verify NO fan-out occurred
@@ -1095,7 +1095,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_conversion_window(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1214,7 +1214,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_custom_conversion_window(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1346,7 +1346,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_action(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1461,7 +1461,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_many_steps(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1573,7 +1573,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_step_property_filter(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1706,7 +1706,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_multiple_similar_steps(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1860,7 +1860,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_with_unordered_steps(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1976,7 +1976,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Skip precomputed - not yet supported (breakdowns/groups)
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_ordered_vs_unordered_comparison(self, name, use_precomputation):
"""Test that ordered and unordered funnels behave differently when events are out of order"""
@@ -2173,7 +2173,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Skip precomputed - not yet supported (breakdowns/groups)
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_excludes_different_feature_flags(self, name, use_precomputation):
"""Test that users with $feature_flag_called events for different flags are excluded"""
@@ -2368,7 +2368,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
# Skip precomputed - experiment end_date filtering not working correctly (TODO: fix)
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_excludes_events_after_experiment_end_date(self, name, use_precomputation):
"""Test that funnel metric events after experiment end_date are excluded from results"""
@@ -2487,7 +2487,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("unordered", StepOrderValue.UNORDERED),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_funnel_metric_events_after_exposure(self, name, funnel_order_type):
"""Test that funnel metric events are only counted if they occur AFTER experiment exposure"""
@@ -2703,7 +2703,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_only_count_matured_users(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -2841,7 +2841,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_maturity_anchored_on_first_exposure(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py
index f6d9650c7eea..4aecfb26f979 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py
@@ -2,7 +2,7 @@ from collections.abc import Sequence
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -34,7 +34,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_property_sum_metric(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -133,7 +133,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_conversion_window_anchored_on_first_exposure(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -297,12 +297,12 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
# Re-run right after the user matures, then again after the re-exposure. The
# matured user's value must not grow just because the flag was re-evaluated.
- with freeze_time("2020-01-04T00:00:00Z"):
+ with time_machine.travel("2020-01-04T00:00:00Z", tick=False):
early = cast(
ExperimentQueryResponse,
ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),
)
- with freeze_time("2020-01-07T00:00:00Z"):
+ with time_machine.travel("2020-01-07T00:00:00Z", tick=False):
late = cast(
ExperimentQueryResponse,
ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),
@@ -319,7 +319,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_outlier_handling_for_sum_metric(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -420,7 +420,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_outlier_handling_for_count_metric(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -523,7 +523,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_unique_sessions_math_type(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -631,7 +631,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("avg_precomputed", True, ExperimentMetricMathType.AVG, 35, 130),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_property_aggregation_metric(
self, name, use_precomputation, math_type, expected_control_sum, expected_test_sum
@@ -720,7 +720,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_outlier_handling_with_ignore_zeros(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -830,7 +830,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_count_unique_property_values_via_hogql(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -925,7 +925,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_only_count_matured_users(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1043,7 +1043,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_hogql_count_metric_with_winsorization(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1176,7 +1176,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_threshold_sum_metric_counts_users_crossing(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1233,7 +1233,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.number_of_samples, 10)
self.assertEqual(test_variant.number_of_samples, 10)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_threshold_is_inclusive_and_zero_for_users_without_events(self):
"""A user whose sum exactly equals the threshold crosses; a user with no events does not."""
feature_flag = self.create_feature_flag()
@@ -1270,7 +1270,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):
self.assertEqual(result.variant_results[0].sum, 1)
self.assertEqual(result.variant_results[0].number_of_samples, 2)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_threshold_count_metric_counts_users_with_enough_events(self):
"""With TOTAL math the per-user value is the event count; threshold compares against it."""
feature_flag = self.create_feature_flag()
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
index fdc7406cdf04..bf599475ef42 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
@@ -1,6 +1,6 @@
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -38,7 +38,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_basic_ratio_metric(self, name, use_precomputation):
"""Test basic ratio metric functionality with revenue per purchase event"""
@@ -185,7 +185,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_different_math_types(self, name, use_precomputation):
"""Test ratio metric with different math types for numerator and denominator"""
@@ -298,7 +298,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_with_conversion_window(self, name, use_precomputation):
"""Test ratio metric with conversion window"""
@@ -502,12 +502,12 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
- with freeze_time("2020-01-04T00:00:00Z"):
+ with time_machine.travel("2020-01-04T00:00:00Z", tick=False):
early = cast(
ExperimentQueryResponse,
ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),
)
- with freeze_time("2020-01-07T00:00:00Z"):
+ with time_machine.travel("2020-01-07T00:00:00Z", tick=False):
late = cast(
ExperimentQueryResponse,
ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),
@@ -526,7 +526,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_zero_denominator(self, name, use_precomputation):
"""Test ratio metric behavior when denominator is zero"""
@@ -635,7 +635,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_same_event_different_properties(self, name, use_precomputation):
"""Test ratio metric using the same event with different math properties"""
@@ -761,7 +761,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_action_and_event_sources(self, name, use_precomputation):
"""Test ratio metric with action source numerator and event source denominator"""
@@ -962,7 +962,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
result = query_runner.calculate()
assert result.variant_results is not None
@@ -993,7 +993,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_ratio_metric_with_parametric_aggregation(self, name, use_precomputation):
"""Test parametric aggregations in ratio metrics.
@@ -1099,7 +1099,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-15T12:00:00Z")
+ @time_machine.travel("2020-01-15T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_only_count_matured_users(self, name, use_precomputation):
from datetime import datetime
@@ -1301,7 +1301,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_outlier_handling_numerator_only(self, name, use_precomputation):
"""Capping only the numerator leaves the denominator untouched."""
@@ -1361,7 +1361,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_outlier_handling_numerator_and_denominator_independent(self, name, use_precomputation):
"""Numerator and denominator are capped independently, each at its own threshold."""
@@ -1416,7 +1416,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
self.assertEqual(control_variant.denominator_sum, 26)
self.assertEqual(test_variant.denominator_sum, 20)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_outlier_handling_with_breakdown(self):
"""Winsorization computes per-breakdown thresholds for ratio metrics, not global ones."""
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_retention_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_retention_metric.py
index 2c6ea7e5e87f..afea707d5329 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_retention_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_retention_metric.py
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -35,7 +35,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_basic_retention_calculation(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -190,7 +190,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_window_boundaries(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -325,7 +325,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_first_seen_vs_last_seen(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -494,7 +494,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_with_conversion_window(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -635,7 +635,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_no_completion_events(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -743,7 +743,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_multiple_variants(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -894,7 +894,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_day_zero_same_day_as_start(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1053,7 +1053,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("first_seen_window_start_one_precomputed", True, StartHandling.FIRST_SEEN, 1, 1, 1, 0),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
def test_retention_same_start_and_completion_event_excludes_self(
self,
name,
@@ -1169,7 +1169,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_hour_based_same_hour(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1324,7 +1324,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_multiple_completions_in_window(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1460,7 +1460,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_retention_start_event_before_exposure_not_excluded(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1616,7 +1616,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-25T12:00:00Z")
+ @time_machine.travel("2020-01-25T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_only_count_matured_users(self, name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
@@ -1764,7 +1764,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-25T12:00:00Z")
+ @time_machine.travel("2020-01-25T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_only_count_matured_users_without_conversion_window(self, name, use_precomputation):
# Retention metrics should respect only_count_matured_users even when no
@@ -1904,7 +1904,7 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
("precomputed", True),
]
)
- @freeze_time("2020-01-25T12:00:00Z")
+ @time_machine.travel("2020-01-25T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_only_count_matured_users_anchors_on_start_event(self, name, use_precomputation):
# Maturity must be anchored on the user's start_event timestamp, not their
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_session_properties.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_session_properties.py
index 5389ed0efd87..22df502c1950 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_session_properties.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_session_properties.py
@@ -1,6 +1,6 @@
from typing import cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from django.test import override_settings
@@ -22,7 +22,7 @@ from products.experiments.backend.hogql_queries.test.experiment_query_runner.bas
@override_settings(IN_UNIT_TESTING=True)
class TestExperimentSessionPropertyMetrics(ExperimentQueryRunnerBaseTest):
@snapshot_clickhouse_queries
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
def test_session_duration_not_multiplied_across_events(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -147,7 +147,7 @@ class TestExperimentSessionPropertyMetrics(ExperimentQueryRunnerBaseTest):
assert control_variant.number_of_samples == 1
assert test_variant.number_of_samples == 1
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
def test_multiple_sessions_per_user_sums_correctly(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -236,7 +236,7 @@ class TestExperimentSessionPropertyMetrics(ExperimentQueryRunnerBaseTest):
assert test_variant.sum == 180
assert test_variant.number_of_samples == 1
- @freeze_time("2024-01-01T12:00:00Z")
+ @time_machine.travel("2024-01-01T12:00:00Z", tick=False)
def test_session_duration_backwards_compat_without_property_type(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
index c6aee5a62fcb..9b7da013acbf 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
@@ -7,7 +7,7 @@ The implementation will follow to make these tests pass.
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -159,7 +159,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
("dropoffs_test", -2, "test", 2), # Step 2 drop-offs - test variant
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_experiment_funnel_actors(self, _name: str, funnel_step: int, variant: str, expected_count: int):
"""
@@ -195,7 +195,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
for distinct_id in distinct_ids:
assert distinct_id.startswith(f"user_{variant}_")
- @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=4))
+ @time_machine.travel(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=4), tick=False)
def test_experiment_funnel_actors_resolves_explicit_default_exposure_event(self) -> None:
feature_flag, experiment, experiment_query = self._create_experiment_with_funnel()
experiment.start_date = EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=1)
@@ -235,7 +235,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
assert [row[1]["distinct_ids"][0] for row in response.results] == [distinct_id]
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_experiment_funnel_actors_with_recordings(self):
"""
@@ -319,7 +319,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
# matched_recordings should be a list (may be empty if no actual recordings exist)
assert isinstance(response.results[0][2], list)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_experiment_exposure_actors_with_recordings(self):
"""
@@ -351,7 +351,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
assert len(response.results[0]) == 3
assert isinstance(response.results[0][2], list)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_experiment_funnel_actors_invalid_steps(self):
"""
Test that invalid funnelStep values are properly rejected with helpful error messages.
@@ -417,7 +417,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
self.assertIn("Valid conversion steps: 0", error_message) # Shows valid range start
self.assertIn("(exposure step) to 2", error_message) # Shows valid range end with explanation
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_experiment_funnel_actors_excludes_events_before_exposure(self):
"""
@@ -507,7 +507,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
assert len(response.results) == 1
assert response.results[0][1]["distinct_ids"][0] == "user_after_exposure"
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_experiment_funnel_actors_step1_dropoff_counts_pre_exposure_signup(self):
"""
@@ -589,7 +589,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
),
]
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_experiment_funnel_actors_cohort_sanitization(
self,
_name: str,
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_funnels_query_runner.py b/products/experiments/backend/hogql_queries/test/test_experiment_funnels_query_runner.py
index 9d3536610817..7500de7d0d68 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_funnels_query_runner.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_funnels_query_runner.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from typing import cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -118,7 +118,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
f"$feature/{original_key}",
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -187,7 +187,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertAlmostEqual(result.credible_intervals["test"][1], 0.9, delta=0.1)
@pytest.mark.flaky(reruns=9)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_standard_flow(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -315,7 +315,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
],
]
)
- @freeze_time("2020-01-01T00:00:00Z")
+ @time_machine.travel("2020-01-01T00:00:00Z", tick=False)
def test_query_runner_attribution(self, attribution_type, expected_counts):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -557,7 +557,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
@snapshot_clickhouse_queries
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_persons_on_events_mode(self, name, persons_on_events_mode, filters, expected_results):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -662,7 +662,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
expected_results,
)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_holdout(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -730,7 +730,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIn("test", result.credible_intervals)
self.assertIn(f"holdout-{holdout.id}", result.credible_intervals)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_validate_event_variants_no_control(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -770,7 +770,7 @@ class TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(cast(list, context.exception.detail)[0], expected_errors)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_validate_event_variants_no_test(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py b/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py
index 9ad88a4b655d..c01415b4ac10 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_trends_query_runner.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -142,7 +142,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(feature_flag_filter.value, [original_key])
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -201,7 +201,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(control_result.absolute_exposure, 7)
self.assertEqual(test_result.absolute_exposure, 9)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_custom_exposure(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -356,7 +356,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(control_result.absolute_exposure, 2)
self.assertEqual(test_result.absolute_exposure, 3)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_custom_exposure_sum_math(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -491,7 +491,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(control_result.absolute_exposure, 2)
self.assertEqual(test_result.absolute_exposure, 2)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_default_exposure(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -583,7 +583,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(control_result.absolute_exposure, 2)
self.assertEqual(test_result.absolute_exposure, 2)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_query_runner_with_action(self):
feature_flag = self.create_feature_flag()
@@ -679,7 +679,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(control_result.absolute_exposure, 2)
self.assertEqual(test_result.absolute_exposure, 2)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_with_holdout(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -1008,7 +1008,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(test_result.absolute_exposure, 16)
# Uses mirrored values for easy comparison with the avg-math scenario
- @freeze_time("2020-01-01T00:00:00Z")
+ @time_machine.travel("2020-01-01T00:00:00Z", tick=False)
def test_query_runner_with_avg_math_v2_stats(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -1119,7 +1119,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
@pytest.mark.flaky(reruns=9)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_query_runner_standard_flow_v2_stats(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -1239,7 +1239,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(test_variant.count, 5.0)
self.assertEqual(test_variant.exposure, 1.0)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_validate_event_variants_no_control(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -1276,7 +1276,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(cast(list, context.exception.detail)[0], expected_errors)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_validate_event_variants_no_test(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
@@ -1321,7 +1321,7 @@ class TestExperimentTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(cast(list, context.exception.detail)[0], expected_errors)
- @freeze_time("2020-01-01T12:00:00Z")
+ @time_machine.travel("2020-01-01T12:00:00Z", tick=False)
def test_validate_event_variants_no_exposure(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(feature_flag=feature_flag)
diff --git a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
index 3b816e5aa0d4..452b70dc264e 100644
--- a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
+++ b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from django.test import override_settings
@@ -39,7 +39,7 @@ class TestPrecomputationDurationGate:
start_date = None if start_offset_seconds is None else now + timedelta(seconds=start_offset_seconds)
end_date = None if end_offset_seconds is None else now + timedelta(seconds=end_offset_seconds)
- with freeze_time(now):
+ with time_machine.travel(now, tick=False):
assert experiment_has_min_runtime_for_precomputation(start_date, end_date) is expected
@@ -53,7 +53,7 @@ class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
query = ExperimentQuery(**kwargs)
return ExperimentQueryRunner(query=query, team=self.team)
- @freeze_time("2026-04-30T12:00:00Z")
+ @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
def test_team_default_skips_when_under_threshold(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -64,7 +64,7 @@ class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
runner = self._build_runner(experiment)
assert runner._should_precompute() is False
- @freeze_time("2026-04-30T12:00:00Z")
+ @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
def test_team_default_enables_when_over_threshold(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -75,7 +75,7 @@ class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
runner = self._build_runner(experiment)
assert runner._should_precompute() is True
- @freeze_time("2026-04-30T12:00:00Z")
+ @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
def test_explicit_precomputed_mode_bypasses_gate(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -86,7 +86,7 @@ class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
runner = self._build_runner(experiment, precomputation_mode=PrecomputationMode.PRECOMPUTED)
assert runner._should_precompute() is True
- @freeze_time("2026-04-30T12:00:00Z")
+ @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
def test_explicit_direct_mode_overrides_passing_gate(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -97,7 +97,7 @@ class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
runner = self._build_runner(experiment, precomputation_mode=PrecomputationMode.DIRECT)
assert runner._should_precompute() is False
- @freeze_time("2026-04-30T12:00:00Z")
+ @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
def test_team_disabled_skips_regardless_of_gate(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
@@ -154,7 +154,7 @@ class TestUncalculatedCohortGate(ExperimentQueryRunnerBaseTest):
)
assert has_uncalculated_cohorts(self.team, metric) is True
- @freeze_time("2026-04-30T12:00:00Z")
+ @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
def test_should_precompute_waits_for_first_cohort_calculation(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
diff --git a/products/experiments/backend/temporal/test_enrollment_census_logic.py b/products/experiments/backend/temporal/test_enrollment_census_logic.py
index 24e15d82039c..7fe1d2e60a28 100644
--- a/products/experiments/backend/temporal/test_enrollment_census_logic.py
+++ b/products/experiments/backend/temporal/test_enrollment_census_logic.py
@@ -2,7 +2,7 @@ import uuid
from datetime import timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -84,7 +84,7 @@ class TestEnrollmentCensusCriteria(BaseTest):
("at_cap", BUILD_LOAD_EXCLUSION_METRICS, False),
]
)
- @freeze_time("2026-01-15")
+ @time_machine.travel("2026-01-15", tick=False)
def test_build_load_cap_excludes_team_with_too_many_running_metrics(
self, _name: str, metric_count: int, expect_excluded: bool
) -> None:
@@ -117,7 +117,7 @@ class TestEnrollmentCensusCriteria(BaseTest):
report = build_census_report([small, large], window_days=14)
assert [candidate.stats.team_id for candidate in report.candidates] == [2, 1]
- @freeze_time("2026-01-15")
+ @time_machine.travel("2026-01-15", tick=False)
def test_build_load_counts_running_experiments_and_all_metric_kinds(self) -> None:
def _experiment(metrics: list[dict], **kwargs: Any) -> Experiment:
return Experiment.objects.create(
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 0d221bd9fb15..54ad5a11ee16 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -2,7 +2,7 @@ from contextlib import contextmanager
from datetime import datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -241,7 +241,7 @@ class TestRecalculationActivities(BaseTest):
("sweep_leaves_completed_at_null", False),
]
)
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_does_not_revive_a_force_failed_run(self, name: str, set_completed_at: bool):
recalc = self._recalc(self._experiment(flag_key=f"progress-start-force-failed-{name}"))
completed_at = timezone.now() if set_completed_at else None
@@ -276,7 +276,7 @@ class TestRecalculationActivities(BaseTest):
("backstop_stamps_failed", "failed"),
]
)
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_completed_does_not_revive_a_force_failed_run(self, name: str, finish_status: str):
# The staleness sweep force-fails a run with completed_at left NULL, and its workflow cancel is
# best-effort. If the workflow survives to its finish write, the tombstone must win: without the
@@ -305,7 +305,7 @@ class TestRecalculationActivities(BaseTest):
assert recalc.status == ExperimentMetricsRecalculation.Status.FAILED
assert recalc.completed_at is None
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_returns_none_when_force_failed_after_query_to_pinned(self):
# mark_started ran first and pinned query_to (run went IN_PROGRESS), then an admin force-failed it.
# A retried mark_started loses the guard, but the read-back must NOT hand back the pinned query_to as a
@@ -344,7 +344,7 @@ class TestRecalculationActivities(BaseTest):
("future_end_uses_now", 5, False),
]
)
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_query_to_is_data_window_end(self, name: str, end_date_offset_days, expect_end_date: bool):
# query_to is the data-window end (experiment_window_end), not bare now. For a stopped experiment it
# resolves to end_date — a fixed value — so reruns reuse the same result row instead of appending a
@@ -382,7 +382,7 @@ class TestRecalculationActivities(BaseTest):
(ExperimentMetricsRecalculation.Trigger.AUTO_REFRESH, False),
]
)
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_reuses_prior_window_only_for_metric_config_change(self, trigger: str, expect_reuse: bool):
# A running experiment has no end_date, so advancing triggers pin now while metric_config_change copies
# the latest completed run's query_to — the signal that keeps unchanged metrics on the cache.
@@ -411,7 +411,7 @@ class TestRecalculationActivities(BaseTest):
recalc.refresh_from_db()
assert recalc.query_to == (prior_window if expect_reuse else now)
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_reuses_partial_failure_window(self):
# A run where one metric failed is marked FAILED but stamps completed_at and holds result rows for the
# metrics that succeeded. Reuse must anchor on that newest terminal window, not fall back to an older
@@ -449,7 +449,7 @@ class TestRecalculationActivities(BaseTest):
recalc.refresh_from_db()
assert recalc.query_to == newer_partial
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_does_not_reuse_window_before_start_date(self):
# After a reset and relaunch the prior run's rows survive with a query_to from before the new start_date.
# Reusing that cutoff would begin the window before the experiment exists, so advance to now instead.
@@ -479,7 +479,7 @@ class TestRecalculationActivities(BaseTest):
recalc.refresh_from_db()
assert recalc.query_to == now
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_metric_config_change_clamps_to_end_date_when_stopped(self):
# A stopped experiment has a fixed window: even metric_config_change resolves to end_date, so a stale
# prior window (recorded before the stop) can never push the recompute window past end_date.
@@ -509,7 +509,7 @@ class TestRecalculationActivities(BaseTest):
recalc.refresh_from_db()
assert recalc.query_to == exp.end_date
- @freeze_time("2026-06-23T05:00:00Z")
+ @time_machine.travel("2026-06-23T05:00:00Z", tick=False)
def test_mark_started_metric_config_change_advances_when_no_prior_window(self):
# First metric-scoped run: nothing to reuse, so it falls back to now rather than leaving query_to unset.
now = timezone.now()
@@ -744,7 +744,7 @@ class TestCalculateActivity(BaseTest):
),
]
)
- @freeze_time("2026-05-29T13:00:00Z")
+ @time_machine.travel("2026-05-29T13:00:00Z", tick=False)
def test_transient_attempt_records_retry_state_and_success_clears_it(
self, name: str, exc: Exception, expected_error_type: str, expected_delay_seconds: int, expected_message: str
):
diff --git a/products/experiments/backend/test/test_contracts.py b/products/experiments/backend/test/test_contracts.py
index 5d54576ac35e..c94aeeabcc16 100644
--- a/products/experiments/backend/test/test_contracts.py
+++ b/products/experiments/backend/test/test_contracts.py
@@ -12,7 +12,7 @@ the experiment's feature_flag object, not here.
from datetime import UTC, datetime
import pytest
-from freezegun import freeze_time
+import time_machine
from products.experiments.backend.facade.contracts import CreateExperimentInput, Experiment, FeatureFlag
@@ -36,7 +36,7 @@ class TestContractImmutability:
with pytest.raises(AttributeError):
setattr(instance, field_name, new_value)
- @freeze_time("2026-03-21T12:00:00Z")
+ @time_machine.travel("2026-03-21T12:00:00Z", tick=False)
@pytest.mark.parametrize(
("instance", "field_name", "new_value"),
[
@@ -75,7 +75,7 @@ class TestContractImmutability:
class TestContractHashability:
"""Test that contracts are hashable (required for Turbo caching)."""
- @freeze_time("2026-03-21T12:00:00Z")
+ @time_machine.travel("2026-03-21T12:00:00Z", tick=False)
@pytest.mark.parametrize(
"instance",
[
@@ -144,61 +144,3 @@ class TestCreateExperimentInput:
assert input_dto.parameters is not None
assert "variant_notes" in input_dto.parameters
-
-
-@freeze_time("2026-03-21T12:00:00Z")
-class TestFeatureFlag:
- def test_feature_flag_output(self):
- """Test feature flag output DTO."""
- flag = FeatureFlag(
- id=123,
- key="my-flag",
- name="My Flag",
- active=True,
- created_at=datetime.now(UTC),
- )
-
- assert flag.id == 123
- assert flag.key == "my-flag"
- assert flag.name == "My Flag"
- assert flag.active is True
-
-
-@freeze_time("2026-03-21T12:00:00Z")
-class TestExperiment:
- def test_experiment_output_minimal(self):
- """Test experiment output DTO with minimal fields."""
- exp = Experiment(
- id=456,
- name="My Experiment",
- feature_flag_id=123,
- feature_flag_key="my-flag",
- is_draft=True,
- created_at=datetime.now(UTC),
- )
-
- assert exp.id == 456
- assert exp.name == "My Experiment"
- assert exp.feature_flag_id == 123
- assert exp.is_draft is True
-
- def test_experiment_output_full(self):
- """Test experiment output with all fields."""
- now = datetime.now(UTC)
- exp = Experiment(
- id=456,
- name="My Experiment",
- description="Test description",
- feature_flag_id=123,
- feature_flag_key="my-flag",
- is_draft=False,
- start_date=now,
- end_date=None,
- created_at=now,
- updated_at=now,
- )
-
- assert exp.description == "Test description"
- assert exp.is_draft is False
- assert exp.start_date == now
- assert exp.updated_at == now
diff --git a/products/experiments/backend/test/test_experiment_summary_tool.py b/products/experiments/backend/test/test_experiment_summary_tool.py
index b8c356feaf14..abfeaf23ce9f 100644
--- a/products/experiments/backend/test/test_experiment_summary_tool.py
+++ b/products/experiments/backend/test/test_experiment_summary_tool.py
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
@@ -248,7 +248,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):
metrics_secondary=[],
)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
async def test_fetch_experiment_data_with_mocked_query_runners(self):
experiment = await self.acreate_experiment(name="query-runner-test", with_metrics=True)
@@ -323,7 +323,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):
ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
async def test_fetch_experiment_data_executes_queries_on_cold_cache(self):
"""
On a cold cache, queries must execute synchronously rather than
@@ -347,7 +347,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(summary_data.pending_calculation)
self.assertIsNotNone(summary_data.last_refresh)
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
async def test_fetch_experiment_data_includes_saved_metrics(self):
experiment = await self.acreate_experiment(name="saved-metrics-test", with_metrics=False)
@@ -435,7 +435,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):
metrics_queried = [call.kwargs["query"].metric.metric_type for call in query_runner_calls]
self.assertEqual(metrics_queried, ["funnel", "funnel"])
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
async def test_fetch_experiment_data_combines_inline_and_saved_metrics(self):
experiment = await self.acreate_experiment(name="mixed-metrics-test", with_metrics=True)
# experiment.metrics already has 1 inline primary metric from acreate_experiment
@@ -542,7 +542,7 @@ class TestExperimentSummaryDataService(ClickhouseTestMixin, APIBaseTest):
# Saved mean primary (ordered first), inline funnel primary, inline funnel secondary, saved funnel secondary
self.assertEqual(metrics_queried, ["mean", "funnel", "funnel", "funnel"])
- @freeze_time("2020-01-10T12:00:00Z")
+ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)
async def test_fetch_experiment_data_reports_metrics_omitted_by_cap(self):
experiment = await self.acreate_experiment(name="metric-cap-test", with_metrics=False)
experiment.metrics = [
diff --git a/products/experiments/backend/test/test_facade.py b/products/experiments/backend/test/test_facade.py
index 6d36dec58780..431ce4cf4279 100644
--- a/products/experiments/backend/test/test_facade.py
+++ b/products/experiments/backend/test/test_facade.py
@@ -2,7 +2,7 @@
from datetime import UTC, datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from products.experiments.backend.facade import create_experiment
@@ -61,7 +61,7 @@ class TestCreateExperiment(APIBaseTest):
experiment = Experiment.objects.get(id=result.id)
assert experiment.parameters == {"variant_notes": {"control": "baseline", "test": "new checkout"}}
- @freeze_time("2025-01-01 12:00:00")
+ @time_machine.travel("2025-01-01 12:00:00", tick=False)
def test_create_experiment_with_start_date(self):
"""Test creating launched (non-draft) experiment."""
start_date = datetime(2025, 1, 1, 12, 0, 0, tzinfo=UTC)
diff --git a/products/experiments/backend/test/test_freeze_exposure_clickhouse.py b/products/experiments/backend/test/test_freeze_exposure_clickhouse.py
index 8e565e7d682d..312ff558fc2d 100644
--- a/products/experiments/backend/test/test_freeze_exposure_clickhouse.py
+++ b/products/experiments/backend/test/test_freeze_exposure_clickhouse.py
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
@@ -143,7 +143,7 @@ class TestFreezeExposureClickhouse(ClickhouseTestMixin, APIBaseTest):
("before_cutoff", True, -7, "$feature_flag_called"),
]
)
- @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10))
+ @time_machine.travel(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10), tick=False)
def test_fetch_exposed_person_uuids_reads_the_resolved_exposure_event(
self, _name: str, flag_enabled: bool, start_offset_days: int, expected_event: str
) -> None:
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 909e33e1f6ec..464c1093befb 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -4,7 +4,7 @@ from typing import Any, cast
from uuid import uuid4
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, FuzzyInt, _create_event, _create_person, flush_persons_and_events
from unittest.mock import ANY, MagicMock, patch
@@ -661,7 +661,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
)
with (
- freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=now_offset_days)),
+ time_machine.travel(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=now_offset_days), tick=False),
patch("posthoganalytics.feature_enabled", return_value=True),
):
serialized = ExperimentSerializer(
@@ -1502,7 +1502,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(response.json()["type"], "validation_error")
self.assertEqual(response.json()["detail"], "Metadata must be an object")
- @freeze_time("2025-02-10T13:00:00Z")
+ @time_machine.travel("2025-02-10T13:00:00Z", tick=False)
def test_fetching_experiment_with_stale_metric_dates_applies_experiment_date_range(self):
test_feature_flag = FeatureFlag.objects.create(
name=f"Test experiment flag",
diff --git a/products/experiments/backend/test/test_session_buckets_api.py b/products/experiments/backend/test/test_session_buckets_api.py
index 40e5b8f25b40..cce2d5e9834d 100644
--- a/products/experiments/backend/test/test_session_buckets_api.py
+++ b/products/experiments/backend/test/test_session_buckets_api.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -122,7 +122,7 @@ PURCHASE = {"kind": "EventsNode", "event": "purchase"}
SERVER_CHARGE = {"kind": "EventsNode", "event": "server charge"}
-@freeze_time(NOW)
+@time_machine.travel(NOW, tick=False)
class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
def setUp(self) -> None:
super().setUp()
@@ -536,7 +536,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
("before_cutoff", True, -7, "$feature_flag_called"),
]
)
- @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10))
+ @time_machine.travel(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10), tick=False)
def test_bucket_population_reads_the_resolved_exposure_event(
self, _name: str, flag_enabled: bool, start_offset_days: int, expected_event: str
) -> None:
@@ -585,7 +585,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
assert other_flag_session not in response.json()["session_ids"]
assert response.json()["used_exposure_fallback"] is False
- @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10))
+ @time_machine.travel(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10), tick=False)
def test_rollout_exposure_event_captured_server_side_keeps_the_stamped_property_fallback(self) -> None:
self.client.force_login(self.user)
experiment = self._create_experiment(
diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.py
index 252432ddcc84..a3d6f7cd8ed9 100644
--- a/products/experiments/backend/test/test_session_context_api.py
+++ b/products/experiments/backend/test/test_session_context_api.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -63,7 +63,7 @@ def _hogql_table_tree(node: TableNode) -> dict[str, Any]:
}
-@freeze_time("2026-01-02T12:00:00Z")
+@time_machine.travel("2026-01-02T12:00:00Z", tick=False)
class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):
def setUp(self) -> None:
super().setUp()
diff --git a/products/experiments/backend/test/test_session_event_deltas_api.py b/products/experiments/backend/test/test_session_event_deltas_api.py
index a3e36620569b..fd83b5b86544 100644
--- a/products/experiments/backend/test/test_session_event_deltas_api.py
+++ b/products/experiments/backend/test/test_session_event_deltas_api.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
@@ -72,7 +72,7 @@ def rank_anything(test: Any) -> Any:
return test
-@freeze_time(NOW)
+@time_machine.travel(NOW, tick=False)
class TestExperimentSessionEventDeltas(ClickhouseTestMixin, APILicensedTest):
def setUp(self) -> None:
super().setUp()
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index a9036a3f315b..4d6c09d5f46b 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from typing import Literal, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_events
from unittest.mock import ANY, AsyncMock, patch
@@ -354,7 +354,7 @@ class TestExports(APIBaseTest):
@patch("products.exports.backend.tasks.image_exporter._export_to_png")
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_can_create_new_valid_export_insight(self, mock_exporter_task, mock_export_to_png) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/exports",
@@ -840,7 +840,7 @@ class TestExports(APIBaseTest):
self.assertIn(ordinary_export.id, {result["id"] for result in list_response.json()["results"]})
def test_list_shows_stuck_exports_as_failed_in_response(self) -> None:
- with freeze_time(now() - timedelta(seconds=2 * HOGQL_INCREASED_MAX_EXECUTION_TIME)):
+ with time_machine.travel(now() - timedelta(seconds=2 * HOGQL_INCREASED_MAX_EXECUTION_TIME), tick=False):
# Create an export that's older than HOGQL_INCREASED_MAX_EXECUTION_TIME
stuck_export = ExportedAsset.objects.create(
team=self.team,
@@ -969,7 +969,7 @@ class TestExports(APIBaseTest):
age: timedelta,
expected_failed: bool,
) -> None:
- with freeze_time(now() - age):
+ with time_machine.travel(now() - age, tick=False):
export = ExportedAsset.objects.create(
team=self.team,
export_format=export_format,
@@ -990,7 +990,7 @@ class TestExports(APIBaseTest):
stays incomplete, so the count reflects how often clients poll rather than how many exports
failed.
"""
- with freeze_time(now() - RASTERIZE_WORKFLOW_TIMEOUT - timedelta(minutes=1)):
+ with time_machine.travel(now() - RASTERIZE_WORKFLOW_TIMEOUT - timedelta(minutes=1), tick=False):
ExportedAsset.objects.create(
team=self.team,
export_format=ExportedAsset.ExportFormat.MP4,
@@ -1005,7 +1005,7 @@ class TestExports(APIBaseTest):
self.assertEqual([call for call in mock_capture.call_args_list if "export" in str(call)], [])
def test_retrieve_shows_stuck_export_as_failed_in_response(self) -> None:
- with freeze_time(now() - timedelta(seconds=2 * HOGQL_INCREASED_MAX_EXECUTION_TIME)):
+ with time_machine.travel(now() - timedelta(seconds=2 * HOGQL_INCREASED_MAX_EXECUTION_TIME), tick=False):
# Create an export that's older than HOGQL_INCREASED_MAX_EXECUTION_TIME
stuck_export = ExportedAsset.objects.create(
team=self.team,
@@ -1630,7 +1630,7 @@ class TestExports(APIBaseTest):
@patch("products.exports.backend.api.exports.async_to_sync")
@patch("products.exports.backend.api.exports.async_connect")
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_video_export_limit_resets_monthly(self, mock_async_connect, mock_async_to_sync) -> None:
"""Test that the video export limit resets at the beginning of each month"""
@@ -1656,7 +1656,7 @@ class TestExports(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
# Move to February 1st
- with freeze_time("2024-02-01T12:00:00Z"):
+ with time_machine.travel("2024-02-01T12:00:00Z", tick=False):
# Should succeed in February (limit reset)
response = self.client.post(
f"/api/projects/{self.team.id}/exports",
diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.py
index 7821dce21407..b3e0c27d4694 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter.py
@@ -5,7 +5,7 @@ from io import BytesIO
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, _create_event, _create_person, flush_persons_and_events
from unittest import mock
from unittest.mock import ANY, MagicMock, Mock, patch
@@ -1035,7 +1035,7 @@ class TestCSVExporter(APIBaseTest):
def test_csv_exporter_trends_actors(
self,
) -> None:
- with freeze_time("2022-06-01T12:00:00.000Z"):
+ with time_machine.travel("2022-06-01T12:00:00.000Z", tick=False):
_create_person(distinct_ids=[f"user_1"], team=self.team, uuid="725f10a7-26dd-fa38-f973-757866a10ad4")
events_by_person = {
@@ -1104,7 +1104,7 @@ class TestCSVExporter(APIBaseTest):
def test_csv_exporter_trends_query_with_formula(
self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10
) -> None:
- with freeze_time("2024-05-15T12:00:00.000Z"):
+ with time_machine.travel("2024-05-15T12:00:00.000Z", tick=False):
_create_person(distinct_ids=["formula_test_user_xyz"], team=self.team)
events_by_person = {
@@ -1161,7 +1161,7 @@ class TestCSVExporter(APIBaseTest):
def test_csv_exporter_trends_query_with_formula_and_single_breakdown(
self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10
) -> None:
- with freeze_time("2024-06-10T12:00:00.000Z"):
+ with time_machine.travel("2024-06-10T12:00:00.000Z", tick=False):
_create_person(distinct_ids=["breakdown_user_single"], team=self.team)
_create_event(
@@ -1239,7 +1239,7 @@ class TestCSVExporter(APIBaseTest):
def test_csv_exporter_trends_query_with_formula_and_multiple_breakdowns(
self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10
) -> None:
- with freeze_time("2024-07-20T12:00:00.000Z"):
+ with time_machine.travel("2024-07-20T12:00:00.000Z", tick=False):
_create_person(distinct_ids=["multi_breakdown_user_1"], team=self.team)
_create_person(distinct_ids=["multi_breakdown_user_2"], team=self.team)
@@ -1330,7 +1330,7 @@ class TestCSVExporter(APIBaseTest):
@patch("products.exports.backend.models.exported_asset.UUIDT")
def test_csv_exporter_trends_with_breakdown(self, mocked_uuidt: Any) -> None:
- with freeze_time("2025-05-22T12:00:00.000Z"):
+ with time_machine.travel("2025-05-22T12:00:00.000Z", tick=False):
_create_person(distinct_ids=["user_1"], team=self.team)
_create_person(distinct_ids=["user_2"], team=self.team)
@@ -1400,7 +1400,7 @@ class TestCSVExporter(APIBaseTest):
@patch("products.exports.backend.models.exported_asset.UUIDT")
def test_csv_exporter_trends_with_breakdown_and_action(self, mocked_uuidt: Any) -> None:
- with freeze_time("2025-05-22T12:00:00.000Z"):
+ with time_machine.travel("2025-05-22T12:00:00.000Z", tick=False):
_create_person(distinct_ids=["user_1"], team=self.team)
_create_person(distinct_ids=["user_2"], team=self.team)
diff --git a/products/exports/backend/tests/test_exported_asset_model.py b/products/exports/backend/tests/test_exported_asset_model.py
index e8aec591b68d..d156b9b4d7c9 100644
--- a/products/exports/backend/tests/test_exported_asset_model.py
+++ b/products/exports/backend/tests/test_exported_asset_model.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from tempfile import NamedTemporaryFile
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -62,14 +62,14 @@ class TestExportedAssetModel(APIBaseTest):
assert list(ExportedAsset.objects_including_ttl_deleted.filter(id=asset.id)) == [asset]
def test_exported_asset_outside_ttl_is_not_visible_to_both_managers(self) -> None:
- with freeze_time("2021-01-01T12:00:00Z") as frozen_time:
+ with time_machine.travel("2021-01-01T12:00:00Z", tick=False) as frozen_time:
asset = ExportedAsset.objects.create(
team=self.team,
created_by=self.user,
expires_after=datetime.now() + timedelta(seconds=100),
)
- frozen_time.tick(delta=timedelta(seconds=101))
+ frozen_time.shift(timedelta(seconds=101))
assert list(ExportedAsset.objects.filter(id=asset.id)) == []
assert list(ExportedAsset.objects_including_ttl_deleted.filter(id=asset.id)) == [asset]
@@ -124,7 +124,7 @@ class TestExportedAssetExpiresAfter(APIBaseTest):
(ExportedAsset.ExportFormat.JSONL, SEVEN_DAYS),
]
)
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_auto_sets_expires_after_based_on_format(self, export_format: str, expected_delta: timedelta) -> None:
asset = ExportedAsset.objects.create(
team=self.team,
@@ -136,7 +136,7 @@ class TestExportedAssetExpiresAfter(APIBaseTest):
)
assert asset.expires_after == expected_expiry
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_respects_explicit_expires_after(self) -> None:
custom_expiry = datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC)
asset = ExportedAsset.objects.create(
@@ -147,7 +147,7 @@ class TestExportedAssetExpiresAfter(APIBaseTest):
assert asset.expires_after == custom_expiry
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_partial_save_does_not_overwrite_existing_expires_after(self) -> None:
custom_expiry = datetime(2025, 12, 22, 0, 0, 0, tzinfo=UTC)
asset = ExportedAsset.objects.create(
@@ -162,7 +162,7 @@ class TestExportedAssetExpiresAfter(APIBaseTest):
asset.refresh_from_db()
assert asset.expires_after == custom_expiry
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_explicitly_updating_expires_after_field(self) -> None:
custom_expiry = datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC)
asset = ExportedAsset.objects.create(
@@ -180,7 +180,7 @@ class TestExportedAssetExpiresAfter(APIBaseTest):
class TestExportedAssetFilename(APIBaseTest):
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_filename_includes_timestamp(self) -> None:
asset = ExportedAsset.objects.create(
team=self.team,
@@ -188,7 +188,7 @@ class TestExportedAssetFilename(APIBaseTest):
)
assert asset.filename == "export-2024-06-15-103000.csv"
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_filename_uses_custom_name_with_timestamp(self) -> None:
asset = ExportedAsset.objects.create(
team=self.team,
@@ -197,7 +197,7 @@ class TestExportedAssetFilename(APIBaseTest):
)
assert asset.filename == "my-cohort-name-2024-06-15-103000.csv"
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_filename_slugifies_special_characters(self) -> None:
asset = ExportedAsset.objects.create(
team=self.team,
@@ -212,7 +212,7 @@ class TestExportedAssetFilename(APIBaseTest):
(ExportedAsset.ExportFormat.JSONL, "jsonl"),
]
)
- @freeze_time("2024-06-15T10:30:00Z")
+ @time_machine.travel("2024-06-15T10:30:00Z", tick=False)
def test_tabular_format_extension(self, export_format: str, expected_extension: str) -> None:
asset = ExportedAsset.objects.create(
team=self.team,
diff --git a/products/exports/backend/tests/test_stuck_exports.py b/products/exports/backend/tests/test_stuck_exports.py
index edc26d052ffb..255fa421bf56 100644
--- a/products/exports/backend/tests/test_stuck_exports.py
+++ b/products/exports/backend/tests/test_stuck_exports.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -30,7 +30,7 @@ class TestFailStuckVideoExports(APIBaseTest):
"created_by": self.user,
}
fields.update(overrides)
- with freeze_time(now() - age):
+ with time_machine.travel(now() - age, tick=False):
return ExportedAsset.objects.create(**fields)
def test_fails_a_video_export_whose_workflow_never_reported_back(self) -> None:
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 837668a8b2be..13729df4235f 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
import pytest
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -1013,7 +1013,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
response.json()["detail"], "groups[0].properties[0].group_type_index: A valid integer is required."
)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_create_feature_flag(self, mock_report_user_action):
response = self.client.post(
@@ -1736,7 +1736,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -1745,7 +1745,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -1876,7 +1876,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_updating_feature_flag_partial(self, mock_report_user_action):
# Test that we can update a feature flag with only some of the fields
# And the unchanged fields are not updated
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{
@@ -1906,7 +1906,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -1923,7 +1923,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_with_different_user(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
# Create flag with original user
original_user = self.user
response = self.client.post(
@@ -1934,7 +1934,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Create and login as different user
different_user = User.objects.create_and_join(self.organization, "[email protected]", None)
@@ -1956,7 +1956,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_fails_concurrency_check_when_version_outdated(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
# Create flag with original user: version 0
original_user = self.user
response = self.client.post(
@@ -1972,7 +1972,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(feature_flag.version, 1)
self.assertEqual(feature_flag.last_modified_by, original_user)
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Create and login as different user
different_user = User.objects.create_and_join(self.organization, "[email protected]", None)
@@ -2042,7 +2042,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
):
# If another users saves changes, but my changes don't conflict with those changes,
# then we should not fail the concurrency check
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
# Create flag with original user: version 0
original_user = self.user
response = self.client.post(
@@ -2075,7 +2075,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flag_id = response.json()["id"]
original_version = response.json()["version"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Create and login as different user
different_user = User.objects.create_and_join(self.organization, "[email protected]", None)
@@ -2155,7 +2155,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_does_not_fail_when_version_not_in_request(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
data={"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -2164,7 +2164,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
flag_id = response.json()["id"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -2476,7 +2476,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
client.delete(f"posthog:remote_config_requests:{self.team.pk}")
client.delete(f"posthog:decide_requests:{self.team.pk}")
- with freeze_time("2022-05-07 12:23:07"):
+ with time_machine.travel("2022-05-07 12:23:07", tick=False):
for _ in range(3):
response = self.client.get(
f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",
@@ -2974,7 +2974,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_treats_null_version_as_zero(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
data={"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -2985,7 +2985,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
feature_flag = FeatureFlag.objects.get(id=flag_id)
feature_flag.version = None
feature_flag.save()
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -3000,7 +3000,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_key(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -3010,7 +3010,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flag_id = response.json()["id"]
self._generate_usage_dashboard(flag_id)
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Assert that the insights were created properly.
feature_flag = FeatureFlag.objects.get(id=flag_id)
@@ -3185,7 +3185,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_key_does_not_update_insight_with_changed_description(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -3195,7 +3195,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flag_id = response.json()["id"]
self._generate_usage_dashboard(flag_id)
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Assert that the insights were created properly.
feature_flag = FeatureFlag.objects.get(id=flag_id)
@@ -3275,7 +3275,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_key_does_not_update_insight_with_changed_filter(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -3285,7 +3285,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flag_id = response.json()["id"]
self._generate_usage_dashboard(flag_id)
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Assert that the insights were created properly.
feature_flag = FeatureFlag.objects.get(id=flag_id)
@@ -3365,7 +3365,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_updating_feature_flag_key_does_not_update_insight_with_removed_filter(self, mock_report_user_action):
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "original name", "key": "a-feature-flag-that-is-updated"},
@@ -3375,7 +3375,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flag_id = response.json()["id"]
self._generate_usage_dashboard(flag_id)
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
# Assert that the insights were created properly.
feature_flag = FeatureFlag.objects.get(id=flag_id)
@@ -3474,7 +3474,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.client.force_login(new_user)
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
create_response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "feature flag with activity", "key": "feature_with_activity"},
@@ -3483,7 +3483,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
flag_id = create_response.json()["id"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
update_response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -3569,7 +3569,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.client.force_login(new_user)
- with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:
+ with time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) as frozen_datetime:
create_response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
{"name": "feature flag with activity", "key": "feature_with_activity"},
@@ -3578,7 +3578,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
flag_id = create_response.json()["id"]
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
update_response = self.client.patch(
f"/api/projects/{self.team.id}/feature_flags/{flag_id}",
@@ -3590,7 +3590,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
- frozen_datetime.tick(delta=timedelta(minutes=10))
+ frozen_datetime.shift(timedelta(minutes=10))
second_create_response = self.client.post(
f"/api/projects/{self.team.id}/feature_flags/",
@@ -5068,7 +5068,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
"Shows the number of unique group calls made on feature flag per variant with key: renamed-group-feature",
)
- @freeze_time("2021-08-25T22:09:14.252Z")
+ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
@patch("products.feature_flags.backend.api.feature_flag.report_user_action")
def test_dashboard_enrichment_fails_if_already_enriched(self, mock_report_user_action):
response = self.client.post(
@@ -5367,7 +5367,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.client.logout()
# `local_evaluation` is called by logged out clients!
- with freeze_time("2022-05-07 12:23:07"):
+ with time_machine.travel("2022-05-07 12:23:07", tick=False):
# missing API key
response = self.client.get(f"/api/feature_flag?token={self.team.api_token}")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
@@ -7180,7 +7180,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_get_flags_with_stale_filter(self):
# Create a stale flag (100% rollout with no properties and 30+ days old)
# No last_called_at so it falls back to config-based staleness detection
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7200,7 +7200,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
# Create another non-stale flag (old but not 100% rollout)
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
partial_flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7212,7 +7212,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
partial_flag.save()
# Create a non-stale flag (100% rollout but has properties)
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
filtered_flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7238,7 +7238,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
filtered_flag.save()
# Create a non-stale flag (100% rollout but has multiple groups, with only 1 group that has 100% rollout)
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
multi_group_flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7284,7 +7284,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_get_flags_with_stale_filter_multivariate(self):
# Create a stale multivariate flag (no last_called_at so it falls back to config-based detection)
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7302,7 +7302,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
# Create a non-stale multivariate flag (no variant at 100%)
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
active_flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7331,7 +7331,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_get_flags_with_stale_filter_multivariate_condition_variant_override(self):
# Create a stale multivariate flag (no last_called_at so it falls back to config-based detection)
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7350,7 +7350,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
# Create a multivariate flag with rollout <100% should not be stale
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
low_rollout_flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7371,7 +7371,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
low_rollout_flag.save()
# Create a multivariate flag with rollout 100% but has properties filter, should not be stale
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
with_props_flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7416,7 +7416,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
# Regression test: flags created via frontend have explicit multivariate: null
# The SQL filter should handle both missing key AND explicit null value
# No last_called_at so it falls back to config-based detection
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7476,7 +7476,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
]
)
def test_get_flags_with_stale_filter_jsonb_edge_cases(self, flag_key, flag_filters, expect_stale):
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -7601,7 +7601,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(len(response_json["analytics_dashboards"]), 1)
- @freeze_time("2021-01-01")
+ @time_machine.travel("2021-01-01", tick=False)
@snapshot_clickhouse_queries
@patch("posthog.api.cohort.batch_evaluate_flag_for_team")
def test_creating_static_cohort(self, mock_batch_evaluate):
@@ -9866,7 +9866,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(set(affected), {"org:0", "org:1", "org:2", "org:3"})
- @freeze_time("2024-01-11")
+ @time_machine.travel("2024-01-11", tick=False)
def test_user_blast_radius_with_relative_date_filters(self):
for i in range(8):
_create_person(
diff --git a/products/feature_flags/backend/test/test_feature_flag_sync.py b/products/feature_flags/backend/test/test_feature_flag_sync.py
index 9f55c514f396..cbcd54f6488a 100644
--- a/products/feature_flags/backend/test/test_feature_flag_sync.py
+++ b/products/feature_flags/backend/test/test_feature_flag_sync.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, Mock, patch
@@ -61,7 +61,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
cache.clear()
super().tearDown()
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_no_events_updates_checkpoint(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -80,7 +80,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
self.flag1.refresh_from_db()
assert self.flag1.last_called_at is None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_existing_checkpoint_used(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -100,7 +100,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
params = call_args[0][1]
assert params["last_sync_timestamp"] == checkpoint_time
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_updates_null_timestamps(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -118,7 +118,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
self.flag1.refresh_from_db()
assert self.flag1.last_called_at == latest_timestamp
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_updates_only_more_recent_timestamps(
@@ -148,7 +148,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
# flag3 should be updated
assert self.flag3.last_called_at == newer_timestamp
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_handles_nonexistent_flags(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -168,7 +168,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
self.flag1.refresh_from_db()
assert self.flag1.last_called_at is not None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_skips_flag_keys_with_nul_bytes(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -187,7 +187,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
self.flag1.refresh_from_db()
assert self.flag1.last_called_at is not None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
@override_settings(FEATURE_FLAG_LAST_CALLED_AT_SYNC_BATCH_SIZE=2)
@@ -234,7 +234,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
assert flag4.last_called_at == timestamp
assert flag5.last_called_at == timestamp
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_redis_error_falls_back_to_lookback_days(
@@ -258,7 +258,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
assert last_sync.month == 6
assert last_sync.day == 14
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.tasks.tasks.get_client")
def test_concurrent_execution_prevented(self, mock_get_client: MagicMock) -> None:
"""Only one instance should execute at a time due to lock"""
@@ -273,7 +273,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
# Task should exit early without executing query
mock_sync_execute.assert_not_called()
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_lock_released_after_execution(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -288,7 +288,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
# Lock should be deleted
assert cache.get(lock_key) is None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_lock_released_after_exception(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -305,7 +305,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
# Lock should be deleted
assert cache.get(lock_key) is None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_handles_invalid_timestamps(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -328,7 +328,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
self.flag2.refresh_from_db()
assert self.flag2.last_called_at is not None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_checkpoint_updated_to_current_sync_timestamp(
@@ -356,7 +356,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
assert "2024-06-15" in stored_timestamp
assert "2024-06-15T11:59:00" in stored_timestamp
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
@override_settings(FEATURE_FLAG_LAST_CALLED_AT_SYNC_CLICKHOUSE_LIMIT=2)
@@ -373,7 +373,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):
params = call_args[0][1]
assert params["limit"] == 2
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_handles_naive_datetimes_from_clickhouse(
@@ -425,7 +425,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
cache.clear()
super().tearDown()
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_chunking_splits_large_window(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -452,7 +452,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
params = call[0][1]
assert params["last_sync_timestamp"] == expected_starts[i], f"Chunk {i} start mismatch"
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_checkpoint_stops_at_first_failed_chunk(
@@ -490,7 +490,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
stored = redis_mock.storage.get(checkpoint_key)
assert stored == tz.make_aware(datetime(2024, 6, 15, 11, 50, 0)).isoformat()
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_every_chunk_failing_raises_and_leaves_checkpoint(
@@ -515,7 +515,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
assert mock_sync_execute.call_count == 1
assert redis_mock.storage.get(checkpoint_key) == checkpoint_time.isoformat().encode()
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_transient_error_propagates_instead_of_being_tolerated(
@@ -548,7 +548,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
self.flag1.refresh_from_db()
assert self.flag1.last_called_at is None
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_max_lookback_caps_stale_checkpoint(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -569,7 +569,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
expected_cap = tz.make_aware(datetime(2024, 6, 15, 6, 0, 0))
assert first_start == expected_cap
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_merges_results_across_chunks(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
@@ -598,7 +598,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
self.flag1.refresh_from_db()
assert self.flag1.last_called_at == later_ts
- @freeze_time("2024-06-15 12:00:00")
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
@patch("posthog.clickhouse.client.sync_execute")
@patch("posthog.tasks.tasks.get_client")
def test_all_none_timestamps_skips_pg_query(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:
diff --git a/products/growth/backend/api/test_product_push.py b/products/growth/backend/api/test_product_push.py
index 689d86a07bb9..502887e2d019 100644
--- a/products/growth/backend/api/test_product_push.py
+++ b/products/growth/backend/api/test_product_push.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.utils import timezone
@@ -29,7 +29,7 @@ class TestProductPushCampaignAPI(APIBaseTest):
assert response.status_code == status.HTTP_204_NO_CONTENT
- @freeze_time("2026-07-03T12:00:00Z")
+ @time_machine.travel("2026-07-03T12:00:00Z", tick=False)
def test_active_returns_the_running_campaign_with_resolved_product_path(self) -> None:
started_at = timezone.now() - timedelta(days=3)
campaign = ProductPushCampaign.objects.create(
@@ -50,7 +50,7 @@ class TestProductPushCampaignAPI(APIBaseTest):
assert data["reason_text"] == "Watch real sessions."
assert data["product_path"]
- @freeze_time("2026-07-03T12:00:00Z")
+ @time_machine.travel("2026-07-03T12:00:00Z", tick=False)
def test_campaign_is_hidden_in_projects_that_already_use_the_product(self) -> None:
started_at = timezone.now() - timedelta(days=3)
ProductPushCampaign.objects.create(
@@ -71,7 +71,7 @@ class TestProductPushCampaignAPI(APIBaseTest):
assert self.client.get(self._url() + "?team_id=99999999").status_code == status.HTTP_404_NOT_FOUND
assert self.client.get(self._url() + "?team_id=nope").status_code == status.HTTP_400_BAD_REQUEST
- @freeze_time("2026-07-03T12:00:00Z")
+ @time_machine.travel("2026-07-03T12:00:00Z", tick=False)
def test_restricted_team_returns_404_same_as_nonexistent(self) -> None:
"""Inaccessible teams should be indistinguishable from nonexistent ones."""
if AccessControl is None:
@@ -108,7 +108,7 @@ class TestProductPushCampaignAPI(APIBaseTest):
"Restricted teams should return 404, same as nonexistent teams"
)
- @freeze_time("2026-07-03T12:00:00Z")
+ @time_machine.travel("2026-07-03T12:00:00Z", tick=False)
def test_non_member_cannot_read_another_orgs_campaign(self) -> None:
other_organization = Organization.objects.create(name="other")
ProductPushCampaign.objects.create(
diff --git a/products/growth/dags/tests/test_oauth.py b/products/growth/dags/tests/test_oauth.py
index 0a9c445b6d9c..b5408b42cb18 100644
--- a/products/growth/dags/tests/test_oauth.py
+++ b/products/growth/dags/tests/test_oauth.py
@@ -1,7 +1,7 @@
from datetime import timedelta
+import time_machine
import unittest.mock
-from freezegun import freeze_time
from django.db.models import Q
from django.test import TestCase, override_settings
@@ -35,7 +35,7 @@ class TestOAuthTokenCleanup(TestCase):
algorithm="RS256",
)
- @freeze_time("2023-01-15 02:00:00")
+ @time_machine.travel("2023-01-15 02:00:00", tick=False)
def test_oauth_cleanup_job_with_real_tokens(self):
expired_time = timezone.now() - timedelta(days=95) # Beyond retention period
OAuthAccessToken.objects.create(
diff --git a/products/growth/dags/tests/test_team_production_event_activation.py b/products/growth/dags/tests/test_team_production_event_activation.py
index 326bf80ff479..cc8ddd919ff8 100644
--- a/products/growth/dags/tests/test_team_production_event_activation.py
+++ b/products/growth/dags/tests/test_team_production_event_activation.py
@@ -2,7 +2,7 @@ from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import MagicMock, patch
@@ -55,7 +55,7 @@ class TestDetectFirstTeamProductionEventJob(ClickhouseTestMixin, BaseTest):
def test_qualifying_team_is_flagged(self) -> None:
_seed_event(self.team.id, host="app.example.com")
- with freeze_time("2026-06-05T12:00:00Z"), _mock_capture():
+ with time_machine.travel("2026-06-05T12:00:00Z", tick=False), _mock_capture():
result = detect_first_team_production_event_job.execute_in_process()
self.assertTrue(result.success)
@@ -69,7 +69,7 @@ class TestDetectFirstTeamProductionEventJob(ClickhouseTestMixin, BaseTest):
def test_non_qualifying_team_only_gets_last_checked_at_bumped(self) -> None:
_seed_event(self.team.id, host="localhost:3000")
- with freeze_time("2026-06-05T12:00:00Z"):
+ with time_machine.travel("2026-06-05T12:00:00Z", tick=False):
result = detect_first_team_production_event_job.execute_in_process()
self.assertTrue(result.success)
diff --git a/products/live_debugger/backend/test_models.py b/products/live_debugger/backend/test_models.py
index a7b60e9e436e..8372447ae5be 100644
--- a/products/live_debugger/backend/test_models.py
+++ b/products/live_debugger/backend/test_models.py
@@ -1,7 +1,7 @@
import uuid
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin
from posthog.models.event.util import bulk_create_events
@@ -189,7 +189,7 @@ class TestLiveDebuggerBreakpointModel(ClickhouseTestMixin, BaseTest):
now = datetime.now()
# Create event from 30 minutes ago (should be included)
- with freeze_time(now - timedelta(minutes=30)):
+ with time_machine.travel(now - timedelta(minutes=30), tick=False):
bulk_create_events(
[
{
@@ -210,7 +210,7 @@ class TestLiveDebuggerBreakpointModel(ClickhouseTestMixin, BaseTest):
)
# Create event from 2 hours ago (should be excluded)
- with freeze_time(now - timedelta(hours=2)):
+ with time_machine.travel(now - timedelta(hours=2), tick=False):
bulk_create_events(
[
{
diff --git a/products/logs/backend/test/test_alert_check_query.py b/products/logs/backend/test/test_alert_check_query.py
index 0a69437fe1ae..f42c095f3b86 100644
--- a/products/logs/backend/test/test_alert_check_query.py
+++ b/products/logs/backend/test/test_alert_check_query.py
@@ -5,7 +5,7 @@ import datetime as dt
from datetime import UTC, datetime
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -212,7 +212,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
date_to=datetime(2025, 12, 16, 10, 33, 0, tzinfo=UTC),
)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_projection_path_service_severity_only(self):
alert = self._make_alert(
filters={
@@ -226,7 +226,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert result.count > 0
assert result.query_duration_ms >= 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_projection_path_service_only(self):
alert = self._make_alert(
filters={
@@ -237,14 +237,14 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, AlertCheckCountResult)
assert result.count == 100
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_empty_filters_returns_all_logs(self):
alert = self._make_alert(filters={})
result = self._make_query(alert).execute()
assert isinstance(result, AlertCheckCountResult)
assert result.count > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_null_filter_values_treated_as_empty(self):
# The frontend/API can persist explicit `null` for these keys (as opposed to
# omitting them), which previously crashed every check with a pydantic
@@ -255,7 +255,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, AlertCheckCountResult)
assert result.count > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_raw_scan_path_body_filter(self):
alert = self._make_alert(
filters={
@@ -282,7 +282,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, AlertCheckCountResult)
assert result.count > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_raw_scan_path_resource_attribute_filter(self):
alert = self._make_alert(
filters={
@@ -308,7 +308,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, AlertCheckCountResult)
assert result.count > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_raw_scan_path_log_attribute_filter(self):
# log_attribute filters read the `attributes_map_str` Map column. This only happens with
# propertyGroupsMode=OPTIMIZED; without it the read falls back to JSONExtract, which is
@@ -337,7 +337,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, AlertCheckCountResult)
assert result.count > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_empty_results_return_zero(self):
alert = self._make_alert(
filters={
@@ -348,7 +348,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, AlertCheckCountResult)
assert result.count == 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_output(self):
alert = self._make_alert(
filters={
@@ -365,7 +365,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
timestamps = [item.timestamp for item in result]
assert timestamps == sorted(timestamps)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_empty_results(self):
alert = self._make_alert(
filters={
@@ -375,7 +375,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
result = self._make_query(alert).execute_bucketed(interval_minutes=5)
assert result == []
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_output_with_body_filter(self):
alert = self._make_alert(
filters={
@@ -403,7 +403,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
total = sum(item.count for item in result)
assert total > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_projection_path(self):
alert = self._make_alert(
filters={
@@ -415,7 +415,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, list)
assert len(result) > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_raw_scan_path(self):
alert = self._make_alert(
filters={
@@ -442,7 +442,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert isinstance(result, list)
assert len(result) > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_count_placement(self):
# Seeds five logs at known timestamps spanning two 5-min buckets
# ([10:00, 10:05) and [10:05, 10:10)) and asserts the per-bucket counts
@@ -488,7 +488,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert bucket_a.timestamp.replace(tzinfo=UTC) == datetime(2025, 12, 16, 10, 0, 0, tzinfo=UTC)
assert bucket_b.timestamp.replace(tzinfo=UTC) == datetime(2025, 12, 16, 10, 5, 0, tzinfo=UTC)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_sum_equals_single_count(self):
# Same WHERE clause, same date range, just GROUP BY in one path. If any
# rows fall through bucket boundaries (e.g. a half-open interval bug
@@ -501,7 +501,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert sum(b.count for b in bucketed) == single.count
- @freeze_time("2025-12-16T11:00:00Z")
+ @time_machine.travel("2025-12-16T11:00:00Z", tick=False)
def test_bucketed_count_matches_python_histogram_across_random_inputs(self):
# Stress test the actual ClickHouse bucketing: seed N logs at random
# timestamps with a unique service name, run execute_bucketed, then
@@ -567,7 +567,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
f"expected: {sorted(expected.items())}"
)
- @freeze_time("2025-12-17T01:00:00Z")
+ @time_machine.travel("2025-12-17T01:00:00Z", tick=False)
def test_bucketed_count_correct_across_midnight_boundary(self):
# Cadence-grid bucketing anchors at midnight UTC — buckets that span
# the day rollover must land in the right slot.
@@ -611,7 +611,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
}
assert actual == expected
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_subsecond_precision_at_boundaries(self):
# DateTime64(6) precision: a log at :04:59.999999 is in [10:00, 10:05);
# one at :05:00.000000 is in [10:05, 10:10). Boundary ownership matters
@@ -653,7 +653,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
}
assert actual == expected
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_excludes_log_at_exact_date_to(self):
# Half-open [date_from, date_to) — a log timestamped exactly at date_to
# must be excluded. Catches an off-by-one if anyone changes < to <=.
@@ -690,7 +690,7 @@ class TestAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
# Only the .999999 log should be counted; the .000000 log is at date_to and excluded.
assert actual == {datetime(2025, 12, 16, 10, 5, 0, tzinfo=UTC): 1}
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucketed_sparse_data_returns_only_populated_buckets(self):
# CH GROUP BY only emits buckets that have data. This is the contract
# downstream callers (the activity, the simulate fill helper) depend on:
@@ -807,7 +807,7 @@ class TestEvaluatorWindowAccuracy(ClickhouseTestMixin, APIBaseTest):
("offset_55", 55),
]
)
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_equals_1_full_window_count_is_independent_of_nca_offset(self, _name: str, offset_minutes: int):
# 1 log/min × 60-min window = 60.
self._seed_one_log_per_minute(start_hour_utc=10, hours=3)
@@ -835,7 +835,7 @@ class TestEvaluatorWindowAccuracy(ClickhouseTestMixin, APIBaseTest):
("offset_55", 55),
]
)
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_of_n_each_period_reports_full_window_count(self, _name: str, offset_minutes: int):
# 1 log/min × 3 × 20-min periods = 20 each.
self._seed_one_log_per_minute(start_hour_utc=10, hours=3)
@@ -858,7 +858,7 @@ class TestEvaluatorWindowAccuracy(ClickhouseTestMixin, APIBaseTest):
# Total across all periods = 60 logs.
assert sum(p.count for p in result) == 60
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_equals_1_steady_rate_does_not_oscillate_across_hour(self):
self._seed_one_log_per_minute(start_hour_utc=10, hours=3)
alert = self._make_alert(window_minutes=60, evaluation_periods=1)
@@ -877,7 +877,7 @@ class TestEvaluatorWindowAccuracy(ClickhouseTestMixin, APIBaseTest):
f"Per-offset counts: {counts_by_offset}"
)
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_of_n_steady_rate_does_not_oscillate_across_hour(self):
self._seed_one_log_per_minute(start_hour_utc=10, hours=3)
alert = self._make_alert(window_minutes=20, evaluation_periods=3)
@@ -911,7 +911,7 @@ class TestExecuteRollingChecks(ClickhouseTestMixin, APIBaseTest):
def _seed_per_minute(self, base: datetime, counts_per_minute: list[int]) -> None:
_seed_log_rows(self.team.id, self.SERVICE, base, counts_per_minute, "rc")
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_equals_1_returns_single_latest_window_count(self):
self._seed_per_minute(datetime(2025, 12, 16, 12, 0, tzinfo=UTC), [1, 1, 1, 1, 1])
alert = self._make_alert(window_minutes=15)
@@ -925,7 +925,7 @@ class TestExecuteRollingChecks(ClickhouseTestMixin, APIBaseTest):
assert result[0].count == 5
assert result[0].timestamp == datetime(2025, 12, 16, 12, 0, tzinfo=UTC)
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_equals_3_overlapping_windows_each_count_includes_shared_data(self):
self._seed_per_minute(datetime(2025, 12, 16, 12, 0, tzinfo=UTC), [1] * 60)
alert = self._make_alert(window_minutes=15)
@@ -944,7 +944,7 @@ class TestExecuteRollingChecks(ClickhouseTestMixin, APIBaseTest):
datetime(2025, 12, 16, 12, 15, tzinfo=UTC),
]
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_spike_is_visible_in_all_windows_that_contain_it(self):
counts = [0] * 60
for m in range(8, 13):
@@ -975,7 +975,7 @@ class TestExecuteRollingChecks(ClickhouseTestMixin, APIBaseTest):
("offset_59", 59),
]
)
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_count_is_invariant_to_nca_clock_offset(self, _name: str, offset_min: int):
self._seed_per_minute(datetime(2025, 12, 16, 10, 0, tzinfo=UTC), [1] * 180)
alert = self._make_alert(window_minutes=15)
@@ -988,7 +988,7 @@ class TestExecuteRollingChecks(ClickhouseTestMixin, APIBaseTest):
counts = [b.count for b in result]
assert counts == [15, 15, 15]
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_cadence_other_than_5min_works(self):
self._seed_per_minute(datetime(2025, 12, 16, 12, 0, tzinfo=UTC), [1] * 60)
alert = self._make_alert(window_minutes=15, check_interval_minutes=10)
@@ -1001,7 +1001,7 @@ class TestExecuteRollingChecks(ClickhouseTestMixin, APIBaseTest):
assert [b.count for b in result] == [15, 15, 15]
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_empty_results_returns_zero_for_each_period(self):
alert = self._make_alert(filters={"serviceNames": ["nonexistent"]})
nca = datetime(2025, 12, 16, 12, 30, tzinfo=UTC)
@@ -1034,7 +1034,7 @@ class TestExecuteRollingChecksBatched(ClickhouseTestMixin, APIBaseTest):
def _seed(self, service: str, base: datetime, counts_per_minute: list[int]) -> None:
_seed_log_rows(self.team.id, service, base, counts_per_minute, f"rcb-{service}")
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_per_alert_counts_match_single_alert_query(self):
base = datetime(2025, 12, 16, 12, 0, tzinfo=UTC)
self._seed(self.SERVICE_A, base, [3] * 60)
@@ -1056,7 +1056,7 @@ class TestExecuteRollingChecksBatched(ClickhouseTestMixin, APIBaseTest):
).execute_rolling_checks(nca=nca, window_minutes=15, cadence_minutes=5, period_count=3)
assert batched.per_alert[str(alert.id)] == single
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_single_alert_cohort_matches_per_alert_path(self):
base = datetime(2025, 12, 16, 12, 0, tzinfo=UTC)
self._seed(self.SERVICE_A, base, [5] * 60)
@@ -1074,7 +1074,7 @@ class TestExecuteRollingChecksBatched(ClickhouseTestMixin, APIBaseTest):
assert batched.per_alert[str(alert.id)] == single
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_m_equals_1_returns_single_period_per_alert(self):
base = datetime(2025, 12, 16, 12, 0, tzinfo=UTC)
self._seed(self.SERVICE_A, base, [2] * 60)
@@ -1129,7 +1129,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
def _date_range(self) -> tuple[datetime, datetime]:
return datetime(2025, 12, 16, 9, 0, 0, tzinfo=UTC), datetime(2025, 12, 16, 10, 33, 0, tzinfo=UTC)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_returns_per_alert_buckets(self):
alert_a = self._make_alert(name="A", filters={"serviceNames": ["argo-rollouts"]})
alert_b = self._make_alert(name="B", filters={"serviceNames": ["billing"]})
@@ -1143,7 +1143,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert set(result.per_alert.keys()) == {str(alert_a.id), str(alert_b.id)}
assert result.query_duration_ms >= 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_per_alert_counts_match_single_alert_query(self):
# Equivalence guarantee: every per-alert bucket column from the batched
# query must match what a single-alert AlertCheckQuery returns. If they
@@ -1169,7 +1169,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
non_zero_batched = [b for b in batched_for_alert if b.count > 0]
assert non_zero_batched == single, f"alert={alert.name}"
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_single_alert_cohort_is_supported(self):
# The activity sends every cohort through the batched path even when
# there's only one alert in it. Verify N=1 behaves correctly.
@@ -1184,7 +1184,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
non_zero = [b for b in result.per_alert[str(alert.id)] if b.count > 0]
assert len(non_zero) > 0
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_empty_alerts_raises(self):
date_from, date_to = self._date_range()
with self.assertRaisesRegex(ValueError, "at least one alert"):
@@ -1205,7 +1205,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
date_to=datetime(2025, 12, 16, 10, 33, 0, tzinfo=UTC),
)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_mixed_projection_eligibility_drops_to_raw_scan(self):
# If any alert in the batch has a body filter, the cohort drops projection
# eligibility — entire batch falls back to raw scan. Both columns still
@@ -1241,7 +1241,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert set(result.per_alert.keys()) == {str(alert_proj.id), str(alert_body.id)}
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_no_matching_logs_returns_zero_counts(self):
alert_a = self._make_alert(name="A", filters={"serviceNames": ["nonexistent-a"]})
alert_b = self._make_alert(name="B", filters={"serviceNames": ["nonexistent-b"]})
@@ -1258,7 +1258,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
buckets = result.per_alert[str(alert.id)]
assert all(b.count == 0 for b in buckets)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_buckets_in_ascending_order(self):
alert_a = self._make_alert(name="A", filters={"serviceNames": ["argo-rollouts"]})
alert_b = self._make_alert(name="B", filters={"serviceNames": ["billing"]})
@@ -1272,7 +1272,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
timestamps = [b.timestamp for b in result.per_alert[str(alert.id)]]
assert timestamps == sorted(timestamps), f"alert={alert.name}"
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_query_failure_propagates(self):
alert = self._make_alert()
date_from, date_to = self._date_range()
@@ -1292,7 +1292,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
("offset_55", 55),
]
)
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_execute_periods_per_alert_per_period_indexing_is_correct(self, _name: str, offset_minutes: int):
# service_a: 1 log/min. service_b: 2 logs/min. Expected: A=[20,20,20], B=[40,40,40] for any NCA offset.
rows = []
@@ -1360,7 +1360,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
f"NCA offset {offset_minutes}min: alert B per-period counts diverge from constant 40; got {b_counts}"
)
- @freeze_time("2025-12-16T11:00:00Z")
+ @time_machine.travel("2025-12-16T11:00:00Z", tick=False)
def test_per_alert_results_match_single_query_across_random_inputs(self):
# Generative property test: the batched query must produce the same
# per-alert bucket counts as running each alert through `AlertCheckQuery`
@@ -1433,7 +1433,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
f"single: {single}"
)
- @freeze_time("2025-12-16T11:00:00Z")
+ @time_machine.travel("2025-12-16T11:00:00Z", tick=False)
def test_sparse_alert_in_busy_cohort_returns_zero_counts(self):
# Multi-alert cohort where one alert has matches and one is sparse:
# confirm the sparse alert's per_alert slice contains only zeros (the
@@ -1481,7 +1481,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
assert all(b.count == 0 for b in sparse_buckets)
assert [b.timestamp for b in busy_buckets] == [b.timestamp for b in sparse_buckets]
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_excludes_log_at_exact_date_to(self):
# Half-open [date_from, date_to). A log timestamped exactly at date_to
# must be excluded for every alert in the cohort.
@@ -1522,7 +1522,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
# Only the .999999 log is counted; the .000000 log at date_to is excluded.
assert non_zero == {datetime(2025, 12, 16, 10, 5, 0, tzinfo=UTC): 1}
- @freeze_time("2025-12-17T01:00:00Z")
+ @time_machine.travel("2025-12-17T01:00:00Z", tick=False)
def test_buckets_correct_across_midnight_boundary(self):
# Cadence-grid bucketing anchors at midnight UTC — buckets that span
# the day rollover must land in the right slot in the batched path too.
@@ -1570,7 +1570,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
}
assert actual == expected
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_subsecond_precision_at_boundaries(self):
# DateTime64(6) precision: a log at :04:59.999999 belongs in [10:00, 10:05);
# one at :05:00.000000 belongs in [10:05, 10:10). Ensure batched bucket
@@ -1615,7 +1615,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
datetime(2025, 12, 16, 10, 5, 0, tzinfo=UTC): 2,
}
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_bucket_placement_matches_single_query(self):
# Targeted equivalence test: seed five logs at known timestamps that
# split across two 5-minute buckets, run batched with two alerts (one
@@ -1667,7 +1667,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
)
@parameterized.expand([("bucketed",), ("periods",), ("rolling",)])
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_heterogeneous_cohort_matches_single_alert_results(self, path: str):
# Cohort mixing a match-everything alert (its predicate is ~always true),
# a service alert, an attribute alert, and a zero-match alert. Guards the
@@ -1696,7 +1696,7 @@ class TestBatchedAlertCheckQuery(ClickhouseTestMixin, APIBaseTest):
got = [b for b in got if b.count > 0]
assert got == single, f"alert={alert.name} path={path}"
- @freeze_time("2025-12-16T13:30:00Z")
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_max_cohort_size_query_builds_and_matches(self):
# A full-size cohort duplicates every predicate into the hoisted OR
# chain on top of its countIf copy: guards the doubled predicate text
@@ -1880,7 +1880,7 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
("matches_nothing", "no-such-kind", 0),
]
)
- @freeze_time("2026-02-03T10:05:00Z")
+ @time_machine.travel("2026-02-03T10:05:00Z", tick=False)
def test_single_alert_attribute_filter_cohort_matches_per_alert_path(
self, _name: str, attr_value: str, expected_total: int
):
@@ -2005,7 +2005,7 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2026-02-03T10:05:00Z")
+ @time_machine.travel("2026-02-03T10:05:00Z", tick=False)
def test_boundary_rows_with_attribute_filter(
self, name: str, timestamps: list[str], date_from: datetime, date_to: datetime, expected_total: int
):
@@ -2061,7 +2061,7 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
("regex", "regex", "connection reset|task_crashed", 2),
]
)
- @freeze_time("2026-02-03T10:05:00Z")
+ @time_machine.travel("2026-02-03T10:05:00Z", tick=False)
def test_body_filter_alert_matches_per_alert_path(self, _name: str, operator: str, value: str, expected: int):
# Body filters are the only predicates carrying an indexHint(...). With
# the hint hoisted into the outer WHERE alongside its countIf copy,
@@ -2089,7 +2089,7 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
non_zero = [b for b in batched_bucketed.per_alert[str(alert.id)] if b.count > 0]
assert non_zero == single_bucketed
- @freeze_time("2026-02-03T10:05:00Z")
+ @time_machine.travel("2026-02-03T10:05:00Z", tick=False)
def test_body_and_resource_attribute_filter_matches_per_alert_path(self):
# The full failing shape: the body filter contributes the indexHint and
# the resource-attribute filter contributes a `resource_fingerprint IN
@@ -2141,7 +2141,7 @@ class TestBatchedQueryPredicateHoisting(ClickhouseTestMixin, APIBaseTest):
# source stream. Seeded classes can never hit it; production hits it whenever
# a shard has no matching parts for the check window.
class TestBatchedQueryPredicateHoistingEmptyScan(ClickhouseTestMixin, APIBaseTest):
- @freeze_time("2026-02-03T10:05:00Z")
+ @time_machine.travel("2026-02-03T10:05:00Z", tick=False)
def test_body_and_resource_filter_with_no_matching_logs(self):
alert = LogsAlertConfiguration.objects.create(
team=self.team,
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 366607cc3be8..99b5c8abd7ca 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
@@ -89,14 +89,14 @@ class TestLogsAlertAPI(APIBaseTest):
assert mock_report.call_args.args[2]["alert_name"] == "High error rate"
assert mock_report.call_args.args[2]["threshold_count"] == 10
- @freeze_time("2026-01-01T23:00:00Z")
+ @time_machine.travel("2026-01-01T23:00:00Z", tick=False)
def test_create_with_quiet_hours_defers_next_check(self):
data = self._create_via_api(schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]})
assert data["schedule_restriction"] == {"blocked_windows": [{"start": "22:00", "end": "07:00"}]}
assert data["next_check_at"] == "2026-01-02T07:00:00Z"
- @freeze_time("2026-01-01T23:00:00Z")
+ @time_machine.travel("2026-01-01T23:00:00Z", tick=False)
def test_update_with_quiet_hours_defers_next_check(self):
created = self._create_via_api()
@@ -110,13 +110,13 @@ class TestLogsAlertAPI(APIBaseTest):
assert response.json()["next_check_at"] == "2026-01-02T07:00:00Z"
def test_enabling_alert_during_quiet_hours_defers_next_check(self):
- with freeze_time("2026-01-01T16:00:00Z"):
+ with time_machine.travel("2026-01-01T16:00:00Z", tick=False):
created = self._create_via_api(
schedule_restriction={"blocked_windows": [{"start": "22:00", "end": "07:00"}]}
)
self.client.patch(f"{self.base_url}{created['id']}/", {"enabled": False}, format="json")
- with freeze_time("2026-01-01T23:00:00Z"):
+ with time_machine.travel("2026-01-01T23:00:00Z", tick=False):
response = self.client.patch(f"{self.base_url}{created['id']}/", {"enabled": True}, format="json")
assert response.status_code == status.HTTP_200_OK, response.json()
@@ -1652,7 +1652,7 @@ class TestLogsAlertAPI(APIBaseTest):
event.refresh_from_db()
return event
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
def test_state_timeline_single_interval_for_empty_alert(self):
created = self._create_via_api()
@@ -1669,7 +1669,7 @@ class TestLogsAlertAPI(APIBaseTest):
# 24h span, ending at "now".
assert (end - start) == timedelta(hours=24)
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
def test_state_timeline_splits_on_state_transitions(self):
created = self._create_via_api()
alert_id = created["id"]
@@ -1700,7 +1700,7 @@ class TestLogsAlertAPI(APIBaseTest):
2025, 12, 16, 8, 30, tzinfo=UTC
)
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
def test_state_timeline_collapses_same_state_checks(self):
created = self._create_via_api()
alert_id = created["id"]
@@ -1715,7 +1715,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert timeline[0]["state"] == "not_firing"
assert timeline[0]["enabled"] is True
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
def test_state_timeline_tracks_enable_disable_toggles(self):
created = self._create_via_api()
alert_id = created["id"]
@@ -1741,7 +1741,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert [i["enabled"] for i in timeline] == [True, False, True]
assert all(i["state"] == "not_firing" for i in timeline)
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
def test_state_timeline_seeds_enabled_from_pre_window_toggle(self):
created = self._create_via_api()
alert_id = created["id"]
@@ -1760,7 +1760,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert len(timeline) == 1
assert timeline[0]["enabled"] is False
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
def test_state_timeline_excludes_events_older_than_24h(self):
created = self._create_via_api()
alert_id = created["id"]
@@ -1804,7 +1804,7 @@ class TestLogsAlertAPI(APIBaseTest):
base = datetime(2025, 12, 16, 10, 0, tzinfo=UTC)
return [BucketedCount(timestamp=base + timedelta(minutes=m), count=c) for m, c in offset_counts]
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_returns_response_shape(self, mock_query_cls):
mock_query_cls.return_value.execute_bucketed.return_value = self._mock_cadence_buckets([(0, 50), (5, 20)])
@@ -1822,7 +1822,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert "state" in bucket
assert "notification" in bucket
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_fills_empty_minutes(self, mock_query_cls):
# Two data points 10 minutes apart — should fill 5-min cadence gaps between them
@@ -1855,7 +1855,7 @@ class TestLogsAlertAPI(APIBaseTest):
),
]
)
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_rolling_window(self, _name, buckets, payload_overrides, expected, mock_query_cls):
mock_query_cls.return_value.execute_bucketed.return_value = self._mock_cadence_buckets(buckets)
@@ -1871,7 +1871,7 @@ class TestLogsAlertAPI(APIBaseTest):
if "min_resolve_count" in expected:
assert data["resolve_count"] >= expected["min_resolve_count"]
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_n_of_m_delays_firing(self, mock_query_cls):
# window=5, 2-of-3 N-of-M. Cadence-spaced buckets at minute 0 and 5 each have
@@ -1899,7 +1899,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert data_buckets[1]["state"] == "firing"
assert data_buckets[1]["notification"] == "fire"
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_cooldown_suppresses_renotification(self, mock_query_cls):
# window=5, cooldown=15 min. Two spikes 10 minutes apart: first fires at minute 0,
@@ -1926,7 +1926,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert data_buckets[1]["notification"] == "none"
assert data["fire_count"] == 1
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_empty_results(self, mock_query_cls):
mock_query_cls.return_value.execute_bucketed.return_value = []
@@ -1962,7 +1962,7 @@ class TestLogsAlertAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_echoes_threshold_config(self, mock_query_cls):
mock_query_cls.return_value.execute_bucketed.return_value = self._mock_cadence_buckets([(0, 10)])
@@ -1976,7 +1976,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert data["threshold_count"] == 42
assert data["threshold_operator"] == "below"
- @freeze_time("2025-12-16T10:30:00Z")
+ @time_machine.travel("2025-12-16T10:30:00Z", tick=False)
@patch("products.logs.backend.presentation.views.alerts_api.AlertCheckQuery")
def test_simulate_rolling_window_excludes_current_bucket(self, mock_query_cls):
# Regression test: the simulator's rolling sum at bucket time T must
@@ -2061,7 +2061,7 @@ class TestSimulateEvaluatorParity(ClickhouseTestMixin, APIBaseTest):
("c10_w30_m3", 10, 30, 3),
]
)
- @freeze_time("2025-12-16T11:30:00Z")
+ @time_machine.travel("2025-12-16T11:30:00Z", tick=False)
def test_simulator_rolling_count_matches_evaluator_at_cadence_steps(
self, _name: str, cadence: int, window: int, m: int
) -> None:
@@ -2197,10 +2197,8 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):
start_nca: datetime,
end_nca: datetime,
) -> list[tuple[datetime, str]]:
- # Run the sync helpers directly rather than the async activities. The
- # async path uses `database_sync_to_async_pool`, whose thread-pool
- # dispatch loses freezegun's clock-patching for this lifecycle test.
- # The async orchestration is covered by `test_logs_alerting_workflow.py`.
+ # Run the sync helpers directly rather than the async activities, whose
+ # orchestration is covered by `test_logs_alerting_workflow.py`.
from products.logs.backend.temporal.activities import (
_cohort_from_manifest,
_discover_cohorts_sync,
@@ -2235,7 +2233,7 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):
nca = start_nca
while nca <= end_nca:
- with freeze_time(nca):
+ with time_machine.travel(nca, tick=False):
_one_cycle()
nca += timedelta(minutes=alert.check_interval_minutes)
@@ -2350,7 +2348,7 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):
start = self.BASE_TIME
end = self.BASE_TIME + timedelta(minutes=110)
- with freeze_time(end + timedelta(minutes=cadence)):
+ with time_machine.travel(end + timedelta(minutes=cadence), tick=False):
sim_events = self._run_simulator(
filters={"serviceNames": [self.service]},
threshold=100,
diff --git a/products/logs/backend/test/test_count_api.py b/products/logs/backend/test/test_count_api.py
index a46998a876f7..6479ed17db6d 100644
--- a/products/logs/backend/test/test_count_api.py
+++ b/products/logs/backend/test/test_count_api.py
@@ -1,7 +1,7 @@
import os
import json
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from parameterized import parameterized
@@ -41,7 +41,7 @@ class TestCountApi(ClickhouseTestMixin, APIBaseTest):
("empty_window", {"date_from": "2000-01-01T00:00:00Z", "date_to": "2000-01-02T00:00:00Z"}, 0),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_count_date_range(self, _name, date_range, expected):
response = self._count({"dateRange": date_range})
self.assertEqual(response["count"], expected)
@@ -54,7 +54,7 @@ class TestCountApi(ClickhouseTestMixin, APIBaseTest):
(["info", "error"], 945),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_count_severity_filter(self, severities, expected):
response = self._count({"dateRange": _FIXTURE_WINDOW, "severityLevels": severities})
self.assertEqual(response["count"], expected)
@@ -67,17 +67,17 @@ class TestCountApi(ClickhouseTestMixin, APIBaseTest):
(["nonexistent-service-xyz"], 0),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_count_service_filter(self, services, expected):
response = self._count({"dateRange": _FIXTURE_WINDOW, "serviceNames": services})
self.assertEqual(response["count"], expected)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_count_search_term_matches_body_text(self):
response = self._count({"dateRange": _FIXTURE_WINDOW, "searchTerm": "connection refused"})
self.assertEqual(response["count"], 1)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_count_defaults_date_range_to_last_hour(self):
# No dateRange in request; default should be -1h relative to frozen "now".
# Fixture's latest timestamp is 2025-12-18T02:00Z — outside the last hour.
@@ -104,7 +104,7 @@ class TestCountApi(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_count_matches_sparkline_sum(self, _name, date_range, filters):
# Cross-verify: sum of sparkline bucket counts should equal the scalar count
# for the same query. Catches drift between the two endpoints' WHERE handling.
diff --git a/products/logs/backend/test/test_count_ranges_api.py b/products/logs/backend/test/test_count_ranges_api.py
index d36c3bc9b5c4..d212dc83dfe6 100644
--- a/products/logs/backend/test/test_count_ranges_api.py
+++ b/products/logs/backend/test/test_count_ranges_api.py
@@ -3,7 +3,7 @@ import re
import json
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from parameterized import parameterized
@@ -42,7 +42,7 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, expected_status)
return response.json() if expected_status == status.HTTP_200_OK else response
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_default_target_buckets_picks_12h_interval(self):
# 5-day window / 10 target buckets => 12-hour interval (deterministic from
# the picker's "round" interval list).
@@ -61,19 +61,19 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
(50, "2h"),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_target_buckets_picks_appropriate_interval(self, target, expected_interval):
response = self._ranges({"dateRange": _FIXTURE_WINDOW, "targetBuckets": target})
self.assertEqual(response["interval"], expected_interval)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_target_buckets_above_max_is_clamped(self):
over = self._ranges({"dateRange": _FIXTURE_WINDOW, "targetBuckets": 999})
capped = self._ranges({"dateRange": _FIXTURE_WINDOW, "targetBuckets": 100})
self.assertEqual(over["interval"], capped["interval"])
self.assertEqual(len(over["ranges"]), len(capped["ranges"]))
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_empty_window_returns_no_ranges(self):
response = self._ranges(
{"dateRange": {"date_from": "2000-01-01T00:00:00Z", "date_to": "2000-01-02T00:00:00Z"}},
@@ -91,7 +91,7 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
("service_argo_rollouts_contour", "serviceNames", ["argo-rollouts", "contour"]),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_filter_sum_matches_count_endpoint(self, _name, field, value):
params = {"dateRange": _FIXTURE_WINDOW, field: value}
ranges_response = self._ranges({**params, "targetBuckets": 50})
@@ -104,7 +104,7 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(count_response.status_code, status.HTTP_200_OK)
self.assertEqual(bucket_sum, count_response.json()["count"])
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_buckets_ordered_ascending_and_aligned(self):
response = self._ranges({"dateRange": _DENSE_DAY, "targetBuckets": 24})
ranges = response["ranges"]
@@ -116,7 +116,7 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
dt_ = datetime.fromisoformat(bucket["date_to"])
self.assertGreater(dt_, df)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_bucket_timestamps_are_utc_z_suffixed(self):
ranges = self._ranges({"dateRange": _DENSE_DAY, "targetBuckets": 24})["ranges"]
self.assertGreater(len(ranges), 0)
@@ -124,7 +124,7 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(bucket["date_from"].endswith("Z"), bucket["date_from"])
self.assertTrue(bucket["date_to"].endswith("Z"), bucket["date_to"])
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_recursion_happy_path(self):
wide = self._ranges({"dateRange": _FIXTURE_WINDOW, "targetBuckets": 10})
densest = max(wide["ranges"], key=lambda b: b["count"])
@@ -140,12 +140,12 @@ class TestCountRangesApi(ClickhouseTestMixin, APIBaseTest):
self.assertLessEqual(narrow_sum, densest["count"])
self.assertGreater(narrow_sum, 0)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_no_filtergroup_does_not_crash(self):
response = self._ranges({"dateRange": _DENSE_DAY})
self.assertGreater(len(response["ranges"]), 0)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_defaults_date_range_to_last_hour(self):
response = self._ranges({})
self.assertEqual(response["ranges"], [])
diff --git a/products/logs/backend/test/test_group_by_query_runner.py b/products/logs/backend/test/test_group_by_query_runner.py
index f3acbabd5751..e4bd4f288fe6 100644
--- a/products/logs/backend/test/test_group_by_query_runner.py
+++ b/products/logs/backend/test/test_group_by_query_runner.py
@@ -1,10 +1,8 @@
import json
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from django.urls import resolve
-
from parameterized import parameterized
from rest_framework import status
@@ -73,7 +71,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert isinstance(results, dict)
return results
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_groups_by_log_attribute_with_counts_and_last_seen(self) -> None:
self._insert(
[
@@ -114,7 +112,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
("top_level_column", "severity_level", "column", ["error", "info"]),
]
)
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_groups_by_source(self, _name: str, group_by: str, source: str, expected_values: list[str]) -> None:
self._insert(
[
@@ -129,7 +127,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert [g["value"] for g in results["groups"]] == expected_values
assert [g["log_count"] for g in results["groups"]] == [2, 1]
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_limit_truncates_but_reports_full_totals(self) -> None:
self._insert(
[self._log(attributes={"session_id": f"s{i}"}, minute=i) for i in range(3)]
@@ -144,7 +142,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert results["total_logs"] == 4
assert results["truncated"] is True
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_order_groups_by_error_count_reranks(self) -> None:
self._insert(
[self._log(attributes={"session_id": "noisy"}, severity="info", minute=m) for m in range(3)]
@@ -157,7 +155,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert [g["value"] for g in by_count["groups"]] == ["noisy", "failing"]
assert [g["value"] for g in by_errors["groups"]] == ["failing", "noisy"]
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_window_bounds_are_row_precise_not_day_precise(self) -> None:
# The shared filter builder bounds only time_bucket (day precision); the runner must
# add per-row timestamp bounds or same-day rows outside the window leak into counts.
@@ -173,7 +171,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert results["total_logs"] == 1
assert results["groups"][0]["log_count"] == 1
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_respects_service_filter(self) -> None:
self._insert(
[
@@ -186,7 +184,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert [g["value"] for g in results["groups"]] == ["s1"]
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_combined_dimensions_group_by_value_tuples(self) -> None:
# Combined grouping must count per value-combination with values in request order;
# a row missing one of the log-attribute dimensions is not a group member.
@@ -211,7 +209,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
(["s2", "info"], 1, 0),
]
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_combined_resource_dimension_joins_without_fanout(self) -> None:
# A resource dimension inside a combination still translates via the fingerprint
# join; broken composition would drop rows (missed join) or double-count (fan-out).
@@ -281,16 +279,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
class TestGroupByAPI(ClickhouseTestMixin, APIBaseTest):
- @classmethod
- def setUpClass(cls) -> None:
- super().setUpClass()
- # The process's first request imports the URLconf, which transitively pulls
- # langchain's pydantic.v1 shim — an import that crashes if it first runs under
- # freeze_time (FakeDate breaks pydantic.v1's date metaclass). Load it unfrozen
- # so no frozen test is the one to trigger it.
- resolve("/")
-
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_endpoint_returns_grouped_results(self) -> None:
sync_execute(
"INSERT INTO logs FORMAT JSONEachRow\n"
@@ -330,7 +319,7 @@ class TestGroupByAPI(ClickhouseTestMixin, APIBaseTest):
}
]
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_endpoint_accepts_combined_dimensions(self) -> None:
# Wiring guard for the groupBys request shape: the view must parse the dimension
# list (not fall back to the legacy single-key fields) and surface per-dimension
diff --git a/products/logs/backend/test/test_impact_api.py b/products/logs/backend/test/test_impact_api.py
index 1b0e1adceb8e..dda795d9019d 100644
--- a/products/logs/backend/test/test_impact_api.py
+++ b/products/logs/backend/test/test_impact_api.py
@@ -1,7 +1,7 @@
import json
import uuid
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from parameterized import parameterized
@@ -112,7 +112,7 @@ class TestImpactApi(ClickhouseTestMixin, APIBaseTest):
("empty_window", {"date_from": "2000-01-01T00:00:00Z", "date_to": "2000-01-02T00:00:00Z"}, _ZERO_IMPACT),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_impact_counts_identity_coverage(self, _name: str, date_range: dict, expected: dict) -> None:
response = self._impact({"dateRange": date_range})
# topK breaks count ties in an unspecified order, so only the value set is stable.
@@ -120,19 +120,19 @@ class TestImpactApi(ClickhouseTestMixin, APIBaseTest):
response[top_list] = sorted(response[top_list], key=lambda entry: entry["value"])
self.assertEqual(response, expected)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_impact_accepts_null_filter_lists(self) -> None:
response = self._impact({"dateRange": _FIXTURE_WINDOW, "severityLevels": None, "serviceNames": None})
self.assertEqual(response["total"], 7)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_impact_applies_filters(self) -> None:
# The only error-severity row carries no identity attributes, so every
# identity count must drop to zero with it.
response = self._impact({"dateRange": _FIXTURE_WINDOW, "severityLevels": ["error"]})
self.assertEqual(response, {**_ZERO_IMPACT, "total": 1})
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_impact_counts_team_configured_session_keys(self) -> None:
TeamLogsConfig.objects.update_or_create(
team=self.team, defaults={"logs_session_id_attribute_keys": ["my_session"]}
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index cea7b738c876..22d69b15a288 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -7,7 +7,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, cast
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, NonAtomicBaseTest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -528,7 +528,7 @@ class TestRunCohortQueryFallbackEndToEnd(ClickhouseTestMixin, APIBaseTest):
filters={"serviceNames": [service]},
)
- @freeze_time("2026-01-01T10:05:00Z")
+ @time_machine.travel("2026-01-01T10:05:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.classify_alert_error")
@patch("products.logs.backend.temporal.activities.increment_cohort_query_fallback")
@patch("products.logs.backend.temporal.activities._run_batched_query")
@@ -564,7 +564,7 @@ class TestRunCohortQueryFallbackEndToEnd(ClickhouseTestMixin, APIBaseTest):
assert prefetch_a.query_duration_ms is not None and prefetch_a.query_duration_ms >= 0
assert prefetch_b.query_duration_ms is not None and prefetch_b.query_duration_ms >= 0
- @freeze_time("2026-01-01T10:05:00Z")
+ @time_machine.travel("2026-01-01T10:05:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.classify_alert_error")
@patch("products.logs.backend.temporal.activities.increment_cohort_query_fallback")
@patch("products.logs.backend.temporal.activities._run_batched_query")
@@ -610,7 +610,7 @@ class TestRunCohortQueryFallbackEndToEnd(ClickhouseTestMixin, APIBaseTest):
assert "simulated per-alert query failure" in str(bad_prefetch.error)
assert bad_prefetch.query_duration_ms is not None and bad_prefetch.query_duration_ms >= 0
- @freeze_time("2026-01-01T10:05:00Z")
+ @time_machine.travel("2026-01-01T10:05:00Z", tick=False)
def test_attribute_filter_single_alert_cohort_succeeds_end_to_end(self):
# The shape that broke in production: a size-1, projection-ineligible
# cohort whose alert filters on a log attribute. Runs the real batched
@@ -716,7 +716,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
defaults.update(kwargs)
return LogsAlertConfiguration.objects.create(**defaults)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_threshold_breached_transitions_to_firing(self, mock_produce, mock_query_cls):
@@ -734,7 +734,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
mock_produce.assert_called_once()
assert mock_produce.call_args.kwargs["event"].event == "$logs_alert_firing"
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_threshold_not_breached_stays_not_firing(self, mock_produce, mock_query_cls):
@@ -751,7 +751,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert stats["fired"] == 0
mock_produce.assert_not_called()
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_steady_state_writes_no_alert_event(self, _mock_produce, mock_query_cls):
@@ -762,7 +762,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert LogsAlertEvent.objects.filter(alert=alert).count() == 0
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_creates_event_row(self, mock_produce, mock_query_cls):
@@ -783,7 +783,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert check.query_duration_ms is not None and check.query_duration_ms >= 0
assert check.error_message is None
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_advances_next_check_at(self, mock_produce, mock_query_cls):
@@ -797,7 +797,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.next_check_at is not None and alert.next_check_at > now
- @freeze_time("2025-01-01T21:58:00Z")
+ @time_machine.travel("2025-01-01T21:58:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_advances_next_check_at_past_quiet_hours(self, _mock_produce, mock_query_cls):
@@ -813,7 +813,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
- @freeze_time("2025-01-01T21:58:00Z")
+ @time_machine.travel("2025-01-01T21:58:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_uses_quiet_hours_saved_after_the_alert_loaded(self, _mock_produce, mock_query_cls):
@@ -829,7 +829,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
- @freeze_time("2025-01-01T23:00:00Z")
+ @time_machine.travel("2025-01-01T23:00:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_suppresses_notification_when_quiet_hours_start_after_evaluation(self, mock_produce, mock_query_cls):
@@ -848,7 +848,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
- @freeze_time("2025-01-02T06:56:00Z")
+ @time_machine.travel("2025-01-02T06:56:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_advances_last_quiet_hours_check_to_the_window_end(self, _mock_produce, mock_query_cls):
@@ -864,7 +864,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.next_check_at == datetime(2025, 1, 2, 7, 0, tzinfo=UTC)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@patch(
@@ -891,7 +891,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert "DB::Exception" not in (check.error_message or "")
assert stats["errored"] == 1
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_emit_event_uses_team_distinct_id(self, mock_produce, mock_query_cls):
@@ -905,7 +905,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
event = mock_produce.call_args.kwargs["event"]
assert event.distinct_id == f"team_{self.team.id}"
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_last_notified_at_set_after_kafka_success(self, mock_produce, mock_query_cls):
@@ -919,7 +919,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.last_notified_at == now
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))
@patch("products.alerts.backend.destinations.capture_exception")
@@ -943,7 +943,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
("below_not_breached", "below", 50, False),
]
)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_threshold_operators(self, _name, operator, count, should_fire, mock_produce, mock_query_cls):
@@ -962,7 +962,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert alert.state == LogsAlertConfiguration.State.NOT_FIRING
assert stats["fired"] == 0
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_resolution_emits_resolved_event(self, mock_produce, mock_query_cls):
@@ -984,7 +984,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
mock_produce.assert_called_once()
assert mock_produce.call_args.kwargs["event"].event == "$logs_alert_resolved"
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_cooldown_suppresses_notification(self, mock_produce, mock_query_cls):
@@ -1003,7 +1003,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert alert.state == LogsAlertConfiguration.State.FIRING
mock_produce.assert_not_called()
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_n_of_m_requires_multiple_breaches_to_fire(self, mock_produce, mock_query_cls):
@@ -1033,7 +1033,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert stats["fired"] == 1
mock_produce.assert_called_once()
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_event_properties_include_logs_url_params(self, mock_produce, mock_query_cls):
@@ -1054,7 +1054,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert props["severity_levels"] == ["error"]
assert props["triggered_at"] == "2025-01-01T00:01:00+00:00"
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_logs_url_params_includes_absolute_date_range(self, mock_produce, mock_query_cls):
@@ -1073,7 +1073,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert "2024-12-31T23%3A51%3A00" in props["logs_url_params"] or "23:51:00" in props["logs_url_params"]
assert "2025-01-01T00%3A01%3A00" in props["logs_url_params"] or "00:01:00" in props["logs_url_params"]
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_resolution_within_cooldown_suppresses_resolved_event(self, mock_produce, mock_query_cls):
@@ -1129,7 +1129,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
),
]
)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_break_on_consecutive_failures(
@@ -1174,7 +1174,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert props["last_error_message"] == "Query is too expensive. Try narrower filters or a shorter window."
assert "DB::Exception" not in props["last_error_message"]
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_state_transition")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@@ -1186,7 +1186,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
mock_transition.assert_called_once_with(AlertState.NOT_FIRING, AlertState.FIRING)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_state_transition")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@@ -1206,7 +1206,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
("resolve", 0, LogsAlertConfiguration.State.FIRING),
]
)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_notification_failures")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))
@@ -1230,7 +1230,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
mock_notif_failures.assert_called_once_with(NotificationAction(expected_action_name))
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_notification_failures")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@@ -1252,7 +1252,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
("unknown", QueryErrorCategory.ERROR),
]
)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_check_errors")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@@ -1277,7 +1277,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
mock_check_errors.assert_called_once_with(expected_category)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_check_errors")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
@@ -1291,7 +1291,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
mock_check_errors.assert_not_called()
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_query_uses_checkpoint_as_date_to_when_in_past(self, _mock_produce, mock_query_cls):
@@ -1306,7 +1306,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert kwargs["date_to"] == checkpoint
assert kwargs["date_from"] == checkpoint - dt.timedelta(minutes=5)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_query_uses_now_when_checkpoint_is_in_future(self, _mock_produce, mock_query_cls):
@@ -1322,7 +1322,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert kwargs["date_to"] == now
assert kwargs["date_from"] == now - dt.timedelta(minutes=5)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_query_uses_now_when_checkpoint_is_none(self, _mock_produce, mock_query_cls):
@@ -1336,7 +1336,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert kwargs["date_to"] == now
assert kwargs["date_from"] == now - dt.timedelta(minutes=5)
- @freeze_time("2025-01-01T01:00:00Z")
+ @time_machine.travel("2025-01-01T01:00:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_query_ignores_stale_checkpoint_quiet_partition_case(self, _mock_produce, mock_query_cls):
@@ -1362,7 +1362,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
("M=10_window=60_worst_case", 60, 10, 105),
]
)
- @freeze_time("2025-01-01T05:00:00Z")
+ @time_machine.travel("2025-01-01T05:00:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_date_from_covers_full_rolling_check_lookback(
@@ -1382,7 +1382,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert kwargs["date_to"] == now
assert kwargs["date_from"] == now - dt.timedelta(minutes=expected_range_minutes)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_errored_notification_emitted_on_first_error(self, mock_produce, mock_query_cls):
@@ -1409,7 +1409,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
assert len(errored_calls) == 1
assert errored_calls[0].kwargs["event"].properties["consecutive_failures"] == 1
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.logs.backend.temporal.activities.capture_exception")
def test_errored_notification_retried_after_kafka_failure(self, _mock_capture, mock_query_cls):
@@ -1442,7 +1442,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
]
assert len(errored_calls) == 1
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.logs.backend.temporal.activities.capture_exception")
def test_enqueue_failure_keeps_successful_checks_counter_reset(self, _mock_capture, mock_query_cls):
@@ -1480,7 +1480,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
]
assert len(errored_calls) == 1
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.capture_exception")
def test_broken_notification_retried_after_kafka_failure(self, _mock_capture, mock_query_cls):
@@ -1519,7 +1519,7 @@ class TestEvaluateSingleAlert(APIBaseTest):
("broken", LogsAlertConfiguration.State.ERRORED, 4, NotificationAction.BROKEN),
]
)
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.increment_notification_failures")
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))
@@ -1665,7 +1665,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):
see.
"""
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_breach_against_real_clickhouse_fires_alert(self, _mock_produce):
# Five logs at 10:30 with a unique service. next_check_at=10:33,
@@ -1729,7 +1729,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):
defaults.update(kwargs)
return LogsAlertConfiguration.objects.create(**defaults)
- @freeze_time("2025-12-16T10:35:00Z")
+ @time_machine.travel("2025-12-16T10:35:00Z", tick=False)
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_n_of_m_progression_across_consecutive_evals(self, _mock_produce):
# Real-CH version of the N-of-M progression test. M=3 N=2 over 5-min buckets.
@@ -1790,7 +1790,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):
alert.refresh_from_db()
assert alert.state == LogsAlertConfiguration.State.NOT_FIRING
- @freeze_time("2025-12-16T10:25:00Z")
+ @time_machine.travel("2025-12-16T10:25:00Z", tick=False)
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_cooldown_suppresses_resolve_notification_within_window(self, mock_produce):
# Alert fires at next_check_at #1, resolve attempted at next_check_at #2
@@ -1823,7 +1823,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):
assert alert.state == LogsAlertConfiguration.State.NOT_FIRING # state still transitions
assert mock_produce.call_count == 1 # but no second notification dispatched
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_below_operator_fires_on_truly_silent_service(self, _mock_produce):
# `execute_rolling_checks` always returns exactly `period_count` entries (zero
@@ -1845,7 +1845,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):
"below operator on a silent service must fire — count=0 satisfies count<threshold"
)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
@patch("products.alerts.backend.destinations.produce_internal_event")
def test_first_run_with_null_nca_anchors_on_now(self, _mock_produce):
# Alert created with next_check_at=None (first eval after enable). The
@@ -2045,7 +2045,7 @@ class TestCohortManifest(unittest.TestCase):
class TestDiscoverCohortsActivity(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
- @freeze_time("2026-05-05T23:00:00Z")
+ @time_machine.travel("2026-05-05T23:00:00Z", tick=False)
def test_skips_alert_with_invalid_quiet_hours_and_discovers_healthy_alerts(self):
from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
@@ -2080,7 +2080,7 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):
discovered_alert_ids = [alert_id for manifest in result.manifests for alert_id in manifest.alert_ids]
assert discovered_alert_ids == [str(healthy_alert.id)]
- @freeze_time("2026-05-05T23:00:00Z")
+ @time_machine.travel("2026-05-05T23:00:00Z", tick=False)
def test_reschedules_due_alert_during_quiet_hours_before_evaluation(self):
from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
@@ -2103,7 +2103,7 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):
alert.refresh_from_db()
assert alert.next_check_at == datetime(2026, 5, 6, 7, 0, tzinfo=UTC)
- @freeze_time("2026-05-05T10:00:00Z")
+ @time_machine.travel("2026-05-05T10:00:00Z", tick=False)
def test_returns_manifests_for_due_alerts_only(self):
from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
@@ -2139,7 +2139,7 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):
assert len(result.manifests) == 1
assert len(result.manifests[0].alert_ids) == 2
- @freeze_time("2026-05-05T10:00:00Z")
+ @time_machine.travel("2026-05-05T10:00:00Z", tick=False)
def test_transitions_alert_with_broken_filter_config_to_broken(self):
from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activity
@@ -2227,7 +2227,7 @@ class TestCohortFromManifest(unittest.TestCase):
class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
- @freeze_time("2026-05-05T10:05:00Z")
+ @time_machine.travel("2026-05-05T10:05:00Z", tick=False)
@patch("posthog.slo.context.emit_slo_completed")
@patch("posthog.slo.context.emit_slo_started")
@patch("products.logs.backend.temporal.activities._run_cohort_query")
@@ -2289,7 +2289,7 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert call.kwargs["properties"].outcome == SloOutcome.SUCCESS
assert call.kwargs["extra_properties"]["alert_state"] == AlertState.NOT_FIRING
- @freeze_time("2026-05-05T10:05:00Z")
+ @time_machine.travel("2026-05-05T10:05:00Z", tick=False)
@patch("products.logs.backend.temporal.activities._run_cohort_query")
def test_one_cohorts_failure_isolated_within_batch(self, mock_run_cohort_query):
# If one cohort raises, the remaining cohorts in the batch still run.
@@ -2352,7 +2352,7 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.alerts_errored == 1
assert result.alerts_checked == 1
- @freeze_time("2025-01-01T00:01:00Z")
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US")
@patch("posthog.slo.context.emit_slo_completed")
@patch("posthog.slo.context.emit_slo_started")
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index b0cda5bfea96..809625d76ef9 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -2,7 +2,7 @@ import os
import json
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from parameterized import parameterized
@@ -602,7 +602,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, expected_status)
return response.json() if expected_status == status.HTTP_200_OK else response
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_logs_integration_exact_limit(self):
# query matches exactly 50 results from the test data
query_params = {
@@ -617,7 +617,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertFalse(response["hasMore"])
self.assertEqual(len(queries), 1)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_logs_integration_one_more(self):
# query matches exactly 51 results from the test data
query_params = {
@@ -632,7 +632,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(response["hasMore"])
self.assertEqual(len(queries), 1)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_logs_slicing(self):
# should slice the query, only return 100 results first time, then get the rest
query_params = {
@@ -652,7 +652,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("naive", "2025-12-16T00:00:00"),
]
)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_live_tail_checkpoint_iso_string(self, _name, checkpoint):
query_params = {
"dateRange": {"date_from": "2025-12-16 09:32:36.178572Z", "date_to": None},
@@ -665,7 +665,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
response = self._make_logs_api_request(query_params)
self.assertGreater(len(response["results"]), 0)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_resource_filters(self):
query_params = {
"dateRange": {"date_from": "2025-12-16 09:32:36.178572Z", "date_to": None},
@@ -700,7 +700,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response["results"]), 1)
self.assertEqual(len(queries), 2)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_resource_negative_filters(self):
query_params = {
"dateRange": {"date_from": "2025-12-16 09:32:36.178572Z", "date_to": None},
@@ -735,7 +735,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response["results"]), 0)
self.assertEqual(len(queries), 2)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_multiple_negative_resource_attribute_filters(self):
# Two negative resource attribute filters on disjoint values (no log has both an envoy
# container AND the kube-system namespace). The fix exists so a resource is excluded when
@@ -821,7 +821,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
return runner.calculate().results
@parameterized.expand([(PropertyGroupsMode.OPTIMIZED,), (PropertyGroupsMode.DISABLED,)])
- @freeze_time("2025-12-18T03:00:00Z")
+ @time_machine.travel("2025-12-18T03:00:00Z", tick=False)
def test_log_attribute_filter_resolves_regardless_of_property_groups_mode(self, mode: PropertyGroupsMode):
# The seed data has 1000 logs with logtag="F" and 11 without. A log-attribute filter must resolve the
# type-suffixed key (logtag__str) to its physical Map column for every property-groups mode — otherwise an
@@ -838,7 +838,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(all(r["attributes"].get("logtag") == "F" for r in exact_results))
self.assertEqual(len(exact_results), 1000)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_resource_negative_attribute_filters(self):
query_params = {
"dateRange": {"date_from": "2025-12-16 09:00:36.178572Z", "date_to": None},
@@ -872,7 +872,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response["results"]), 99)
self.assertEqual(len(queries), 2)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_resource_number_filters(self):
query_params = {
"dateRange": {"date_from": "-2h", "date_to": "2025-12-16 09:10:36.178572Z"},
@@ -900,7 +900,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response["results"]), 10)
self.assertEqual(len(queries), 2)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_trace_and_span_ids_returned_as_hex(self):
query_params = {
"dateRange": {"date_from": "2025-12-16 09:01:22.139425Z", "date_to": "2025-12-16 09:01:22.139426Z"},
@@ -961,7 +961,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_resource_fingerprint_integration(self):
"""Integration test for resource fingerprint queries using actual test data"""
# First, get logs with a specific resource attribute to identify a resource fingerprint
@@ -1030,7 +1030,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
"filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},
}
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_single_day_no_boundary(self):
"""Query entirely within Dec 15 — should only return Dec 15 logs."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-15 00:00:00Z", "2025-12-16 00:00:00Z"))
@@ -1041,7 +1041,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertNotIn("boundary-log-dec14-noon", bodies)
self.assertNotIn("boundary-log-dec16-midnight-exact", bodies)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_cross_midnight_dec15_to_dec16(self):
"""Query spanning 23:59 Dec 15 → 00:01 Dec 16 crosses the day boundary."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-15 23:59:00Z", "2025-12-16 00:00:012Z"))
@@ -1055,7 +1055,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Earlier Dec 15 morning should NOT match (outside timestamp range)
self.assertNotIn("boundary-log-dec15-morning", bodies)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_exactly_midnight_from(self):
"""date_from exactly at midnight — toStartOfDay still equals that day."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-16 00:00:00Z", "2025-12-16 00:00:012Z"))
@@ -1065,7 +1065,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Dec 15 logs should NOT appear (time_bucket Dec 15 < toStartOfDay(Dec 16))
self.assertNotIn("boundary-log-dec15-2359", bodies)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_exactly_midnight_to(self):
"""date_to exactly at midnight Dec 17 — toStartOfDay(date_to) = Dec 17, so Dec 17 time_bucket included."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-17 00:00:00Z", "2025-12-17 00:00:00.000002Z"))
@@ -1074,7 +1074,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Dec 16 logs should NOT appear
self.assertNotIn("boundary-log-dec16-midnight-exact", bodies)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_multi_day_span(self):
"""Query spanning Dec 14 noon → Dec 18 early should include all boundary logs."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-14 00:00:00Z", "2025-12-19 00:00:00Z"))
@@ -1093,7 +1093,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
}
self.assertEqual(bodies, expected)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_narrow_window_around_midnight(self):
"""Very narrow window: last microsecond of Dec 15 → first microsecond of Dec 16.
Both days' time_buckets must be scanned."""
@@ -1104,7 +1104,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIn("boundary-log-dec16-midnight-exact", bodies)
self.assertIn("boundary-log-dec16-midnight-plus1us", bodies)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_excludes_outside_days(self):
"""Query for Dec 15 only — Dec 14 and Dec 16+ must not appear."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-15 00:00:00Z", "2025-12-16 00:00:00Z"))
@@ -1113,7 +1113,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertNotIn("boundary-log-dec17-midnight-exact", bodies)
self.assertNotIn("boundary-log-dec18-early", bodies)
- @freeze_time("2025-12-19T00:00:00Z")
+ @time_machine.travel("2025-12-19T00:00:00Z", tick=False)
def test_time_bucket_date_to_midday_does_not_leak_next_day(self):
"""date_to in the middle of Dec 17 — Dec 18 logs must NOT appear."""
bodies = self._boundary_bodies(self._boundary_query("2025-12-17 00:00:00Z", "2025-12-17 15:00:00Z"))
@@ -1122,7 +1122,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIn("boundary-log-dec17-afternoon", bodies)
self.assertNotIn("boundary-log-dec18-early", bodies)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_relative_date_from_keeps_exact_window(self):
# "-1d" must mean exactly 24 hours back, not "since midnight yesterday": the count and
# sparkline runners resolve day-level presets exactly, so a midnight-snapped list would
@@ -1157,7 +1157,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(LogsViewSet._normalize_filter_group(input_value), expected)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_query_with_flat_filter_group(self):
"""The query endpoint normalizes flat filter arrays to nested PropertyGroupFilter."""
query_params = {
@@ -1177,7 +1177,7 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
for result in response["results"]:
self.assertIn("efs-csi-node", result["resource_attributes"].get("k8s.pod.name", ""))
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_query_with_empty_flat_filter_group(self):
"""Empty flat filter array should return results (no filtering)."""
query_params = {
diff --git a/products/logs/backend/test/test_models.py b/products/logs/backend/test/test_models.py
index 17f4cb79d338..2756343305f8 100644
--- a/products/logs/backend/test/test_models.py
+++ b/products/logs/backend/test/test_models.py
@@ -1,7 +1,7 @@
import importlib
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from django.apps import apps
@@ -188,7 +188,7 @@ class TestLogsAlertEvent(BaseTest):
defaults.update(kwargs)
return LogsAlertEvent.objects.create(**defaults)
- @freeze_time("2026-03-09T12:00:00Z")
+ @time_machine.travel("2026-03-09T12:00:00Z", tick=False)
def test_clean_up_old_events_prunes_rows_older_than_event_retention(self):
alert = self._create_alert()
old_errored = self._create_check(alert, error_message="CH timeout")
@@ -205,7 +205,7 @@ class TestLogsAlertEvent(BaseTest):
assert not LogsAlertEvent.objects.filter(pk=old_errored.pk).exists()
assert LogsAlertEvent.objects.filter(pk=recent_transition.pk).exists()
- @freeze_time("2026-03-09T12:00:00Z")
+ @time_machine.travel("2026-03-09T12:00:00Z", tick=False)
def test_clean_up_old_events_does_not_prune_non_event_rows(self):
# Non-event rows are the activity's problem (inline cap). If a stale OK row sits
# in the table, clean_up_old_events should leave it alone — the activity will
diff --git a/products/logs/backend/test/test_pattern_diff.py b/products/logs/backend/test/test_pattern_diff.py
index bffe7a0dda3e..30c7e4eb9c9d 100644
--- a/products/logs/backend/test/test_pattern_diff.py
+++ b/products/logs/backend/test/test_pattern_diff.py
@@ -1,7 +1,7 @@
import json
import datetime as dt
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest import TestCase
@@ -171,7 +171,7 @@ class TestRunPatternsDiff(ClickhouseTestMixin, APIBaseTest):
"service_name": service,
}
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_auto_baseline_mines_the_same_window_a_week_earlier(self) -> None:
# Wiring no pure test can catch: the baseline window must be the resolved current
# window shifted -7d, with the query's filters carried over, and the whole diff
@@ -206,7 +206,7 @@ class TestRunPatternsDiff(ClickhouseTestMixin, APIBaseTest):
assert run_patterns_diff(self.team, query, None) == results
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_explicit_baseline_range_is_used_verbatim(self) -> None:
self._insert(
[
diff --git a/products/logs/backend/test/test_patterns_api.py b/products/logs/backend/test/test_patterns_api.py
index eb5781173d97..46328113f8ba 100644
--- a/products/logs/backend/test/test_patterns_api.py
+++ b/products/logs/backend/test/test_patterns_api.py
@@ -1,6 +1,6 @@
import json
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from rest_framework import status
@@ -18,7 +18,7 @@ class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, expected_status)
return response.json() if expected_status == status.HTTP_200_OK else response
- @freeze_time("2026-06-23T13:00:00Z")
+ @time_machine.travel("2026-06-23T13:00:00Z", tick=False)
def test_patterns_endpoint_returns_mined_patterns(self) -> None:
self._insert(
[
@@ -50,7 +50,7 @@ class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):
assert pattern["estimated_error_count"] == 3
assert pattern["services"] == ["auth"]
- @freeze_time("2026-06-23T13:00:00Z")
+ @time_machine.travel("2026-06-23T13:00:00Z", tick=False)
def test_patterns_endpoint_accepts_flat_filter_group(self) -> None:
self._insert(
[
diff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.py
index 4edb2386ea48..19841021e1f0 100644
--- a/products/logs/backend/test/test_patterns_query_runner.py
+++ b/products/logs/backend/test/test_patterns_query_runner.py
@@ -3,7 +3,7 @@ import re
import json
import datetime as dt
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -44,7 +44,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
response = PatternsQueryRunner(team=self.team, query=query).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
return response.results
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_mines_templates_from_clickhouse(self) -> None:
self._insert(
[
@@ -83,7 +83,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert len(results["sparkline_buckets"]) == 24
assert sum(by_template["User <*> not found"]["sparkline"]) == 3
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_sets_sampled_and_caps_scanned_count_above_the_limit(self) -> None:
self._insert([self._log(f"request {i} handled") for i in range(20)])
@@ -95,7 +95,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# total_count reports the full window size even though the sample is capped.
assert results["total_count"] == 20
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_sampled_runs_are_deterministic(self) -> None:
# The sample hashes each row's immutable uuid rather than using rand(), so the same
# window + filters must mine identical patterns on every run. Guards against
@@ -110,7 +110,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert first["patterns"] == second["patterns"]
assert first["scanned_count"] == second["scanned_count"]
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_scan_budget_bounds_eligible_rows_via_time_slices(self) -> None:
# 60 rows, one per minute across a 1h window; a budget of 30 with 6 slices makes only
# half the window eligible. No hash sampling kicks in (pool < sample limit), so the
@@ -185,7 +185,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_sample_divisor_rounds_up_to_keep_sample_within_limit(self, total: int, expected: int) -> None:
assert _sample_divisor(total, sample_limit=10) == expected
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_respects_service_filter(self) -> None:
self._insert(
[self._log("auth check passed", service="api") for _ in range(3)]
@@ -199,7 +199,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):
services_seen = {svc for p in results["patterns"] for svc in p["services"]}
assert services_seen == {"api"}
- @freeze_time(_FROZEN_NOW)
+ @time_machine.travel(_FROZEN_NOW, tick=False)
def test_empty_window_returns_no_patterns(self) -> None:
results = self._run()
diff --git a/products/logs/backend/test/test_services_query_runner.py b/products/logs/backend/test/test_services_query_runner.py
index 036ac1093f17..1ebf708e2980 100644
--- a/products/logs/backend/test/test_services_query_runner.py
+++ b/products/logs/backend/test/test_services_query_runner.py
@@ -3,7 +3,7 @@ import json
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -196,7 +196,7 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
return response.json()
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_services_honors_sub_day_date_range(self):
# The fixture has 1003 logs on 2025-12-16 across 12 services, but only the
# 10:32 batch (100 logs from cdp-legacy-events-consumer) falls in this
@@ -210,7 +210,7 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(windowed["services"][0]["service_name"], "cdp-legacy-events-consumer")
self.assertEqual(windowed["services"][0]["log_count"], 100)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_services_normalizes_flat_filter_group_from_mcp(self):
# MCP tools send `filterGroup` as a flat list of property filters (see
# `_normalize_filter_group`'s docstring), not the nested PropertyGroupFilter shape
@@ -236,7 +236,7 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):
services = response.json()["services"]
self.assertEqual({s["service_name"] for s in services}, {"cdp-legacy-events-consumer"})
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_sparkline_covers_exactly_the_returned_services(self):
# Exact equality holds because the fixture's 12 services fit within
# SPARKLINE_SERVICES_LIMIT; past the limit only the top services get a trend.
@@ -247,9 +247,6 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(service_names)
self.assertEqual(sparkline_services, service_names)
- # The tests below pass absolute date ranges instead of freezing time: the first
- # request of a test process imports the URLconf, and transitively pydantic.v1,
- # whose date subclasses cannot be built while freezegun has datetime.date patched.
def test_cap_limits_services_but_not_total_count(self):
with patch.object(services_query_runner, "SERVICES_LIMIT", 5):
result = self._services("2025-12-16T00:00:00Z", "2025-12-16T23:59:59Z")
diff --git a/products/logs/backend/test/test_sparkline_api.py b/products/logs/backend/test/test_sparkline_api.py
index 43c6b4c1db30..54c7ad9e60ac 100644
--- a/products/logs/backend/test/test_sparkline_api.py
+++ b/products/logs/backend/test/test_sparkline_api.py
@@ -2,7 +2,7 @@ import os
import json
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from parameterized import parameterized
@@ -44,7 +44,7 @@ class TestSparklineApi(ClickhouseTestMixin, APIBaseTest):
("defaults_to_last_hour", {}, 0),
]
)
- @freeze_time("2025-12-18T12:00:00Z")
+ @time_machine.travel("2025-12-18T12:00:00Z", tick=False)
def test_sparkline(self, _name, query_params, expected_count):
buckets = self._sparkline(query_params)
self.assertEqual(sum(bucket["count"] for bucket in buckets), expected_count)
diff --git a/products/logs/backend/test/test_sparkline_query_runner.py b/products/logs/backend/test/test_sparkline_query_runner.py
index 7f2e221ce226..826b37464fca 100644
--- a/products/logs/backend/test/test_sparkline_query_runner.py
+++ b/products/logs/backend/test/test_sparkline_query_runner.py
@@ -3,11 +3,9 @@ import json
import uuid
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from django.urls import get_resolver
-
from rest_framework import status
from posthog.clickhouse.client import sync_execute
@@ -31,13 +29,6 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- # Import the URL tree before any test freezes time. Every test here requests under
- # freeze_time, and the first such request is what imports the URL conf — which reaches
- # pydantic.v1, whose ConstrainedDate subclasses `date`. freezegun has swapped that for
- # FakeDate by then, so the import dies with a metaclass conflict and whichever test happens
- # to run first fails.
- assert get_resolver().url_patterns is not None
-
with open(os.path.join(os.path.dirname(__file__), "test_logs.jsonnd")) as f:
sql = ""
for line in f:
@@ -66,7 +57,7 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, expected_status)
return response.json() if expected_status == status.HTTP_200_OK else response
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_sparkline_single_log(self):
query_params = {
"dateRange": {"date_from": "2025-12-16T10:23:16.449937Z", "date_to": "2025-12-16T10:23:16.449937Z"},
@@ -78,7 +69,7 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response), 1)
self.assertEqual(response[0]["count"], 1)
- @freeze_time("2025-12-16T10:33:00Z")
+ @time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_sparkline_near_full(self):
query_params = {
"dateRange": {"date_from": "2025-12-16T09:00:00.000000Z", "date_to": "2025-12-16T10:31:35.692143Z"},
@@ -100,7 +91,7 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):
query_params["sparklineRankBy"] = rank_by
return self._make_sparkline_api_request(query_params)
- @freeze_time("2026-03-02T00:10:00Z")
+ @time_machine.travel("2026-03-02T00:10:00Z", tick=False)
def test_service_breakdown_collapses_the_tail_into_one_other_bucket(self):
response = self._service_sparkline()
@@ -118,7 +109,7 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):
folded_count * self.BUCKET_COUNT,
)
- @freeze_time("2026-03-02T00:10:00Z")
+ @time_machine.travel("2026-03-02T00:10:00Z", tick=False)
def test_rank_by_bytes_keeps_a_different_top_ten_than_rank_by_count(self):
# Every service logs the same number of times, but one carries a million-fold more bytes per
# log. A caller charting bytes has to see that service as its own series; ranking by count
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
index c949b8a9ba5b..c091e38aaa73 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
@@ -1,7 +1,7 @@
from pathlib import Path
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, events_cache_tests
from parameterized import parameterized
@@ -109,7 +109,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def _create_test_data(self):
"""Create comprehensive test data covering various scenarios"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# Basic users
_create_person(distinct_ids=["user1"], team=self.team, properties={"$browser": "Chrome"})
_create_person(distinct_ids=["user2"], team=self.team, properties={"$browser": "Firefox"})
@@ -317,7 +317,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test TOTAL math type correctly counts all events - business logic validation"""
# Create test data: multiple events per user to test total count vs unique users
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: 3 sign_ups (should count as 3 total events)
_create_person(distinct_ids=["total_test_user1"], team=self.team)
_create_event(
@@ -397,7 +397,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test DAU math type correctly counts unique users - business logic validation"""
# Create test data: 3 users with different patterns
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: 3 sign_ups (should count as 1 unique user)
_create_person(distinct_ids=["dau_test_user1"], team=self.team)
_create_event(
@@ -486,7 +486,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test SUM math type correctly adds revenue property values - business logic validation"""
# Create test data: purchases with different revenue amounts
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: $100 purchase
_create_person(distinct_ids=["sum_test_buyer1"], team=self.team)
_create_event(
@@ -575,7 +575,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test SUM math type correctly handles missing properties and zero values - business logic validation"""
# Create test data: events with different revenue scenarios
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: Mix of valid, zero, and missing revenue values
_create_person(distinct_ids=["sum_missing_test_user1"], team=self.team)
_create_event(
@@ -722,7 +722,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test AVERAGE math type fallback behavior - counts events since AVG not implemented - business logic validation"""
# Create test data: events to test AVG fallback behavior
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: 2 purchase events (should count as 2 events, not average revenue)
_create_person(distinct_ids=["avg_test_user1"], team=self.team)
_create_event(
@@ -800,7 +800,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test property filters actually filter events based on numeric conditions (>= operator) - business logic validation"""
# Create test data: purchases with different revenue amounts
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: revenue=75 (should be EXCLUDED by revenue >= 100 filter)
_create_person(distinct_ids=["filter_test_buyer1"], team=self.team)
_create_event(
@@ -889,7 +889,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_property_filters_multiple_filters(self):
"""Test ConversionGoalProcessor query correctly filters events with multiple property conditions"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: High revenue + correct source (should MATCH both filters)
_create_person(distinct_ids=["multi_filter_user1"], team=self.team)
_create_event(
@@ -970,7 +970,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_property_filters_complex_operators(self):
"""Test complex property filter operators LT and ICONTAINS work correctly together"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# User1: Low revenue + campaign contains "sale" (should MATCH both filters)
_create_person(distinct_ids=["complex_user1"], team=self.team)
_create_event(
@@ -1164,7 +1164,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
logic in the processor wasn't working properly.
"""
# Create events with UTM data stored in CUSTOM field names
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_person(distinct_ids=["custom_fields_user"], team=self.team)
_create_event(
distinct_id="custom_fields_user",
@@ -1181,7 +1181,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(
distinct_id="custom_fields_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -1329,7 +1329,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_error_empty_event_name(self):
"""Test what actually happens when we execute query with empty event name"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# Create different event types to see what gets matched with empty event name
_create_person(distinct_ids=["empty_test_user1"], team=self.team)
_create_event(
@@ -1391,7 +1391,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_edge_case_very_long_goal_names(self):
"""Test that queries work correctly with very long goal names"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# Create test event for very long goal name
_create_person(distinct_ids=["long_name_user"], team=self.team)
_create_event(
@@ -1448,7 +1448,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_edge_case_special_characters_in_event_names(self):
"""Test that events with special characters in names are correctly matched"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
special_event = "event-with_special.chars@123!$%" # Removed quotes/backslashes to avoid escaping issues
# Create event with special characters in the name
@@ -1516,7 +1516,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_edge_case_unicode_in_properties(self):
"""Test that Unicode property names work correctly in queries and attribution"""
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
# Create event with Unicode property names and values
_create_person(distinct_ids=["unicode_user"], team=self.team)
_create_event(
@@ -1578,7 +1578,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""Test that ConversionGoalProcessor correctly handles conversions with complex temporal scenarios"""
# Create complex timeline: UTM before range → conversion in range → UTM after
- with freeze_time("2022-12-15"):
+ with time_machine.travel("2022-12-15", tick=False):
_create_person(distinct_ids=["temporal_user"], team=self.team)
_create_event(
distinct_id="temporal_user",
@@ -1588,7 +1588,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-01-10"):
+ with time_machine.travel("2023-01-10", tick=False):
_create_event(
distinct_id="temporal_user",
event="purchase",
@@ -1597,7 +1597,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-01-20"):
+ with time_machine.travel("2023-01-20", tick=False):
_create_event(
distinct_id="temporal_user",
event="$pageview",
@@ -1767,7 +1767,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Conversion should be attributed to the April ad
Rule: Ads must come BEFORE conversions to get attribution credit
"""
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_person(distinct_ids=["forward_user"], team=self.team)
_create_event(
distinct_id="forward_user",
@@ -1777,7 +1777,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(
distinct_id="forward_user",
event="purchase",
@@ -1834,7 +1834,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Attribution goes to ad1 (direct UTM) NOT ad2 (last temporal touchpoint)
"""
# Setup: Create ad1 touchpoint first
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_person(distinct_ids=["direct_utm_user"], team=self.team)
_create_event(
distinct_id="direct_utm_user",
@@ -1845,7 +1845,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Setup: Create ad2 touchpoint later (would be last touch temporally)
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(
distinct_id="direct_utm_user",
event="$pageview",
@@ -1856,7 +1856,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# Note: Conversion event has ad1 UTM params directly
# This should override temporal attribution to ad2
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(
distinct_id="direct_utm_user",
event="purchase",
@@ -1923,7 +1923,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Conversion should NOT be attributed to the May ad (Unknown attribution)
Rule: Ads that come after conversions cannot get credit for those conversions
"""
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_person(distinct_ids=["backward_user"], team=self.team)
_create_event(
distinct_id="backward_user",
@@ -1933,7 +1933,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(
distinct_id="backward_user",
event="$pageview",
@@ -1990,7 +1990,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Attribution should go to April Google ad (last touch)
Note: This tests last-touch attribution model
"""
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_person(distinct_ids=["multi_touch_user"], team=self.team)
_create_event(
distinct_id="multi_touch_user",
@@ -2000,7 +2000,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(
distinct_id="multi_touch_user",
event="$pageview",
@@ -2009,7 +2009,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(distinct_id="multi_touch_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
@@ -2061,7 +2061,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Attribution should go to March email ad (first touch)
Note: This tests first-touch attribution model using AttributionModeOperator.FIRST_TOUCH
"""
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_person(distinct_ids=["first_touch_user"], team=self.team)
_create_event(
distinct_id="first_touch_user",
@@ -2071,7 +2071,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(
distinct_id="first_touch_user",
event="$pageview",
@@ -2080,7 +2080,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(distinct_id="first_touch_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
@@ -2138,7 +2138,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Only ads before conversion should be considered for attribution
Attribution should go to April Google ad (last valid touchpoint)
"""
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_person(distinct_ids=["mixed_timeline_user"], team=self.team)
_create_event(
distinct_id="mixed_timeline_user",
@@ -2148,7 +2148,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(
distinct_id="mixed_timeline_user",
event="$pageview",
@@ -2157,7 +2157,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(
distinct_id="mixed_timeline_user",
event="purchase",
@@ -2166,7 +2166,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-05"):
+ with time_machine.travel("2023-06-05", tick=False):
_create_event(
distinct_id="mixed_timeline_user",
event="$pageview",
@@ -2175,7 +2175,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-07-01"):
+ with time_machine.travel("2023-07-01", tick=False):
_create_event(
distinct_id="mixed_timeline_user",
event="$pageview",
@@ -2232,7 +2232,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should attribute if within attribution window
Tests attribution window limits and long customer journeys
"""
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
_create_person(distinct_ids=["long_window_user"], team=self.team)
_create_event(
distinct_id="long_window_user",
@@ -2242,7 +2242,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-12-31"):
+ with time_machine.travel("2023-12-31", tick=False):
_create_event(
distinct_id="long_window_user",
event="purchase",
@@ -2296,7 +2296,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Each conversion gets attributed to the most recent qualifying ad
"""
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_person(distinct_ids=["multi_conversion_user"], team=self.team)
_create_event(
distinct_id="multi_conversion_user",
@@ -2306,7 +2306,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(
distinct_id="multi_conversion_user",
event="purchase",
@@ -2315,7 +2315,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-20"):
+ with time_machine.travel("2023-05-20", tick=False):
_create_event(
distinct_id="multi_conversion_user",
event="$pageview",
@@ -2324,7 +2324,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-25"):
+ with time_machine.travel("2023-05-25", tick=False):
_create_event(
distinct_id="multi_conversion_user",
event="purchase",
@@ -2333,7 +2333,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-10"):
+ with time_machine.travel("2023-06-10", tick=False):
_create_event(
distinct_id="multi_conversion_user",
event="purchase",
@@ -2479,7 +2479,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should attribute to morning ad ✅
Tests intraday temporal precision
"""
- with freeze_time("2023-05-15 08:00:00"):
+ with time_machine.travel("2023-05-15 08:00:00", tick=False):
_create_person(distinct_ids=["same_day_morning_user"], team=self.team)
_create_event(
distinct_id="same_day_morning_user",
@@ -2489,7 +2489,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-15 20:00:00"):
+ with time_machine.travel("2023-05-15 20:00:00", tick=False):
_create_event(
distinct_id="same_day_morning_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -2539,14 +2539,14 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should NOT attribute to evening ad ❌ (Unknown attribution)
Tests that temporal order matters even within the same day
"""
- with freeze_time("2023-05-15 08:00:00"):
+ with time_machine.travel("2023-05-15 08:00:00", tick=False):
_create_person(distinct_ids=["same_day_evening_user"], team=self.team)
_create_event(
distinct_id="same_day_evening_user", event="purchase", team=self.team, properties={"revenue": 100}
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-15 20:00:00"):
+ with time_machine.travel("2023-05-15 20:00:00", tick=False):
_create_event(
distinct_id="same_day_evening_user",
event="$pageview",
@@ -2601,7 +2601,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""
timestamp = "2023-05-15 12:00:00"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(distinct_ids=["simultaneous_user"], team=self.team)
_create_event(
distinct_id="simultaneous_user",
@@ -2658,12 +2658,12 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should NOT attribute ❌ (Unknown attribution)
Tests temporal precision down to the second level
"""
- with freeze_time("2023-05-15 12:00:00"):
+ with time_machine.travel("2023-05-15 12:00:00", tick=False):
_create_person(distinct_ids=["one_second_user"], team=self.team)
_create_event(distinct_id="one_second_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-15 12:00:01"):
+ with time_machine.travel("2023-05-15 12:00:01", tick=False):
_create_event(
distinct_id="one_second_user",
event="$pageview",
@@ -2719,7 +2719,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
conversion_count should be 3 (not 1)
Tests that attribution properly aggregates multiple conversions
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["repeat_buyer"], team=self.team)
_create_event(
distinct_id="repeat_buyer",
@@ -2730,17 +2730,17 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# First purchase
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(distinct_id="repeat_buyer", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
# Second purchase
- with freeze_time("2023-05-20"):
+ with time_machine.travel("2023-05-20", tick=False):
_create_event(distinct_id="repeat_buyer", event="purchase", team=self.team, properties={"revenue": 75})
flush_persons_and_events_in_batches()
# Third purchase
- with freeze_time("2023-06-10"):
+ with time_machine.travel("2023-06-10", tick=False):
_create_event(distinct_id="repeat_buyer", event="purchase", team=self.team, properties={"revenue": 150})
flush_persons_and_events_in_batches()
@@ -2793,27 +2793,27 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
campaign_props = {"utm_campaign": "spring_sale", "utm_source": "google"}
# User A: sees ad, purchases once
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_person(distinct_ids=["user_a"], team=self.team)
_create_event(distinct_id="user_a", event="$pageview", team=self.team, properties=campaign_props)
_create_event(distinct_id="user_a", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
# User B: sees ad, purchases once
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_person(distinct_ids=["user_b"], team=self.team)
_create_event(distinct_id="user_b", event="$pageview", team=self.team, properties=campaign_props)
_create_event(distinct_id="user_b", event="purchase", team=self.team, properties={"revenue": 150})
flush_persons_and_events_in_batches()
# User C: sees ad, purchases twice
- with freeze_time("2023-04-20"):
+ with time_machine.travel("2023-04-20", tick=False):
_create_person(distinct_ids=["user_c"], team=self.team)
_create_event(distinct_id="user_c", event="$pageview", team=self.team, properties=campaign_props)
_create_event(distinct_id="user_c", event="purchase", team=self.team, properties={"revenue": 200})
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-21"):
+ with time_machine.travel("2023-04-21", tick=False):
_create_event(distinct_id="user_c", event="purchase", team=self.team, properties={"revenue": 75})
flush_persons_and_events_in_batches()
@@ -2869,7 +2869,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Purchase should be attributed to Facebook retargeting (last paid touchpoint before conversion)
Post-purchase touchpoints should not affect the original purchase attribution
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["complex_journey_user"], team=self.team)
_create_event(
distinct_id="complex_journey_user",
@@ -2879,7 +2879,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
_create_event(
distinct_id="complex_journey_user",
event="email_open",
@@ -2888,7 +2888,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="complex_journey_user",
event="$pageview",
@@ -2897,7 +2897,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-05"):
+ with time_machine.travel("2023-04-05", tick=False):
_create_event(
distinct_id="complex_journey_user",
event="add_to_cart",
@@ -2906,7 +2906,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_event(
distinct_id="complex_journey_user",
event="purchase",
@@ -2915,7 +2915,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-01"):
+ with time_machine.travel("2023-05-01", tick=False):
_create_event(
distinct_id="complex_journey_user",
event="email_click",
@@ -2971,7 +2971,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Attribution should go to paid search (last paid touchpoint)
Tests how organic vs paid touchpoints are prioritized in attribution
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["organic_paid_user"], team=self.team)
_create_event(
distinct_id="organic_paid_user",
@@ -2981,7 +2981,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="organic_paid_user",
event="$pageview",
@@ -2990,7 +2990,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_event(
distinct_id="organic_paid_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3042,7 +3042,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
- Last-touch: Could be organic or paid (depending on how organic is handled)
- Paid-only last-touch: Should be paid search (last paid touchpoint)
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["paid_organic_user"], team=self.team)
_create_event(
distinct_id="paid_organic_user",
@@ -3052,7 +3052,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="paid_organic_user",
event="$pageview",
@@ -3061,7 +3061,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_event(
distinct_id="paid_organic_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3115,7 +3115,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Attribution should go to Google search ad (last touch)
Tests multi-channel customer journey attribution
"""
- with freeze_time("2023-03-01"): # Week 1
+ with time_machine.travel("2023-03-01", tick=False): # Week 1
_create_person(distinct_ids=["cross_channel_user"], team=self.team)
_create_event(
distinct_id="cross_channel_user",
@@ -3125,7 +3125,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-08"): # Week 2
+ with time_machine.travel("2023-03-08", tick=False): # Week 2
_create_event(
distinct_id="cross_channel_user",
event="email_click",
@@ -3134,7 +3134,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-15"): # Week 3
+ with time_machine.travel("2023-03-15", tick=False): # Week 3
_create_event(
distinct_id="cross_channel_user",
event="$pageview",
@@ -3143,7 +3143,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-22"): # Week 4
+ with time_machine.travel("2023-03-22", tick=False): # Week 4
_create_event(
distinct_id="cross_channel_user",
event="$pageview",
@@ -3152,7 +3152,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-24"): # Week 4
+ with time_machine.travel("2023-03-24", tick=False): # Week 4
_create_event(
distinct_id="cross_channel_user", event="purchase", team=self.team, properties={"revenue": 300}
)
@@ -3206,7 +3206,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Tests attribution across session boundaries and device switching
"""
# Session 1 - Mobile (Instagram discovery)
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["multi_session_user"], team=self.team)
_create_event(
distinct_id="multi_session_user",
@@ -3228,7 +3228,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Session 2 - Desktop (Direct visit)
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
_create_event(
distinct_id="multi_session_user",
event="$pageview",
@@ -3245,7 +3245,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Session 3 - Mobile (Email conversion)
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="multi_session_user",
event="$pageview",
@@ -3314,7 +3314,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Validates: use_temporal_attribution=True ignores query_date_range for UTM lookback
"""
# Setup: Create UTM touchpoint BEFORE query range
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
_create_person(distinct_ids=["filtered_utm_user"], team=self.team)
_create_event(
distinct_id="filtered_utm_user",
@@ -3325,7 +3325,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Setup: Conversion WITHIN query range
- with freeze_time("2023-05-10"):
+ with time_machine.travel("2023-05-10", tick=False):
_create_event(
distinct_id="filtered_utm_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3391,7 +3391,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: First purchase attributed, second purchase not attributed
Tests attribution window cutoff logic
"""
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
_create_person(distinct_ids=["window_test_user"], team=self.team)
_create_event(
distinct_id="window_test_user",
@@ -3401,11 +3401,11 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-01-29"): # Day 29 - within window
+ with time_machine.travel("2023-01-29", tick=False): # Day 29 - within window
_create_event(distinct_id="window_test_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
- with freeze_time("2023-02-01"): # Day 31 - beyond window
+ with time_machine.travel("2023-02-01", tick=False): # Day 31 - beyond window
_create_event(distinct_id="window_test_user", event="purchase", team=self.team, properties={"revenue": 50})
flush_persons_and_events_in_batches()
@@ -3495,7 +3495,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Currently the processor attributes to any campaign regardless of age.
Business requirement: Implement ~30-90 day attribution window limits.
"""
- with freeze_time("2022-01-01"):
+ with time_machine.travel("2022-01-01", tick=False):
_create_person(distinct_ids=["old_campaign_user"], team=self.team)
_create_event(
distinct_id="old_campaign_user",
@@ -3505,7 +3505,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2024-01-01"): # 2 years later
+ with time_machine.travel("2024-01-01", tick=False): # 2 years later
_create_event(
distinct_id="old_campaign_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3563,7 +3563,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
credited to paid (facebook → meta). The Apr 01 pageview has a campaign but no source
and no click id, so it is not a touchpoint.
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["malformed_utm_user"], team=self.team)
_create_event(
distinct_id="malformed_utm_user",
@@ -3573,7 +3573,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="malformed_utm_user",
event="$pageview",
@@ -3582,7 +3582,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-01"):
+ with time_machine.travel("2023-05-01", tick=False):
_create_event(
distinct_id="malformed_utm_user",
event="$pageview",
@@ -3591,7 +3591,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-01"):
+ with time_machine.travel("2023-06-01", tick=False):
_create_event(
distinct_id="malformed_utm_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3643,7 +3643,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
expected_channel: str,
) -> None:
self.config.drill_down_level = MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE
- with freeze_time("2023-05-01"):
+ with time_machine.travel("2023-05-01", tick=False):
_create_person(distinct_ids=["click_id_user"], team=self.team)
_create_event(
distinct_id="click_id_user",
@@ -3653,7 +3653,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-01"):
+ with time_machine.travel("2023-06-01", tick=False):
_create_event(distinct_id="click_id_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
@@ -3691,7 +3691,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Organic Social — a paid source inside an organic channel.
"""
self.config.drill_down_level = MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE
- with freeze_time("2023-05-01"):
+ with time_machine.travel("2023-05-01", tick=False):
_create_person(distinct_ids=["fbclid_user"], team=self.team)
_create_event(
distinct_id="fbclid_user",
@@ -3701,7 +3701,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-01"):
+ with time_machine.travel("2023-06-01", tick=False):
_create_event(distinct_id="fbclid_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
@@ -3744,7 +3744,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""
timestamp = "2023-05-15 12:00:00"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(distinct_ids=["duplicate_events_user"], team=self.team)
_create_event(
distinct_id="duplicate_events_user",
@@ -3762,7 +3762,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-15 13:00:00"):
+ with time_machine.travel("2023-05-15 13:00:00", tick=False):
_create_event(
distinct_id="duplicate_events_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3816,7 +3816,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""
timestamp = "2023-05-15 12:00:00"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(distinct_ids=["duplicate_events_user"], team=self.team)
_create_event(
distinct_id="duplicate_events_user",
@@ -3834,7 +3834,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-15 13:00:00"):
+ with time_machine.travel("2023-05-15 13:00:00", tick=False):
_create_event(
distinct_id="duplicate_events_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3885,7 +3885,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should handle special characters properly in attribution
Tests URL encoding, special characters, and data sanitization
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["special_chars_user"], team=self.team)
_create_event(
distinct_id="special_chars_user",
@@ -3901,7 +3901,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="special_chars_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -3954,7 +3954,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
long_campaign = "very_long_campaign_name_" + "x" * 500
long_source = "extremely_long_source_name_" + "y" * 300
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["long_utm_user"], team=self.team)
_create_event(
distinct_id="long_utm_user",
@@ -3964,7 +3964,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(distinct_id="long_utm_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
@@ -4014,7 +4014,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should handle case sensitivity consistently
Tests whether attribution treats "Google", "google", "GOOGLE" as same or different
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["case_sensitive_user"], team=self.team)
_create_event(
distinct_id="case_sensitive_user",
@@ -4024,7 +4024,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
_create_event(
distinct_id="case_sensitive_user",
event="$pageview",
@@ -4033,7 +4033,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="case_sensitive_user",
event="$pageview",
@@ -4042,7 +4042,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_event(
distinct_id="case_sensitive_user", event="purchase", team=self.team, properties={"revenue": 100}
)
@@ -4095,7 +4095,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: All should be treated consistently as "Unknown" attribution
Tests handling of null, empty, and missing UTM parameters
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["null_empty_user"], team=self.team)
_create_event(
distinct_id="null_empty_user",
@@ -4105,7 +4105,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
_create_event(
distinct_id="null_empty_user",
event="$pageview",
@@ -4114,7 +4114,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_event(
distinct_id="null_empty_user",
event="$pageview",
@@ -4123,7 +4123,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_event(distinct_id="null_empty_user", event="purchase", team=self.team, properties={"revenue": 100})
flush_persons_and_events_in_batches()
@@ -4178,7 +4178,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Attribution should go to the $pageview event UTM, not the other events
Tests that only $pageview events are considered for UTM attribution
"""
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["non_pageview_user"], team=self.team)
# Sign-up with UTM - should be ignored
_create_event(
@@ -4189,7 +4189,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-05"):
+ with time_machine.travel("2023-03-05", tick=False):
# Purchase with UTM - should be ignored
_create_event(
distinct_id="non_pageview_user",
@@ -4199,7 +4199,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
# $pageview with UTM - should be used for attribution
_create_event(
distinct_id="non_pageview_user",
@@ -4209,7 +4209,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
# Final conversion
_create_event(
distinct_id="non_pageview_user", event="purchase", team=self.team, properties={"revenue": 100}
@@ -4270,7 +4270,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Tests comprehensive real-world attribution complexity
"""
# Week 1 - Brand awareness (potentially outside window)
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
_create_person(distinct_ids=["real_world_user"], team=self.team)
_create_event(
distinct_id="real_world_user",
@@ -4281,7 +4281,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Week 5 - Email campaign
- with freeze_time("2023-02-01"):
+ with time_machine.travel("2023-02-01", tick=False):
_create_event(
distinct_id="real_world_user",
event="$pageview",
@@ -4291,7 +4291,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Week 6 - Organic search (no UTM)
- with freeze_time("2023-02-08"):
+ with time_machine.travel("2023-02-08", tick=False):
_create_event(
distinct_id="real_world_user",
event="$pageview",
@@ -4301,7 +4301,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Week 7 - Facebook retargeting (last paid touchpoint)
- with freeze_time("2023-02-15"):
+ with time_machine.travel("2023-02-15", tick=False):
_create_event(
distinct_id="real_world_user",
event="$pageview",
@@ -4311,7 +4311,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Week 7 - First purchase (no UTM on conversion event - tests temporal attribution)
- with freeze_time("2023-02-17"):
+ with time_machine.travel("2023-02-17", tick=False):
_create_event(
distinct_id="real_world_user",
event="purchase",
@@ -4324,7 +4324,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Week 8 - Post-purchase upsell (should not affect first purchase attribution)
- with freeze_time("2023-02-22"):
+ with time_machine.travel("2023-02-22", tick=False):
_create_event(
distinct_id="real_world_user",
event="$pageview",
@@ -4334,7 +4334,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Week 10 - Second purchase
- with freeze_time("2023-03-08"):
+ with time_machine.travel("2023-03-08", tick=False):
_create_event(
distinct_id="real_world_user",
event="purchase",
@@ -4451,7 +4451,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
"""
# Create user journey across multiple distinct IDs
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["laptop_anon", "mobile_app", "[email protected]"], team=self.team)
# UTM campaign from laptop
_create_event(
@@ -4462,17 +4462,17 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-05"):
+ with time_machine.travel("2023-03-05", tick=False):
# Mobile browsing (no UTM)
_create_event(distinct_id="mobile_app", event="$pageview", team=self.team, properties={"page": "/products"})
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
# Purchase from email distinct_id (signed in)
_create_event(distinct_id="[email protected]", event="purchase", team=self.team, properties={"revenue": 99})
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
# Purchase from original laptop session
_create_event(distinct_id="laptop_anon", event="purchase", team=self.team, properties={"revenue": 149})
flush_persons_and_events_in_batches()
@@ -4521,7 +4521,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# Create complex user journey with multiple distinct IDs over time
distinct_ids = ["session_1", "session_2", "session_3", "[email protected]", "session_5"]
- with freeze_time("2023-01-15"):
+ with time_machine.travel("2023-01-15", tick=False):
_create_person(distinct_ids=distinct_ids, team=self.team)
# First touchpoint: organic
_create_event(
@@ -4532,7 +4532,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-02-01"):
+ with time_machine.travel("2023-02-01", tick=False):
# Second session: UTM campaign
_create_event(
distinct_id="session_2",
@@ -4542,7 +4542,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-02-15"):
+ with time_machine.travel("2023-02-15", tick=False):
# Third session: different UTM campaign
_create_event(
distinct_id="session_3",
@@ -4552,19 +4552,19 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
# Fourth session: signed up with email
_create_event(
distinct_id="[email protected]", event="sign_up", team=self.team, properties={"source": "website"}
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
# Purchase 1: Should attribute to valentines_special (most recent UTM)
_create_event(distinct_id="[email protected]", event="purchase", team=self.team, properties={"revenue": 75})
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
# Fifth session: New UTM campaign
_create_event(
distinct_id="session_5",
@@ -4574,7 +4574,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
# Purchase 2: Should attribute to spring_launch (most recent UTM)
_create_event(
distinct_id="session_1", # Back to original session
@@ -4638,7 +4638,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should generate SQL with attribution window logic
Attribution window: 6 months (180 days) to include Jan events for Jun conversions
"""
- with freeze_time("2025-01-01"):
+ with time_machine.travel("2025-01-01", tick=False):
_create_person(distinct_ids=["demo_user"], team=self.team)
_create_event(
distinct_id="demo_user",
@@ -4648,7 +4648,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2025-03-15"):
+ with time_machine.travel("2025-03-15", tick=False):
_create_event(
distinct_id="demo_user",
event="$pageview",
@@ -4657,7 +4657,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2025-06-06"):
+ with time_machine.travel("2025-06-06", tick=False):
_create_event(distinct_id="demo_user", event="user signed up", team=self.team, properties={"value": 1})
flush_persons_and_events_in_batches()
@@ -4721,7 +4721,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should generate SQL with attribution window logic
Attribution window: 6 months (180 days) to include Jan events for Jun conversions
"""
- with freeze_time("2025-01-01"):
+ with time_machine.travel("2025-01-01", tick=False):
_create_person(distinct_ids=["demo_user"], team=self.team)
_create_event(
distinct_id="demo_user",
@@ -4731,7 +4731,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2025-03-15"):
+ with time_machine.travel("2025-03-15", tick=False):
_create_event(
distinct_id="demo_user",
event="$pageview",
@@ -4740,7 +4740,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2025-06-06"):
+ with time_machine.travel("2025-06-06", tick=False):
_create_event(distinct_id="demo_user", event="user signed up", team=self.team, properties={"value": 1})
flush_persons_and_events_in_batches()
@@ -4813,7 +4813,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
This validates that attribution windows work per-conversion, not per-query.
"""
# User2: Pageview on May 29 with UTM
- with freeze_time("2024-05-29"):
+ with time_machine.travel("2024-05-29", tick=False):
_create_person(distinct_ids=["user2"], team=self.team)
_create_event(
distinct_id="user2",
@@ -4824,7 +4824,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# User1: Pageview on May 30 with UTM
- with freeze_time("2024-05-30"):
+ with time_machine.travel("2024-05-30", tick=False):
_create_person(distinct_ids=["user1"], team=self.team)
_create_event(
distinct_id="user1",
@@ -4835,12 +4835,12 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# User2: Converts on June 5 (7 days after pageview - within 30-day window)
- with freeze_time("2024-06-05"):
+ with time_machine.travel("2024-06-05", tick=False):
_create_event(distinct_id="user2", event="user signed up", team=self.team, properties={"value": 1})
flush_persons_and_events_in_batches()
# User1: Converts on July 1 (32 days after pageview - outside 30-day window)
- with freeze_time("2024-07-01"):
+ with time_machine.travel("2024-07-01", tick=False):
_create_event(distinct_id="user1", event="user signed up", team=self.team, properties={"value": 1})
flush_persons_and_events_in_batches()
@@ -4917,7 +4917,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: TOTAL math should count both events (2 conversions)
"""
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_person(distinct_ids=["multi_event_user"], team=self.team)
_create_event(
distinct_id="multi_event_user",
@@ -4927,11 +4927,11 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(distinct_id="multi_event_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-20"):
+ with time_machine.travel("2023-04-20", tick=False):
_create_event(distinct_id="multi_event_user", event="activate_account", team=self.team)
flush_persons_and_events_in_batches()
@@ -4986,7 +4986,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: TOTAL = 4 conversions, DAU = 3 unique users
"""
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
# Create users and show them the ad
for user_id in ["user_a", "user_b", "user_c"]:
_create_person(distinct_ids=[user_id], team=self.team)
@@ -4998,7 +4998,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
# User A signs up
_create_event(
distinct_id="user_a",
@@ -5008,7 +5008,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-20"):
+ with time_machine.travel("2023-04-20", tick=False):
# User B activates account (without signing up in our data)
_create_event(
distinct_id="user_b",
@@ -5018,7 +5018,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-25"):
+ with time_machine.travel("2023-04-25", tick=False):
# User C signs up
_create_event(
distinct_id="user_c",
@@ -5028,7 +5028,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-30"):
+ with time_machine.travel("2023-04-30", tick=False):
# User A activates account (second event from same user)
_create_event(
distinct_id="user_a",
@@ -5112,7 +5112,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Should only count events that match the property filters (2 conversions)
"""
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_person(distinct_ids=["filter_user"], team=self.team)
_create_event(
distinct_id="filter_user",
@@ -5122,7 +5122,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
# Sign up with matching property
_create_event(
distinct_id="filter_user",
@@ -5132,7 +5132,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-20"):
+ with time_machine.travel("2023-04-20", tick=False):
# Activate with matching property
_create_event(
distinct_id="filter_user",
@@ -5142,7 +5142,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-25"):
+ with time_machine.travel("2023-04-25", tick=False):
# Sign up with non-matching property
_create_event(
distinct_id="filter_user",
@@ -5152,7 +5152,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-30"):
+ with time_machine.travel("2023-04-30", tick=False):
# Activate with non-matching property
_create_event(
distinct_id="filter_user",
@@ -5216,7 +5216,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
This test clarifies the current behavior.
"""
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_person(distinct_ids=["semantics_user"], team=self.team)
_create_event(
distinct_id="semantics_user",
@@ -5227,7 +5227,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# User triggers ONLY the first event
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(
distinct_id="semantics_user",
event="sign_up",
@@ -5267,7 +5267,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
first_event_only_count = response.results[0][4] if response.results else 0
# Now user triggers the second event too
- with freeze_time("2023-04-20"):
+ with time_machine.travel("2023-04-20", tick=False):
_create_event(distinct_id="semantics_user", event="activate_account", team=self.team)
flush_persons_and_events_in_batches()
@@ -5286,7 +5286,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Scenario: UTM pageview → action event
Expected: Action should attribute to the prior pageview UTM parameters
"""
- with freeze_time("2023-04-10"):
+ with time_machine.travel("2023-04-10", tick=False):
_create_person(distinct_ids=["attribution_test_user"], team=self.team)
_create_event(
distinct_id="attribution_test_user",
@@ -5296,7 +5296,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(distinct_id="attribution_test_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
@@ -5346,7 +5346,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Both action events attribute to same pageview UTMs
"""
# Create test data with temporal attribution scenario
- with freeze_time("2023-06-01 10:00:00"):
+ with time_machine.travel("2023-06-01 10:00:00", tick=False):
_create_person(distinct_ids=["test_user"], team=self.team)
_create_event(
distinct_id="test_user",
@@ -5356,11 +5356,11 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-01 10:05:00"):
+ with time_machine.travel("2023-06-01 10:05:00", tick=False):
_create_event(distinct_id="test_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
- with freeze_time("2023-06-01 10:10:00"):
+ with time_machine.travel("2023-06-01 10:10:00", tick=False):
_create_event(distinct_id="test_user", event="activate_account", team=self.team)
flush_persons_and_events_in_batches()
@@ -5448,7 +5448,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
Expected: Action correctly attributes to prior pageview UTMs
"""
# Create temporal attribution test data
- with freeze_time("2023-05-01"):
+ with time_machine.travel("2023-05-01", tick=False):
_create_person(distinct_ids=["test_user"], team=self.team)
_create_event(
distinct_id="test_user",
@@ -5458,7 +5458,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-05-02"):
+ with time_machine.travel("2023-05-02", tick=False):
_create_event(distinct_id="test_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
@@ -5514,7 +5514,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
This validates that utm_medium is threaded through the conversion pipeline
and used in channel type classification, matching the behavior of adapter cost data.
"""
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_person(distinct_ids=["paid_user"], team=self.team)
_create_event(
distinct_id="paid_user",
@@ -5524,7 +5524,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-12"):
+ with time_machine.travel("2023-03-12", tick=False):
_create_event(
distinct_id="paid_user",
event="purchase",
@@ -5533,7 +5533,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_person(distinct_ids=["organic_user"], team=self.team)
_create_event(
distinct_id="organic_user",
@@ -5543,7 +5543,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-12"):
+ with time_machine.travel("2023-03-12", tick=False):
_create_event(
distinct_id="organic_user",
event="purchase",
@@ -5604,7 +5604,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
expected_weights: dict[str, float],
):
for i, (campaign, source, date) in enumerate(touchpoints):
- with freeze_time(date):
+ with time_machine.travel(date, tick=False):
if i == 0:
_create_person(distinct_ids=[user_id], team=self.team)
_create_event(
@@ -5615,7 +5615,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time(conversion_date):
+ with time_machine.travel(conversion_date, tick=False):
_create_event(distinct_id=user_id, event="purchase", team=self.team, properties={})
flush_persons_and_events_in_batches()
@@ -5698,7 +5698,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
def test_time_decay_attribution_recent_gets_more_credit(self):
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
_create_person(distinct_ids=["decay_user"], team=self.team)
_create_event(
distinct_id="decay_user",
@@ -5708,7 +5708,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-25"):
+ with time_machine.travel("2023-03-25", tick=False):
_create_event(
distinct_id="decay_user",
event="$pageview",
@@ -5717,7 +5717,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-31"):
+ with time_machine.travel("2023-03-31", tick=False):
_create_event(distinct_id="decay_user", event="purchase", team=self.team, properties={})
flush_persons_and_events_in_batches()
@@ -5821,7 +5821,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
def test_multi_touch_no_touchpoints_returns_no_results(self):
- with freeze_time("2023-04-01"):
+ with time_machine.travel("2023-04-01", tick=False):
_create_person(distinct_ids=["no_utm_user"], team=self.team)
_create_event(
distinct_id="no_utm_user",
@@ -5831,7 +5831,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-04-15"):
+ with time_machine.travel("2023-04-15", tick=False):
_create_event(distinct_id="no_utm_user", event="purchase", team=self.team, properties={})
flush_persons_and_events_in_batches()
@@ -5866,7 +5866,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# ── Multi-touch attribution snapshot tests ──────────────────────────
def _create_multi_touch_scenario(self):
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["mt_user"], team=self.team)
_create_event(
distinct_id="mt_user",
@@ -5876,7 +5876,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_event(
distinct_id="mt_user",
event="$pageview",
@@ -5885,7 +5885,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-20"):
+ with time_machine.travel("2023-03-20", tick=False):
_create_event(
distinct_id="mt_user",
event="$pageview",
@@ -5894,7 +5894,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-25"):
+ with time_machine.travel("2023-03-25", tick=False):
_create_event(
distinct_id="mt_user",
event="purchase",
@@ -6165,7 +6165,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_multi_touch_linear_with_actions_node(self):
# 3 touchpoints → action-based conversion (sign_up OR activate_account)
- with freeze_time("2023-03-01"):
+ with time_machine.travel("2023-03-01", tick=False):
_create_person(distinct_ids=["mt_action_user"], team=self.team)
_create_event(
distinct_id="mt_action_user",
@@ -6175,7 +6175,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-10"):
+ with time_machine.travel("2023-03-10", tick=False):
_create_event(
distinct_id="mt_action_user",
event="$pageview",
@@ -6184,7 +6184,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-20"):
+ with time_machine.travel("2023-03-20", tick=False):
_create_event(distinct_id="mt_action_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
@@ -6231,7 +6231,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
def test_position_based_no_touchpoints_in_window_returns_no_rows(self):
# Touchpoint exists but outside the attribution window → 0 results
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
_create_person(distinct_ids=["outside_window_user"], team=self.team)
_create_event(
distinct_id="outside_window_user",
@@ -6242,7 +6242,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Conversion 1 year later — touchpoint is outside the 90-day window
- with freeze_time("2024-01-01"):
+ with time_machine.travel("2024-01-01", tick=False):
_create_event(
distinct_id="outside_window_user",
event="purchase",
@@ -6286,7 +6286,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# When all touchpoints share the exact same timestamp, exp(0) = 1 for each,
# producing equal weights (degrades to linear behavior).
timestamp = "2023-03-15 12:00:00"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(distinct_ids=["same_ts_user"], team=self.team)
_create_event(
distinct_id="same_ts_user",
@@ -6302,7 +6302,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-20"):
+ with time_machine.travel("2023-03-20", tick=False):
_create_event(distinct_id="same_ts_user", event="purchase", team=self.team)
flush_persons_and_events_in_batches()
@@ -6339,7 +6339,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# When two touchpoints share the same timestamp as min, both get 0.4 before
# normalization. With 3 touchpoints (two at min, one at max), pre-normalization
# sum = 0.4 + 0.4 + 0.4 = 1.2, which normalizes to 0.333 each.
- with freeze_time("2023-03-01 12:00:00"):
+ with time_machine.travel("2023-03-01 12:00:00", tick=False):
_create_person(distinct_ids=["dup_ts_user"], team=self.team)
_create_event(
distinct_id="dup_ts_user",
@@ -6355,7 +6355,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-15"):
+ with time_machine.travel("2023-03-15", tick=False):
_create_event(
distinct_id="dup_ts_user",
event="$pageview",
@@ -6364,7 +6364,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
)
flush_persons_and_events_in_batches()
- with freeze_time("2023-03-20"):
+ with time_machine.travel("2023-03-20", tick=False):
_create_event(distinct_id="dup_ts_user", event="purchase", team=self.team)
flush_persons_and_events_in_batches()
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py
index fdfb2a20e3cd..f88d34336b24 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_base_query_runner.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -34,7 +34,7 @@ def _item(change_pct: float | None) -> MarketingAnalyticsItem:
)
-@freeze_time("2026-06-15T12:00:00Z")
+@time_machine.travel("2026-06-15T12:00:00Z", tick=False)
class TestCostsPrecomputeTtlSchedule(BaseTest):
"""The read path and the Dagster warmer both build their schedule here.
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py
index 5928ba3a3dff..9fc85e6cbacf 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py
@@ -1,5 +1,5 @@
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from parameterized import parameterized
@@ -265,7 +265,7 @@ class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertTrue(response.results[0].values[0].complete)
- @freeze_time("2023-01-11T10:00:00Z")
+ @time_machine.travel("2023-01-11T10:00:00Z", tick=False)
def test_the_period_still_being_lived_through_is_incomplete(self):
# On an open-ended range `date_to` is the end of today, which is in the future, so comparing
# against it alone marks today complete and renders a partial day as a finished number.
diff --git a/products/marketing_analytics/backend/services/test_data_source_health.py b/products/marketing_analytics/backend/services/test_data_source_health.py
index 889ad8b73bf6..aedcc1abfa21 100644
--- a/products/marketing_analytics/backend/services/test_data_source_health.py
+++ b/products/marketing_analytics/backend/services/test_data_source_health.py
@@ -2,7 +2,7 @@ from datetime import timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
@@ -20,8 +20,12 @@ from products.marketing_analytics.backend.services.data_source_health import (
)
-@freeze_time("2025-06-15")
class TestResolveSyncStatus:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2025-06-15", tick=False):
+ yield
+
@parameterized.expand(
[
("never_synced_returns_never", None, None, "never"),
@@ -145,7 +149,7 @@ class _FakeSource:
self.source_type = source_type
-@freeze_time("2025-06-15")
+@time_machine.travel("2025-06-15", tick=False)
class TestGetDataSourceHealthOrchestration(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/products/marketing_analytics/backend/test_max_tools.py b/products/marketing_analytics/backend/test_max_tools.py
index 4cb46e15982a..4a76f3787991 100644
--- a/products/marketing_analytics/backend/test_max_tools.py
+++ b/products/marketing_analytics/backend/test_max_tools.py
@@ -2,7 +2,7 @@ import os
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, patch
@@ -203,7 +203,7 @@ class TestSanitizeForPrompt(BaseTest):
assert result == "abc"
-@freeze_time("2025-06-15")
+@time_machine.travel("2025-06-15", tick=False)
class TestFormatTimestampForLlm(BaseTest):
@parameterized.expand(
[
@@ -296,7 +296,7 @@ class TestResolveLookbackDays(BaseTest):
assert result == 90
-@freeze_time("2025-06-15")
+@time_machine.travel("2025-06-15", tick=False)
class TestFormatDiagnosticForLlm(BaseTest):
def _make_minimal_response(self, *, overall_status="healthy", summary="All good"):
return MarketingDiagnosticResponse(
@@ -467,7 +467,7 @@ class TestFormatGoalLine(BaseTest):
assert "non_integrated=50" in result
-@freeze_time("2025-06-15")
+@time_machine.travel("2025-06-15", tick=False)
class TestFormatDataSourcesForLlm(BaseTest):
def test_not_connected_shows_in_output(self):
entry = _make_data_source_entry(
diff --git a/products/mcp_analytics/backend/tests/test_dashboard_series.py b/products/mcp_analytics/backend/tests/test_dashboard_series.py
index d32bbfa90764..ffdc4ec54eab 100644
--- a/products/mcp_analytics/backend/tests/test_dashboard_series.py
+++ b/products/mcp_analytics/backend/tests/test_dashboard_series.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -102,7 +102,7 @@ class TestMCPToolCallsAndErrorsQueryRunner(_MCPAnalyticsTeamScopedTestMixin, Cli
# Both directions matter here: "last hour" has to stay exact or it pulls in an extra chunk
# of calls, while day and up has to cover whole days or the first bucket undercounts against
# the wall-clock keys the client zero-fills with.
- with freeze_time("2026-07-21 18:30:00"):
+ with time_machine.travel("2026-07-21 18:30:00", tick=False):
# 08:00 Pacific on the 20th: inside the truncated day window, outside an exact one.
self._emit(timestamp=datetime(2026, 7, 20, 15, 0, tzinfo=UTC))
# 10:15 Pacific: inside the truncated hour window (10:00), outside the exact one (10:30).
diff --git a/products/mcp_registry/backend/tests/test_ranking.py b/products/mcp_registry/backend/tests/test_ranking.py
index 1461c63bfa26..f63c13f92dbb 100644
--- a/products/mcp_registry/backend/tests/test_ranking.py
+++ b/products/mcp_registry/backend/tests/test_ranking.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from django.utils import timezone
@@ -27,7 +27,7 @@ def _measured_server(error_rate_pct: float = 5.0, calls: int = 50_000) -> MCPReg
return server
-@freeze_time("2026-08-19")
+@time_machine.travel("2026-08-19", tick=False)
class TestRanking(BaseTest):
def test_measured_signal_flips_ordering_only_in_the_measured_arm(self) -> None:
measured = _measured_server()
diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.py
index 4fd27d995b97..35f8f05c3dbe 100644
--- a/products/metrics/backend/tests/test_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_query_runner.py
@@ -2,7 +2,7 @@ import datetime as dt
from typing import cast
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -69,7 +69,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert request.interval == "minute"
assert (request.date_to - request.date_from) == dt.timedelta(hours=1)
- @freeze_time("2026-07-01T12:00:00Z")
+ @time_machine.travel("2026-07-01T12:00:00Z", tick=False)
def test_default_date_range_is_last_24_hours(self) -> None:
query = MetricsQuery(
clauses=[MetricsQueryClause(name="a", metricName="http_requests_total", aggregation="sum")]
@@ -79,7 +79,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert (request.date_to - request.date_from) == dt.timedelta(hours=24)
- @freeze_time("2026-07-01T12:00:00Z")
+ @time_machine.travel("2026-07-01T12:00:00Z", tick=False)
def test_calculate_returns_one_series_per_group(self) -> None:
base = dt.datetime(2026, 7, 1, 11, 30, tzinfo=dt.UTC)
for container, value in (("capture", 5.0), ("ingestion", 7.0)):
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 9c5539f0f047..4b3fb1037fc6 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -15,7 +15,7 @@ from http.server import ThreadingHTTPServer
from types import SimpleNamespace
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -741,9 +741,9 @@ class TestSQLV2Run(APIBaseTest):
@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
def test_run_uses_the_latest_done_run_of_a_referenced_node(self, _mock_enabled, _mock_enqueue):
# An edited-then-rerun upstream: only its most recent run should be inlined.
- with freeze_time("2026-07-04T00:00:00Z"):
+ with time_machine.travel("2026-07-04T00:00:00Z", tick=False):
self._record_done_run("node-df1", "select 1 as old_col")
- with freeze_time("2026-07-04T00:01:00Z"):
+ with time_machine.travel("2026-07-04T00:01:00Z", tick=False):
self._record_done_run("node-df1", "select 2 as new_col")
response = self.client.post(
self.run_url,
@@ -771,9 +771,9 @@ class TestSQLV2Run(APIBaseTest):
# run must not be used either. But the run did happen: a duckdb run binds its result into
# the kernel namespace under its dataframe name, so downstream cells read it as a local
# frame instead of being told the node never ran.
- with freeze_time("2026-07-04T00:00:00Z"):
+ with time_machine.travel("2026-07-04T00:00:00Z", tick=False):
self._record_done_run("node-c", "select id from events")
- with freeze_time("2026-07-04T00:01:00Z"):
+ with time_machine.travel("2026-07-04T00:01:00Z", tick=False):
with team_scope(self.team.id):
NotebookNodeRun.objects.create(
team=self.team,
@@ -1065,7 +1065,7 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
# This poll is the only thing that advances a direct run, and the only place its expiry
# watchdog fires. Gating before that would strand the run RUNNING forever once access
# went away — so the row must still finish even though the caller is refused its rows.
- with freeze_time("2026-07-01T00:00:00Z"), team_scope(self.team.id):
+ with time_machine.travel("2026-07-01T00:00:00Z", tick=False), team_scope(self.team.id):
run = NotebookNodeRun.objects.create(
team=self.team,
notebook=self.notebook,
@@ -1533,7 +1533,7 @@ class TestSQLV2RunResult(APIBaseTest):
def test_running_run_expires_to_failed_after_grace(self, _name, node_type, expected_error, _mock_enabled):
# This poll is the watchdog for both lanes. Within the grace window it keeps waiting,
# which for hogql also covers pre-deploy kernel-executed runs whose callback is due.
- with freeze_time("2026-07-01T00:00:00Z"):
+ with time_machine.travel("2026-07-01T00:00:00Z", tick=False):
expired = self._create_run(NotebookNodeRun.Status.RUNNING, node_type=node_type)
body = self.client.get(self._url(str(expired.id))).json()
self.assertEqual(body["status"], NotebookNodeRun.Status.FAILED)
@@ -1948,7 +1948,7 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):
def test_a_data_plane_fetch_resets_the_run_watchdog_clock(
self, _name, initial_status, expect_expired, expected_status
):
- with freeze_time("2026-07-01T00:00:00Z"), team_scope(self.team.id):
+ with time_machine.travel("2026-07-01T00:00:00Z", tick=False), team_scope(self.team.id):
run = NotebookNodeRun.objects.create(
team=self.team,
notebook=self.notebook,
@@ -1968,7 +1968,7 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):
def test_a_fetch_without_a_run_claim_touches_no_run(self):
# Tokens minted before the run claim existed stay valid across the deploy that adds
# it. They fetch data as before; they just cannot advance any run's clock.
- with freeze_time("2026-07-01T00:00:00Z"), team_scope(self.team.id):
+ with time_machine.travel("2026-07-01T00:00:00Z", tick=False), team_scope(self.team.id):
run = NotebookNodeRun.objects.create(
team=self.team,
notebook=self.notebook,
diff --git a/products/posthog_ai/eval_harness/test/test_eval_seeders.py b/products/posthog_ai/eval_harness/test/test_eval_seeders.py
index 361613c623f1..71aead438e71 100644
--- a/products/posthog_ai/eval_harness/test/test_eval_seeders.py
+++ b/products/posthog_ai/eval_harness/test/test_eval_seeders.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from posthog.schema import DateRange, ErrorTrackingQuery
@@ -31,7 +31,7 @@ class TestErrorTrackingEvalSeeders(ClickhouseTestMixin, APIBaseTest):
materialize("events", property_name)
super().setUpClass()
- @freeze_time("2026-05-22T12:00:00Z")
+ @time_machine.travel("2026-05-22T12:00:00Z", tick=False)
def test_error_tracking_seeded_events_survive_person_filters(self) -> None:
test_users_cohort = get_or_create_internal_test_users_cohort(
self.team, initiating_user_email="[email protected]"
diff --git a/products/posthog_ai/scripts/hogql_example/__init__.py b/products/posthog_ai/scripts/hogql_example/__init__.py
index ca03531575e5..41d455efda12 100644
--- a/products/posthog_ai/scripts/hogql_example/__init__.py
+++ b/products/posthog_ai/scripts/hogql_example/__init__.py
@@ -15,9 +15,8 @@ _cached_team: Any = None
# Used as the synthetic "now" for relative date ranges (e.g. "-7d") so the
# rendered HogQL is reproducible and doesn't drift between builds. Pinned per
-# runner instead of via freezegun: freezegun monkey-patches `datetime.datetime`
-# process-globally, which is not thread-safe and corrupts unrelated workers
-# (Temporal activities, Django request handlers) running in the same process.
+# runner instead of via a clock mock: clock mocks are process-global, so they hand
+# unrelated workers in the same process the wrong time.
# Tz-aware UTC so QueryDateRange.now_with_timezone (which calls .astimezone)
# produces output that doesn't depend on the build machine's local timezone.
FROZEN_TIME = "2025-12-10T00:00:00+00:00"
diff --git a/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py b/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py
index d2938badad16..806e0269fa00 100644
--- a/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py
+++ b/products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from types import SimpleNamespace
import pytest
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -37,7 +38,7 @@ class TestRenderHogQLExample(BaseTest):
These guard against regressions where the rendered HogQL would silently
drift to wall-clock time, or where the renderer would corrupt global
- process state (the freezegun bug we replaced with `pin_now`).
+ process state.
"""
def setUp(self) -> None:
@@ -70,25 +71,17 @@ class TestRenderHogQLExample(BaseTest):
assert runner.context.now == hogql_example_module._FROZEN_DATETIME
@patch("django.conf.settings.DEBUG", True)
- def test_render_does_not_use_freezegun(self) -> None:
- # The bug: freezegun was used to set `now` for relative date ranges,
- # but it monkey-patches `datetime.datetime` process-globally. Concurrent
- # code (Temporal activities, Django request handlers) calling
- # `timezone.now()` during the freeze races with `tz_offsets.pop()` on
- # exit, crashing with `IndexError: list index out of range`.
- #
- # Single-threaded tests can't observe the race directly because the
- # freeze cleans up before assertions run. Instead, assert the renderer
- # never enters `freeze_time` at all — that's the only safe contract.
- import freezegun
-
+ def test_render_does_not_mock_the_global_clock(self) -> None:
+ # Clock mocking is process-global, so a freeze here hands concurrent Temporal
+ # activities and request handlers the wrong time. A single-threaded test cannot
+ # observe that, so assert the renderer never travels at all.
def _explode(*args: object, **kwargs: object) -> object:
raise AssertionError(
- "render_hogql_example called freezegun.freeze_time — this monkey-patches "
- "datetime globally and crashes concurrent workers. Use _pin_runner_now instead."
+ "render_hogql_example called time_machine.travel — this mocks the clock "
+ "process-globally and corrupts concurrent workers. Use _pin_runner_now instead."
)
- with patch.object(freezegun, "freeze_time", _explode):
+ with patch.object(time_machine, "travel", _explode):
render_hogql_example(
{
"kind": "TrendsQuery",
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/breakdown_cases.py b/products/product_analytics/backend/hogql_queries/funnels/test/breakdown_cases.py
index f36406b0eb18..18b6718ec5dd 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/breakdown_cases.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/breakdown_cases.py
@@ -5,7 +5,7 @@ from pathlib import Path
from string import ascii_lowercase
from typing import Any, Literal, Optional, Union, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
_create_action,
@@ -3438,7 +3438,7 @@ def funnel_breakdown_test_factory(funnel_order_type: FunnelOrderType):
def test_funnels_mixed_event_breakdown(self):
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
_create_person(
distinct_ids=["person1"],
team_id=self.team.pk,
@@ -3581,7 +3581,7 @@ def funnel_breakdown_test_factory(funnel_order_type: FunnelOrderType):
def test_funnels_mixed_person_breakdown(self):
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
_create_person(
distinct_ids=["person1"],
team_id=self.team.pk,
@@ -3724,7 +3724,7 @@ def funnel_breakdown_test_factory(funnel_order_type: FunnelOrderType):
def test_funnels_mixed_data_warehouse_breakdown(self):
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
_create_person(
distinct_ids=["person1"],
team_id=self.team.pk,
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py
index f5d63cd6f0ea..e69a72e152f4 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py
@@ -2,7 +2,7 @@ import uuid
from datetime import datetime
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -276,10 +276,10 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
sync_execute(f"TRUNCATE TABLE {EVENTS_DATA_TABLE()}")
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
sync_execute(f"TRUNCATE TABLE {EVENTS_JSON_DATA_TABLE}")
- with freeze_time("2012-01-01T03:21:34.000Z"):
+ with time_machine.travel("2012-01-01T03:21:34.000Z", tick=False):
funnel = self._basic_funnel()
- with freeze_time("2012-01-01T03:21:35.000Z"):
+ with time_machine.travel("2012-01-01T03:21:35.000Z", tick=False):
# events
stopped_after_signup_person_id = uuid.uuid4()
_create_person(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
@@ -288,49 +288,49 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
person_id=stopped_after_signup_person_id,
)
- with freeze_time("2012-01-01T03:21:36.000Z"):
+ with time_machine.travel("2012-01-01T03:21:36.000Z", tick=False):
stopped_after_pay_person_id = uuid.uuid4()
_create_person(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
self._signup_event(
distinct_id="stopped_after_pay",
person_id=stopped_after_pay_person_id,
)
- with freeze_time("2012-01-01T03:21:37.000Z"):
+ with time_machine.travel("2012-01-01T03:21:37.000Z", tick=False):
self._pay_event(
distinct_id="stopped_after_pay",
person_id=stopped_after_pay_person_id,
)
- with freeze_time("2012-01-01T03:21:38.000Z"):
+ with time_machine.travel("2012-01-01T03:21:38.000Z", tick=False):
had_anonymous_id_person_id = uuid.uuid4()
_create_person(
distinct_ids=["had_anonymous_id", "completed_movie"],
team_id=self.team.pk,
)
self._signup_event(distinct_id="had_anonymous_id", person_id=had_anonymous_id_person_id)
- with freeze_time("2012-01-01T03:21:39.000Z"):
+ with time_machine.travel("2012-01-01T03:21:39.000Z", tick=False):
self._pay_event(distinct_id="completed_movie", person_id=had_anonymous_id_person_id)
- with freeze_time("2012-01-01T03:21:40.000Z"):
+ with time_machine.travel("2012-01-01T03:21:40.000Z", tick=False):
self._movie_event(distinct_id="completed_movie", person_id=had_anonymous_id_person_id)
- with freeze_time("2012-01-01T03:21:41.000Z"):
+ with time_machine.travel("2012-01-01T03:21:41.000Z", tick=False):
just_did_movie_person_id = uuid.uuid4()
_create_person(distinct_ids=["just_did_movie"], team_id=self.team.pk)
self._movie_event(distinct_id="just_did_movie", person_id=just_did_movie_person_id)
- with freeze_time("2012-01-01T03:21:42.000Z"):
+ with time_machine.travel("2012-01-01T03:21:42.000Z", tick=False):
wrong_order_person_id = uuid.uuid4()
_create_person(distinct_ids=["wrong_order"], team_id=self.team.pk)
self._pay_event(distinct_id="wrong_order", person_id=wrong_order_person_id)
- with freeze_time("2012-01-01T03:21:43.000Z"):
+ with time_machine.travel("2012-01-01T03:21:43.000Z", tick=False):
self._signup_event(distinct_id="wrong_order", person_id=wrong_order_person_id)
- with freeze_time("2012-01-01T03:21:44.000Z"):
+ with time_machine.travel("2012-01-01T03:21:44.000Z", tick=False):
self._movie_event(distinct_id="wrong_order", person_id=wrong_order_person_id)
- with freeze_time("2012-01-01T03:21:45.000Z"):
+ with time_machine.travel("2012-01-01T03:21:45.000Z", tick=False):
create_person_id_override_by_distinct_id("stopped_after_signup", "stopped_after_pay", self.team.pk)
- with freeze_time("2012-01-01T03:21:46.000Z"):
+ with time_machine.travel("2012-01-01T03:21:46.000Z", tick=False):
result = funnel.calculate().results
self.assertEqual(result[0]["name"], "user signed up")
@@ -1564,7 +1564,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
],
)
- with freeze_time("2020-01-03"):
+ with time_machine.travel("2020-01-03", tick=False):
# event
person1_stopped_after_two_signups = _create_person(
distinct_ids=["stopped_after_signup1"], team_id=self.team.pk
@@ -3163,10 +3163,10 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
def test_same_event_same_timestamp(self):
_create_person(distinct_ids=["test"], team_id=self.team.pk)
- with freeze_time("2024-01-10T12:01:00"):
+ with time_machine.travel("2024-01-10T12:01:00", tick=False):
for _ in range(20):
_create_event(team=self.team, event="step one", distinct_id="test")
- with freeze_time("2024-01-11T12:01:00"):
+ with time_machine.travel("2024-01-11T12:01:00", tick=False):
_create_event(team=self.team, event="step two", distinct_id="test")
query = FunnelsQuery(
dateRange=DateRange(
@@ -4529,14 +4529,14 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
def test_multiple_events_same_timestamp_exclusions(self):
_create_person(distinct_ids=["test"], team_id=self.team.pk)
- with freeze_time("2024-01-10T12:00:00"):
+ with time_machine.travel("2024-01-10T12:00:00", tick=False):
_create_event(team=self.team, event="step zero", distinct_id="test")
- with freeze_time("2024-01-10T12:01:00"):
+ with time_machine.travel("2024-01-10T12:01:00", tick=False):
for _ in range(30):
_create_event(team=self.team, event="step one", distinct_id="test")
_create_event(team=self.team, event="exclusion", distinct_id="test")
_create_event(team=self.team, event="step two", distinct_id="test")
- with freeze_time("2024-01-10T12:02:00"):
+ with time_machine.travel("2024-01-10T12:02:00", tick=False):
_create_event(team=self.team, event="step three", distinct_id="test")
query = FunnelsQuery(
dateRange=DateRange(
@@ -5418,7 +5418,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
def test_events_same_timestamp_no_exclusions(self):
_create_person(distinct_ids=["test"], team_id=self.team.pk)
- with freeze_time("2024-01-10T12:01:00"):
+ with time_machine.travel("2024-01-10T12:01:00", tick=False):
_create_event(team=self.team, event="step one, ten", distinct_id="test")
_create_event(team=self.team, event="step two, three, seven", distinct_id="test")
_create_event(team=self.team, event="step two, three, seven", distinct_id="test")
@@ -5867,7 +5867,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result[0]["count"], 2)
self.assertEqual(result[1]["count"], 1)
- @freeze_time("2024-01-02T00:00:00Z")
+ @time_machine.travel("2024-01-02T00:00:00Z", tick=False)
def test_funnel_same_event_different_property_filters(self):
_create_person(distinct_ids=["user_both"], team_id=self.team.pk)
_create_event(
@@ -5956,7 +5956,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2024-01-02T00:00:00Z")
+ @time_machine.travel("2024-01-02T00:00:00Z", tick=False)
def test_funnel_breakdown_value_boxing(self, _name, breakdown_type, breakdown_prop, group_type_index, needs_groups):
if needs_groups:
self._create_groups()
@@ -6019,7 +6019,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
else:
assert isinstance(bv, list), f"Expected boxed breakdown_value for {breakdown_type}, got {type(bv)}"
- @freeze_time("2024-01-02T00:00:00Z")
+ @time_machine.travel("2024-01-02T00:00:00Z", tick=False)
def test_funnel_session_breakdown_groups_results_by_session_property(self):
# Three sessions across three users — two from google.com (one converts, one doesn't),
# one from bing.com (converts). The funnel groups by session.$entry_referring_domain,
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_aggregation_operations.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_aggregation_operations.py
index 07425d7a5b3c..b451629ffc1a 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_aggregation_operations.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_aggregation_operations.py
@@ -2,7 +2,7 @@ from datetime import datetime
from typing import cast
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from posthog.schema import DateRange, EventsNode, FunnelsFilter, FunnelsQuery
@@ -53,7 +53,7 @@ class TestFunnelAggregationOperations(ClickhouseTestMixin, APIBaseTest):
dateRange=DateRange(date_from="-14d"),
)
- with freeze_time("2024-07-31"):
+ with time_machine.travel("2024-07-31", tick=False):
ctx = FunnelQueryContext(funnels_query, self.team)
filters = parse_expr("1 = 1")
event_filter = parse_expr("2 = 2")
@@ -106,7 +106,7 @@ class TestFunnelAggregationOperations(ClickhouseTestMixin, APIBaseTest):
dateRange=DateRange(date_from="-14d"),
)
- with freeze_time("2024-07-31"):
+ with time_machine.travel("2024-07-31", tick=False):
ctx = FunnelQueryContext(funnels_query, self.team)
filters = parse_expr("1 = 1")
event_filter = parse_expr("2 = 2")
@@ -133,7 +133,7 @@ class TestFunnelAggregationOperations(ClickhouseTestMixin, APIBaseTest):
dateRange=DateRange(date_from="-14d"),
)
- with freeze_time("2024-07-31"):
+ with time_machine.travel("2024-07-31", tick=False):
ctx = FunnelQueryContext(funnels_query, self.team)
builder = FirstTimeForUserAggregationQuery(context=ctx)
query = builder.to_query()
@@ -284,7 +284,7 @@ class TestFunnelAggregationOperations(ClickhouseTestMixin, APIBaseTest):
dateRange=DateRange(date_from="-14d"),
)
- with freeze_time("2024-07-31"):
+ with time_machine.travel("2024-07-31", tick=False):
ctx = FunnelQueryContext(funnels_query, self.team)
builder = FirstTimeForUserAggregationQuery(context=ctx, dwh_config=_dwh_config())
query = builder.to_query()
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation.py
index 3d56adbd0b46..2ff4ccbc5fb8 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation.py
@@ -1,5 +1,5 @@
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -679,7 +679,7 @@ class TestClickhouseFunnelCorrelation(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(
event_properties=[], person_properties=["$browser"], verify_no_jsonextract=False
)
- @freeze_time("2019-12-31")
+ @time_machine.travel("2019-12-31", tick=False)
@snapshot_clickhouse_queries
def test_basic_funnel_correlation_with_properties(self):
query = FunnelsQuery(
@@ -2430,7 +2430,7 @@ class TestFunnelCorrelationSQLInjection(ClickhouseTestMixin, APIBaseTest):
)
return FunnelCorrelationQueryRunner(query=correlation_query, team=self.team)._calculate_internal()
- @freeze_time("2020-01-14")
+ @time_machine.travel("2020-01-14", tick=False)
def test_sql_injection_quote_breakout_in_correlation_names(self):
"""Verify SQL injection via quote breakout in funnelCorrelationNames is escaped."""
query = self._setup_basic_funnel()
@@ -2456,7 +2456,7 @@ class TestFunnelCorrelationSQLInjection(ClickhouseTestMixin, APIBaseTest):
self.assertNotIn("syntax error", error_msg, f"SQL injection may have worked with payload: {payload}")
self.assertNotIn("unexpected", error_msg, f"SQL injection may have worked with payload: {payload}")
- @freeze_time("2020-01-14")
+ @time_machine.travel("2020-01-14", tick=False)
def test_sql_injection_in_exclude_event_names(self):
"""Verify SQL injection via funnelCorrelationExcludeEventNames is escaped."""
query = self._setup_basic_funnel()
@@ -2473,7 +2473,7 @@ class TestFunnelCorrelationSQLInjection(ClickhouseTestMixin, APIBaseTest):
error_msg = str(e).lower()
self.assertNotIn("syntax error", error_msg, f"SQL injection may have worked with payload: {payload}")
- @freeze_time("2020-01-14")
+ @time_machine.travel("2020-01-14", tick=False)
def test_special_characters_in_property_names_are_handled(self):
"""Verify special characters in property names don't cause SQL errors."""
query = self._setup_basic_funnel()
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation_actors.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation_actors.py
index 1d0a92c53675..d1d272d6b2aa 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation_actors.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_correlation_actors.py
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from typing import Optional
from uuid import UUID
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -255,7 +255,7 @@ class TestFunnelCorrelationActors(ClickhouseTestMixin, APIBaseTest):
self.assertCountEqual([str(val[1]["id"]) for val in serialized_actors], [str(people["user_1"].uuid)])
@snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
+ @time_machine.travel("2021-01-02 00:00:00.000Z", tick=False)
def test_funnel_correlation_on_event_with_recordings(self):
p1 = _create_person(distinct_ids=["user_1"], team=self.team, properties={"foo": "bar"})
_create_event(
@@ -365,7 +365,7 @@ class TestFunnelCorrelationActors(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
+ @time_machine.travel("2021-01-02 00:00:00.000Z", tick=False)
def test_funnel_correlation_on_properties_with_recordings(self):
p1 = _create_person(distinct_ids=["user_1"], team=self.team, properties={"foo": "bar"})
_create_event(
@@ -438,7 +438,7 @@ class TestFunnelCorrelationActors(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
+ @time_machine.travel("2021-01-02 00:00:00.000Z", tick=False)
@skip("Works locally and works after you tmate onto github actions and run it, but fails in CI")
def test_strict_funnel_correlation_with_recordings(self):
# First use that successfully completes the strict funnel
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_data_warehouse.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_data_warehouse.py
index a24e7534fca5..9192022ad06d 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_data_warehouse.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_data_warehouse.py
@@ -2,7 +2,7 @@ from datetime import datetime
from pathlib import Path
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
BaseTest,
ClickhouseTestMixin,
@@ -208,7 +208,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -244,7 +244,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
# so it needs its own day-of-week coverage
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-08"):
+ with time_machine.travel("2025-11-08", tick=False):
response = FunnelsQueryRunner(
query=self._days_of_week_trends_query(table_name, days_of_week),
team=self.team,
@@ -257,7 +257,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
@snapshot_clickhouse_queries
def test_funnels_data_warehouse_and_regular_nodes(self):
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
_create_person(
distinct_ids=["person1"],
team_id=self.team.pk,
@@ -331,7 +331,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
# column (not cast to UUID) must not fail the UNION ALL with NO_COMMON_TYPE
# against the events series' person_id UUID.
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
_create_person(
distinct_ids=["person1"],
team_id=self.team.pk,
@@ -356,7 +356,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
# actor_id, which is a String for a mixed funnel. Exercise it to confirm
# the stringified actor id still resolves to a person.
table_name = self.setup_data_warehouse()
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
_create_person(
distinct_ids=["person1"],
team_id=self.team.pk,
@@ -403,7 +403,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -435,7 +435,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -471,7 +471,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
assert isinstance(funnels_query.series[1], FunnelsDataWarehouseNode) # for mypy
# throws an error because of nulls in id field
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
with pytest.raises(ExposedCHQueryError) as exc_info:
runner.calculate()
@@ -486,7 +486,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
funnels_query.series[0].properties = not_null_filter
funnels_query.series[1].properties = not_null_filter
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -615,7 +615,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
funnelsFilter=FunnelsFilter(funnelWindowInterval=30),
)
- with freeze_time("2024-06-30"):
+ with time_machine.travel("2024-06-30", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -654,7 +654,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
funnelsFilter=FunnelsFilter(funnelWindowInterval=30, funnelOrderType=StepOrderValue.UNORDERED),
)
- with freeze_time("2024-06-30"):
+ with time_machine.travel("2024-06-30", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -689,7 +689,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
funnelsFilter=FunnelsFilter(funnelOrderType=StepOrderValue.UNORDERED),
)
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
runner = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True)
response = runner.calculate()
@@ -718,7 +718,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
series=[node, node],
)
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
total = FunnelsQueryRunner(query=_query(False), team=self.team, just_summarize=True).calculate()
first_time = FunnelsQueryRunner(query=_query(True), team=self.team, just_summarize=True).calculate()
@@ -754,7 +754,7 @@ class TestFunnelDataWarehouse(ClickhouseTestMixin, BaseTest):
funnelsFilter=FunnelsFilter(funnelOrderType=StepOrderValue.UNORDERED),
)
- with freeze_time("2025-11-07"):
+ with time_machine.travel("2025-11-07", tick=False):
response = FunnelsQueryRunner(query=funnels_query, team=self.team, just_summarize=True).calculate()
# Each user appears once per table, so first-time-for-user leaves the counts unchanged —
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py
index 55c2dcdc6bcd..75024614be38 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py
@@ -1,6 +1,6 @@
from textwrap import dedent
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
import regex
@@ -113,7 +113,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
columns=columns,
)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_single_events_table(self):
query = FunnelsQuery(series=[EventsNode(), EventsNode()])
context = FunnelQueryContext(query=query, team=self.team)
@@ -131,7 +131,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_single_dwh_table(self):
dwh_node = FunnelsDataWarehouseNode(
aggregation_target_field="user_id",
@@ -156,7 +156,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_single_dwh_table_string_timestamp(self):
dwh_node = FunnelsDataWarehouseNode(
aggregation_target_field="user_id",
@@ -181,7 +181,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_multiple_tables(self):
query = FunnelsQuery(
kind="FunnelsQuery",
@@ -277,7 +277,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select_3, expected_3)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_dwh_first_time_for_user(self):
dwh_node = FunnelsDataWarehouseNode(
aggregation_target_field="user_id",
@@ -303,7 +303,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
self.assertNotIn("FROM events", sql)
self.assertNotIn("person_id", sql)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_dwh_first_time_for_user_string_timestamp(self):
dwh_node = FunnelsDataWarehouseNode(
aggregation_target_field="user_id",
@@ -324,7 +324,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
self.assertIn("min(toDateTime(e.created_at_str)) AS min_timestamp", sql)
self.assertIn("globalIn(e.id,", sql)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_dwh_first_time_for_user_with_filters(self):
dwh_node = FunnelsDataWarehouseNode(
id="table_one",
@@ -345,7 +345,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
# the step's property filter resolves against the data warehouse table inside the subquery
self.assertIn("equals(some_prop, 'some_value')", sql)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_dwh_first_time_for_user_non_uuid_id_field(self):
dwh_node = FunnelsDataWarehouseNode(
id="table_two",
@@ -398,7 +398,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
self.assertIn("e.uuid_id AS uuid", sql)
self.assertNotIn("throwIf", sql)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_dwh_first_time_for_user_two_different_tables(self):
query = FunnelsQuery(
kind="FunnelsQuery",
@@ -434,7 +434,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
self.assertIn("GROUP BY user_id", sql)
self.assertIn("GROUP BY some_user_id", sql)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_mixed_events_and_dwh_first_time_for_user(self):
query = FunnelsQuery(
kind="FunnelsQuery",
@@ -463,7 +463,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
self.assertIn("argMin(id, e.created_at) AS uuid", sql)
self.assertIn("GROUP BY user_id", sql)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_group_node_two_events(self):
group = GroupNode(
operator=FilterLogicalOperator.OR_,
@@ -485,7 +485,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_group_node_between_event_and_action(self):
checkout_action = Action.objects.create(
team=self.team,
@@ -519,7 +519,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_group_node_with_property_filters(self):
group = GroupNode(
operator=FilterLogicalOperator.OR_,
@@ -550,7 +550,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_group_node_event_or_action(self):
action = Action.objects.create(
team=self.team,
@@ -577,7 +577,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
""").strip()
self.assertEqual(select, expected)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_group_node_entity_prefilter(self):
group = GroupNode(
operator=FilterLogicalOperator.OR_,
@@ -591,7 +591,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
select = format_query(funnel_event_query)
self.assertIn("IN(event, tuple('$pageleave', '$pageview'))", select)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_group_node_and_operator_is_rejected(self):
# AND groups aren't supported yet — must fail validation, not raise UnboundLocalError (500).
group = GroupNode(
@@ -610,7 +610,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
("$channel_type",),
]
)
- @freeze_time("2025-11-12")
+ @time_machine.travel("2025-11-12", tick=False)
def test_session_breakdown(self, breakdown_property: str):
query = FunnelsQuery(
series=[EventsNode(event="$pageview"), EventsNode(event="$autocapture")],
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_insight_actors.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_insight_actors.py
index bd50f007cd86..6b29d9045057 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_insight_actors.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_insight_actors.py
@@ -1,6 +1,6 @@
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -39,7 +39,7 @@ class TestFunnelInsightActors(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
for id, timestamps in data:
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[id],
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_persons.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_persons.py
index 75ccb7b2d8e7..71ec69d8c9cf 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_persons.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_persons.py
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from typing import Optional
from uuid import UUID
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -339,7 +339,7 @@ class TestFunnelPersons(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0][0], person.uuid)
@snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
+ @time_machine.travel("2021-01-02 00:00:00.000Z", tick=False)
def test_funnel_person_recordings(self):
p1 = _create_person(distinct_ids=[f"user_1"], team=self.team)
_create_event(
@@ -733,7 +733,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
),
)
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_returns_sessions_with_person(self):
self._create_session_funnel_data()
@@ -758,7 +758,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
assert "properties" in person_data
assert person_data["properties"]["email"] == "[email protected]"
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_step_completed(self):
self._create_session_funnel_data()
@@ -773,7 +773,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) == 1
assert str(response.results[0][0]["session_id"]) == self.session_id_1
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_dropoff(self):
self._create_session_funnel_data()
@@ -788,7 +788,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) == 1
assert str(response.results[0][0]["session_id"]) == self.session_id_2
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_trends_session_actors(self):
self._create_session_funnel_data()
@@ -813,7 +813,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
assert person_data is not None
assert person_data["properties"]["email"] == "[email protected]"
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_trends_session_actors_dropoff(self):
self._create_session_funnel_data()
@@ -833,7 +833,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) == 1
assert str(response.results[0][0]["session_id"]) == self.session_id_2
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_search_by_email(self):
self._create_session_funnel_data()
@@ -851,7 +851,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
session_ids = {str(row[0]["session_id"]) for row in response.results}
assert session_ids == {self.session_id_1, self.session_id_2}
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_search_by_name(self):
self._create_session_funnel_data()
@@ -869,7 +869,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
session_ids = {str(row[0]["session_id"]) for row in response.results}
assert session_ids == {self.session_id_1, self.session_id_2}
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_search_email_no_match(self):
self._create_session_funnel_data()
@@ -885,7 +885,7 @@ class TestFunnelSessionActors(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) == 0
- @freeze_time("2021-01-08 00:00:00.000Z")
+ @time_machine.travel("2021-01-08 00:00:00.000Z", tick=False)
def test_funnel_session_actors_search_name_no_match(self):
self._create_session_funnel_data()
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict.py
index 5356edf46547..1d652a7c506e 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_action, _create_event, _create_person
from posthog.schema import (
@@ -703,7 +703,7 @@ class TestFunnelStrictSteps(ClickhouseTestMixin, APIBaseTest):
def test_multiple_events_same_timestamp_doesnt_blow_up(self):
_create_person(distinct_ids=["test"], team_id=self.team.pk)
- with freeze_time("2024-01-10T12:01:00"):
+ with time_machine.travel("2024-01-10T12:01:00", tick=False):
for _ in range(30):
_create_event(team=self.team, event="step one", distinct_id="test")
_create_event(team=self.team, event="step two", distinct_id="test")
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py
index 68f1fd56cec3..486552666d65 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from typing import Any, Optional, cast
from uuid import UUID
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -153,7 +153,7 @@ class TestFunnelStrictStepsPersons(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(0, len(results))
@snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
+ @time_machine.travel("2021-01-02 00:00:00.000Z", tick=False)
def test_strict_funnel_person_recordings(self):
p1 = _create_person(distinct_ids=[f"user_1"], team=self.team)
_create_event(
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends.py
index ba553f5aeeb9..d40873f5dd50 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends.py
@@ -2,7 +2,7 @@ from datetime import date, datetime, timedelta
from typing import Optional, cast
from zoneinfo import ZoneInfo
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -169,7 +169,7 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):
)
return FunnelsQueryRunner(query=query, team=self.team, just_summarize=True).calculate().results
- @freeze_time("2021-06-18 12:00:00")
+ @time_machine.travel("2021-06-18 12:00:00", tick=False)
def test_keeps_incomplete_conversion_window_periods_by_default(self):
results = self._run_conversion_window_trends(hide_incomplete_periods=False)
by_day = {row["timestamp"].date(): row for row in results}
@@ -183,7 +183,7 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(by_day[date(2021, 6, 15)]["reached_from_step_count"], 1)
self.assertEqual(by_day[date(2021, 6, 15)]["reached_to_step_count"], 0)
- @freeze_time("2021-06-18 12:00:00")
+ @time_machine.travel("2021-06-18 12:00:00", tick=False)
def test_hides_incomplete_conversion_window_periods_when_enabled(self):
results = self._run_conversion_window_trends(hide_incomplete_periods=True)
by_day = {row["timestamp"].date(): row for row in results}
@@ -371,7 +371,7 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):
),
)
- with freeze_time("2021-05-06T23:40:59Z"):
+ with time_machine.travel("2021-05-06T23:40:59Z", tick=False):
results = FunnelsQueryRunner(query=query, team=self.team, just_summarize=True).calculate().results
self.assertEqual(len(results), 144)
@@ -592,7 +592,7 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2021-05-20T13:01:01Z"):
+ with time_machine.travel("2021-05-20T13:01:01Z", tick=False):
results = FunnelsQueryRunner(query=query, team=self.team, just_summarize=True).calculate().results
self.assertEqual(20, len(results))
@@ -728,7 +728,7 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(0, friday["reached_from_step_count"])
self.assertEqual(0, friday["conversion_rate"])
- @freeze_time("2021-05-02 12:00:00")
+ @time_machine.travel("2021-05-02 12:00:00", tick=False)
def test_period_not_final(self):
now = datetime(2021, 5, 2, 12, 0, 0)
@@ -2122,7 +2122,7 @@ class TestFunnelTrendsUDF(ClickhouseTestMixin, APIBaseTest):
),
)
- with freeze_time("2021-05-06T23:40:59Z"):
+ with time_machine.travel("2021-05-06T23:40:59Z", tick=False):
results = FunnelsQueryRunner(query=query, team=self.team, just_summarize=True).calculate().results
conversion_rates = [row["conversion_rate"] for row in results]
self.assertEqual(conversion_rates, [50.0, 0.0, 0.0, 0.0, 0.0, 0.0])
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends_actors.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends_actors.py
index 1e86e3fa9d25..49ccd952c136 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends_actors.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_trends_actors.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
from posthog.schema import (
@@ -33,7 +33,7 @@ funnels_query = FunnelsQuery(
)
-@freeze_time("2021-05-01")
+@time_machine.travel("2021-05-01", tick=False)
class TestFunnelTrendsActors(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_funnel_trend_persons_returns_recordings(self):
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py
index 4b6d545be806..7f3e8ff809c9 100644
--- a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_data_warehouse.py
@@ -3,7 +3,7 @@ import tempfile
from pathlib import Path
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events
from parameterized import parameterized
@@ -219,7 +219,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
"""Data warehouse source matching a person aggregation target."""
table_name = self._setup_data_warehouse()
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
query = LifecycleQuery(
dateRange=DateRange(date_from="-1d"),
interval=IntervalType.DAY,
@@ -261,7 +261,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
results_by_status["new"]["action"],
)
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
for status, expected_name in {
"new": "user-1",
"returning": "user-2",
@@ -288,7 +288,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
"""Data warehouse source matching a group aggregation target."""
table_name = self._setup_group_data_warehouse()
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
query = LifecycleQuery(
dateRange=DateRange(date_from="-1d"),
interval=IntervalType.DAY,
@@ -317,7 +317,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([0.0, 1.0], results_by_status["resurrecting"]["data"])
self.assertEqual([0.0, -1.0], results_by_status["dormant"]["data"])
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
for status, expected_name in {
"new": "org-new",
"returning": "org-returning",
@@ -344,7 +344,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
"""Series-level data warehouse properties filter lifecycle results."""
table_name = self._setup_data_warehouse()
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
query = LifecycleQuery(
dateRange=DateRange(date_from="-1d"),
interval=IntervalType.DAY,
@@ -375,7 +375,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([0.0, 1.0], results_by_status["resurrecting"]["data"])
self.assertEqual([0.0, 0.0], results_by_status["dormant"]["data"])
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
actors_response = ActorsQueryRunner(
team=self.team,
query=ActorsQuery(
@@ -436,7 +436,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
**extra_query_kwargs,
}
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
with self.assertRaises(ValidationError) as context:
LifecycleQueryRunner(
team=self.team,
@@ -449,7 +449,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
"""Data warehouse source matching no aggregation target. Counts compute, but no actors are returned."""
table_name = self._setup_data_warehouse()
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
query = LifecycleQuery(
dateRange=DateRange(date_from="-1d"),
interval=IntervalType.DAY,
@@ -477,7 +477,7 @@ class TestLifecycleDataWarehouse(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([0.0, 1.0], results_by_status["resurrecting"]["data"])
self.assertEqual([0.0, -1.0], results_by_status["dormant"]["data"])
- with freeze_time("2025-11-07T12:00:00Z"):
+ with time_machine.travel("2025-11-07T12:00:00Z", tick=False):
for status in ["new", "returning", "resurrecting", "dormant"]:
with self.subTest(status=status):
actors_response = ActorsQueryRunner(
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py
index 0484cd7daa9f..b90992b84ea6 100644
--- a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_insight_actors.py
@@ -1,6 +1,6 @@
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -36,7 +36,7 @@ class TestLifecycleInsightActors(ClickhouseTestMixin, APIBaseTest):
("p4", ["2020-01-15T12:00:00Z"]),
]
for distinct_id, timestamps in data:
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[distinct_id],
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
index fd9b93b32042..319773594478 100644
--- a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
@@ -1,7 +1,7 @@
from datetime import datetime
from types import SimpleNamespace
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -59,7 +59,7 @@ class TestLifecycleQueryRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTe
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps_and_groups in data:
- with freeze_time(timestamps_and_groups[0][0]):
+ with time_machine.travel(timestamps_and_groups[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -96,7 +96,7 @@ class TestLifecycleQueryRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTe
)
# Create the group on Jan 9th so that the first event on Jan 9th marks it as "new"
- with freeze_time("2020-01-09T12:00:00Z"):
+ with time_machine.travel("2020-01-09T12:00:00Z", tick=False):
create_group(
team_id=self.team.pk,
group_type_index=0,
@@ -360,7 +360,7 @@ class TestLifecycleQueryRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTe
)
# Create company:1 on Jan 9th so that the first event on Jan 9th marks it as "new"
- with freeze_time("2020-01-09T12:00:00Z"):
+ with time_machine.travel("2020-01-09T12:00:00Z", tick=False):
create_group(
team_id=self.team.pk,
group_type_index=1,
@@ -369,7 +369,7 @@ class TestLifecycleQueryRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTe
)
# Create company:2 on Jan 12th so that the first event on Jan 12th marks it as "new"
- with freeze_time("2020-01-12T12:00:00Z"):
+ with time_machine.travel("2020-01-12T12:00:00Z", tick=False):
create_group(
team_id=self.team.pk,
group_type_index=1,
@@ -634,7 +634,7 @@ class TestLifecycleQueryRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTe
)
# Create groups with specific created_at times that are DIFFERENT from person's created_at
- with freeze_time("2020-01-05T12:00:00Z"): # Group created before the test period
+ with time_machine.travel("2020-01-05T12:00:00Z", tick=False): # Group created before the test period
create_group(
team_id=self.team.pk,
group_type_index=0,
@@ -642,7 +642,7 @@ class TestLifecycleQueryRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTe
properties={"name": "early org"},
)
- with freeze_time("2020-01-12T12:00:00Z"): # Group created during the test period
+ with time_machine.travel("2020-01-12T12:00:00Z", tick=False): # Group created during the test period
create_group(
team_id=self.team.pk,
group_type_index=0,
@@ -737,7 +737,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -883,7 +883,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- with freeze_time("2020-01-12T09:00:00Z"):
+ with time_machine.travel("2020-01-12T09:00:00Z", tick=False):
query = LifecycleQuery(
dateRange=DateRange(date_from="-4d", excludeIncompletePeriods=True),
interval=IntervalType.DAY,
@@ -1571,7 +1571,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def test_lifecycle_virtual_person_property_hogql_filter(self):
- with freeze_time("2020-01-12T12:00:00Z"):
+ with time_machine.travel("2020-01-12T12:00:00Z", tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
@@ -1616,7 +1616,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def test_lifecycle_virtual_person_property_filter(self):
- with freeze_time("2020-01-12T12:00:00Z"):
+ with time_machine.travel("2020-01-12T12:00:00Z", tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
@@ -1665,7 +1665,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def test_lifecycle_trends_distinct_id_repeat(self):
- with freeze_time("2020-01-12T12:00:00Z"):
+ with time_machine.travel("2020-01-12T12:00:00Z", tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["p1", "another_p1"],
@@ -1793,7 +1793,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
)
- with freeze_time("2020-01-17T13:01:01Z"):
+ with time_machine.travel("2020-01-17T13:01:01Z", tick=False):
result = (
LifecycleQueryRunner(
team=self.team,
@@ -2327,7 +2327,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2020-01-20T00:00:00Z")
+ @time_machine.travel("2020-01-20T00:00:00Z", tick=False)
def test_lifecycle_interval_boundary_filtering(self, _name, interval, date_from, date_to):
self._create_test_events()
diff --git a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
index a14db3d2dbd1..c0a2808a347f 100644
--- a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner.py
@@ -1,6 +1,6 @@
import dataclasses
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
BaseTest,
@@ -151,7 +151,7 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
)
)
- with freeze_time("2012-01-15T03:21:34.000Z"):
+ with time_machine.travel("2012-01-15T03:21:34.000Z", tick=False):
result = PathsQueryRunner(
query={
"kind": "PathsQuery",
@@ -178,7 +178,7 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[3].target, "3_/about")
self.assertEqual(response[3].value, 1)
- with freeze_time("2012-01-15T03:21:34.000Z"):
+ with time_machine.travel("2012-01-15T03:21:34.000Z", tick=False):
date_from = now() - relativedelta(days=7)
result = PathsQueryRunner(
query={
@@ -1048,7 +1048,7 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0].target, "2_/about")
self.assertEqual(response[0].value, 2)
- @freeze_time("2012-01-15T03:21:34.000Z")
+ @time_machine.travel("2012-01-15T03:21:34.000Z", tick=False)
def test_path_replacements_none_does_not_apply_team_cleaning(self):
"""pathReplacements=None (omitted) should not apply team cleaning — the frontend sets True explicitly."""
_create_person(team_id=self.team.pk, distinct_ids=["person_1"])
@@ -1083,7 +1083,7 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
combined = " ".join(sources_and_targets)
assert "123" in combined or "456" in combined
- @freeze_time("2012-01-15T03:21:34.000Z")
+ @time_machine.travel("2012-01-15T03:21:34.000Z", tick=False)
def test_path_replacements_false_skips_team_cleaning(self):
"""pathReplacements=False should not apply team path cleaning filters."""
_create_person(team_id=self.team.pk, distinct_ids=["person_1"])
@@ -1119,7 +1119,7 @@ class TestPaths(ClickhouseTestMixin, APIBaseTest):
combined = " ".join(sources_and_targets)
assert "123" in combined or "456" in combined
- @freeze_time("2012-01-15T03:21:34.000Z")
+ @time_machine.travel("2012-01-15T03:21:34.000Z", tick=False)
def test_path_replacements_apply_capture_group_backreference_alias(self):
"""A team cleaning alias can reuse regex capture groups via re2 `\\1` syntax. The paths runner
builds its own replaceRegexpAll chain, so this guards backreference substitution on that path
diff --git a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner_ee.py b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner_ee.py
index a500c7ec5f3b..5ab028fbecdd 100644
--- a/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner_ee.py
+++ b/products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner_ee.py
@@ -4,7 +4,7 @@ from typing import Any
from uuid import UUID
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -149,7 +149,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
),
)
- with freeze_time("2012-01-7T03:21:34.000Z"):
+ with time_machine.travel("2012-01-7T03:21:34.000Z", tick=False):
filter = {"stepLimit": 2}
result = PathsQueryRunner(query={"kind": "PathsQuery", "pathsFilter": filter}, team=self.team).run()
assert isinstance(result, CachedPathsQueryResponse)
@@ -169,7 +169,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([p1.uuid], self._get_people_at_path(filter, "1_/1", "2_/2"))
self.assertEqual([], self._get_people_at_path(filter, "2_/2", "3_/3"))
- with freeze_time("2012-01-7T03:21:34.000Z"):
+ with time_machine.travel("2012-01-7T03:21:34.000Z", tick=False):
filter = {"stepLimit": 3}
result = PathsQueryRunner(query={"kind": "PathsQuery", "pathsFilter": filter}, team=self.team).run()
assert isinstance(result, CachedPathsQueryResponse)
@@ -194,7 +194,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual([p1.uuid], self._get_people_at_path(filter, "2_/2", "3_/3"))
- with freeze_time("2012-01-7T03:21:34.000Z"):
+ with time_machine.travel("2012-01-7T03:21:34.000Z", tick=False):
filter = {"stepLimit": 4}
result = PathsQueryRunner(query={"kind": "PathsQuery", "pathsFilter": filter}, team=self.team).run()
assert isinstance(result, CachedPathsQueryResponse)
@@ -228,7 +228,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([p1.uuid], self._get_people_at_path(filter, "3_/3", "4_/4"))
@snapshot_clickhouse_queries
- @freeze_time("2023-05-23T11:00:00.000Z")
+ @time_machine.travel("2023-05-23T11:00:00.000Z", tick=False)
def test_step_conversion_times(self):
_create_person(team_id=self.team.pk, distinct_ids=["fake"])
@@ -885,7 +885,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2023-05-23T11:00:00.000Z")
+ @time_machine.travel("2023-05-23T11:00:00.000Z", tick=False)
def test_event_inclusion_exclusion_filters(self):
# P1 for pageview event
_create_person(team_id=self.team.pk, distinct_ids=["p1"])
@@ -1108,7 +1108,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2023-05-23T11:00:00.000Z")
+ @time_machine.travel("2023-05-23T11:00:00.000Z", tick=False)
def test_event_exclusion_filters_with_wildcard_groups(self):
# P1 for pageview event /2/bar/1/foo
_create_person(team_id=self.team.pk, distinct_ids=["p1"])
@@ -1485,7 +1485,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2023-05-23T11:00:00.000Z")
+ @time_machine.travel("2023-05-23T11:00:00.000Z", tick=False)
def test_respect_session_limits(self):
_create_person(team_id=self.team.pk, distinct_ids=["fake"])
@@ -1929,7 +1929,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result, expected)
@snapshot_clickhouse_queries
- @freeze_time("2023-05-23T11:00:00.000Z")
+ @time_machine.travel("2023-05-23T11:00:00.000Z", tick=False)
def test_wildcard_groups_across_people(self):
# P1 for pageview event /2/bar/1/foo
_create_person(team_id=self.team.pk, distinct_ids=["p1"])
@@ -2060,7 +2060,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
)
@snapshot_clickhouse_queries
- @freeze_time("2023-05-23T11:00:00.000Z")
+ @time_machine.travel("2023-05-23T11:00:00.000Z", tick=False)
def test_wildcard_groups_evil_input(self):
evil_string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!"
# P1 for pageview event /2/bar/1/foo
@@ -3048,7 +3048,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
],
)
- @freeze_time("2012-01-01T03:21:34.000Z")
+ @time_machine.travel("2012-01-01T03:21:34.000Z", tick=False)
@snapshot_clickhouse_queries
def test_recording(self):
# User with 2 matching paths with recordings
@@ -3206,7 +3206,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
self.assertEqual([], matched_recordings[1])
@snapshot_clickhouse_queries
- @freeze_time("2012-01-01T03:21:34.000Z")
+ @time_machine.travel("2012-01-01T03:21:34.000Z", tick=False)
def test_recording_with_no_window_or_session_id(self):
p1 = _create_person(team_id=self.team.pk, distinct_ids=["p1"])
@@ -3262,7 +3262,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.timeout(60)
@snapshot_clickhouse_queries
- @freeze_time("2012-01-01T03:21:34.000Z")
+ @time_machine.travel("2012-01-01T03:21:34.000Z", tick=False)
def test_recording_with_start_and_end(self):
p1 = _create_person(team_id=self.team.pk, distinct_ids=["p1"])
@@ -3367,7 +3367,7 @@ class TestClickhousePaths(ClickhouseTestMixin, APIBaseTest):
@pytest.mark.timeout(60)
@snapshot_clickhouse_queries
- @freeze_time("2012-01-01T03:21:34.000Z")
+ @time_machine.travel("2012-01-01T03:21:34.000Z", tick=False)
def test_recording_for_dropoff(self):
p1 = _create_person(team_id=self.team.pk, distinct_ids=["p1"])
@@ -3691,7 +3691,7 @@ class TestClickhousePathsFunnelSource(ClickhouseTestMixin, APIBaseTest):
)
def _run_paths_query(self, funnel_source: dict, funnel_path_type: str, funnel_step: int) -> list[tuple]:
- with freeze_time("2021-05-08T00:00:00.000Z"):
+ with time_machine.travel("2021-05-08T00:00:00.000Z", tick=False):
result = PathsQueryRunner(
query={
"kind": "PathsQuery",
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
index 348eedbf2027..f1f4929286e4 100644
--- a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
@@ -4,7 +4,7 @@ from pathlib import Path
from typing import Any, Optional
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -6581,7 +6581,7 @@ class TestClickhouseRetentionGroupAggregation(ClickhouseTestMixin, APIBaseTest):
)
def test_retention_with_virtual_person_property_breakdown(self):
- with freeze_time("2020-01-12T12:00:00Z"):
+ with time_machine.travel("2020-01-12T12:00:00Z", tick=False):
# Create person with initial referring domain
_create_person(
team_id=self.team.pk,
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_insight_actors.py b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_insight_actors.py
index 2e7ed900ea0e..a852cd2d589e 100644
--- a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_insight_actors.py
+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_insight_actors.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -51,7 +51,7 @@ class TestStickinessInsightActors(ClickhouseTestMixin, APIBaseTest):
("p4", ["2020-01-15T12:00:00Z"]),
]
for distinct_id, timestamps in data:
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[distinct_id],
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
index 7f8377be26bd..717cce8ac3ca 100644
--- a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Optional, Union
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
BaseTest,
@@ -125,7 +125,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
properties_to_create[key] = type
- with freeze_time(first_timestamp):
+ with time_machine.travel(first_timestamp, tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -322,7 +322,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_stickiness_data_warehouse(self):
table_name = self._setup_data_warehouse()
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self._run_query(
series=[
DataWarehouseNode(
@@ -345,7 +345,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_stickiness_data_warehouse_with_entity_property_filter(self):
table_name = self._setup_data_warehouse()
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self._run_query(
series=[
DataWarehouseNode(
@@ -376,7 +376,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
# both actors in a single interval -> [2, 0, 0, 0, 0, 0, 0].
table_name = self._setup_data_warehouse_with_decoy_timestamp()
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self._run_query(
series=[
DataWarehouseNode(
@@ -454,7 +454,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_interval_hour_last_days(self):
self._create_test_events()
- with freeze_time("2020-01-20T12:00:00Z"):
+ with time_machine.travel("2020-01-20T12:00:00Z", tick=False):
response = self._run_query(interval=IntervalType.HOUR, date_from="-2d", date_to="now")
result = response.results[0]
# 61 = 48 + 12 + 1
@@ -610,7 +610,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_interval_full_weeks(self):
self._create_test_events()
- with freeze_time("2020-01-23T12:00:00Z"):
+ with time_machine.travel("2020-01-23T12:00:00Z", tick=False):
response = self._run_query(interval=IntervalType.WEEK, date_from="-30d", date_to="now")
result = response.results[0]
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_boxplot_trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_boxplot_trends_query_runner.py
index da63a64d639d..51c033580d88 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_boxplot_trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_boxplot_trends_query_runner.py
@@ -2,7 +2,7 @@ from pathlib import Path
from typing import Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -31,11 +31,11 @@ from products.warehouse_sources.backend.facade.testing import create_data_wareho
TEST_BUCKET = "test_storage_bucket-posthog.hogql.datawarehouse.boxplot"
-@freeze_time("2024-01-01T00:00:00Z")
+@time_machine.travel("2024-01-01T00:00:00Z", tick=False)
class TestBoxPlotTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[id],
@@ -571,7 +571,7 @@ class TestBoxPlotTrendsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest
math_property_type="data_warehouse_properties",
)
)
- with freeze_time("2024-01-01T00:00:00Z"):
+ with time_machine.travel("2024-01-01T00:00:00Z", tick=False):
response = BoxPlotTrendsQueryRunner(team=self.team, query=query).calculate()
data = [BoxPlotDatum(**d) for d in response.results]
@@ -601,7 +601,7 @@ class TestBoxPlotTrendsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest
timestamp_field="created",
)
)
- with freeze_time("2024-01-01T00:00:00Z"):
+ with time_machine.travel("2024-01-01T00:00:00Z", tick=False):
response = BoxPlotTrendsQueryRunner(team=self.team, query=query).calculate()
assert response.results == []
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py
index ecf779f374e6..ececf95f7df1 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py
@@ -1,6 +1,6 @@
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from parameterized import parameterized
@@ -25,7 +25,7 @@ from products.product_analytics.backend.hogql_queries.trends.calendar_heatmap_qu
class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[id],
@@ -1304,7 +1304,7 @@ class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
assert response.results.allAggregations == 1, f"Expected 1 total event, got {response.results.allAggregations}"
- @freeze_time("2026-05-01 14:32:11")
+ @time_machine.travel("2026-05-01 14:32:11", tick=False)
def test_explicit_date_keeps_relative_window_exact(self):
# Without explicitDate, "-7d" truncates the lower bound to start-of-day and rounds the
# upper bound to end-of-day, so the window spans 8 calendar days.
@@ -1366,7 +1366,7 @@ class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
"2023-12-03 00:10:00", # Sunday 00:00 — same session, next day/hour
"2023-12-03 01:30:00", # Sunday 01:00
]
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["userA"], properties={"name": "userA"})
for timestamp in timestamps:
_create_event(
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_formula.py b/products/product_analytics/backend/hogql_queries/trends/test/test_formula.py
index 515438689f63..407b6aba66a3 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_formula.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_formula.py
@@ -1,6 +1,6 @@
from typing import Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -50,7 +50,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
)
s1 = str(uuid7("2020-01-02T13:01:01Z", 1))
- with freeze_time("2020-01-02T13:01:01Z"):
+ with time_machine.travel("2020-01-02T13:01:01Z", tick=False):
_create_event(
team=self.team,
event="session start",
@@ -85,7 +85,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
"$group_0": "org:5",
},
)
- with freeze_time("2020-01-03T13:01:01Z"):
+ with time_machine.travel("2020-01-03T13:01:01Z", tick=False):
_create_event(
team=self.team,
event="session start",
@@ -97,7 +97,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
"$group_0": "org:5",
},
)
- with freeze_time("2020-01-03T13:04:01Z"):
+ with time_machine.travel("2020-01-03T13:04:01Z", tick=False):
_create_event(
team=self.team,
event="session start",
@@ -166,7 +166,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
}
if extra:
query_dict.update(extra)
- with freeze_time(run_at or "2020-01-04T13:01:01Z"):
+ with time_machine.travel(run_at or "2020-01-04T13:01:01Z", tick=False):
trend_query = TrendsQuery(**query_dict)
tqr = TrendsQueryRunner(team=self.team, query=trend_query)
return tqr.calculate().results
@@ -301,7 +301,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_formula_with_unique_sessions(self):
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
{
"series": [
@@ -317,7 +317,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_regression_formula_with_unique_sessions_2x_and_duration_filter(self):
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
{
"series": [
@@ -346,7 +346,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_regression_formula_with_unique_sessions_2x_and_duration_filter_2x(self):
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
{
"series": [
@@ -387,7 +387,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_regression_formula_with_session_duration_aggregation(self):
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
{
"series": [
@@ -415,7 +415,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_aggregated_one_without_events(self):
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
{
"trendsFilter": {
@@ -513,7 +513,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[3]["breakdown_value"], "$$_posthog_breakdown_null_$$")
def test_breakdown_counts_of_different_events_one_without_events(self):
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
{
"trendsFilter": {"display": "ActionsLineGraph", "formula": "B / A"},
@@ -915,7 +915,7 @@ class TestFormula(ClickhouseTestMixin, APIBaseTest):
def test_formula_with_hogql_math_no_matching_events(self):
# Regression test: formula with HogQL math should not crash when one series has no matching events
# (math="hogql" has no ifNull wrapper, so NULL values can propagate into FormulaAST)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
{
"trendsFilter": {
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_slope_graph_trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_slope_graph_trends_query_runner.py
index a6b9f1b471e7..bedd2932b2d2 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_slope_graph_trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_slope_graph_trends_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -28,11 +28,11 @@ from products.product_analytics.backend.hogql_queries.trends.slope_graph_trends_
)
-@freeze_time("2024-06-15T12:00:00Z")
+@time_machine.travel("2024-06-15T12:00:00Z", tick=False)
class TestSlopeGraphTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
for distinct_id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
_create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties={"name": distinct_id})
for timestamp, *rest in timestamps:
_create_event(
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
index cc615db3f5cd..9a3494331e72 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
@@ -6,7 +6,7 @@ from typing import Any, Optional, Union, cast
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -191,7 +191,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
if use_time:
freeze_args = freeze_with_time
- with freeze_time(freeze_args[0]):
+ with time_machine.travel(freeze_args[0], tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -199,7 +199,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$bool_prop": True},
)
- with freeze_time(freeze_args[1]):
+ with time_machine.travel(freeze_args[1], tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -213,7 +213,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$bool_prop": False},
)
self._create_event(team=self.team, event="sign up", distinct_id="blabla")
- with freeze_time(freeze_args[2]):
+ with time_machine.travel(freeze_args[2], tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -243,7 +243,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def _create_breakdown_events(self):
freeze_without_time = ["2020-01-02"]
- with freeze_time(freeze_without_time[0]):
+ with time_machine.travel(freeze_without_time[0], tick=False):
for i in range(25):
self._create_event(
team=self.team,
@@ -256,7 +256,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def _create_breakdown_url_events(self):
freeze_without_time = ["2020-01-02"]
- with freeze_time(freeze_without_time[0]):
+ with time_machine.travel(freeze_without_time[0], tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -290,7 +290,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"fruit": "tomato"},
)
- with freeze_time("2020-01-01 00:06:02"):
+ with time_machine.travel("2020-01-01 00:06:02", tick=False):
self._create_event(
team=self.team,
event="viewed video",
@@ -316,7 +316,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$group_0": "kiki"},
)
- with freeze_time("2020-01-03 19:06:34"):
+ with time_machine.travel("2020-01-03 19:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -324,7 +324,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$group_0": "kiki"},
)
- with freeze_time("2020-01-04 23:17:00"):
+ with time_machine.travel("2020-01-04 23:17:00", tick=False):
self._create_event(
team=self.team,
event="viewed video",
@@ -332,7 +332,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"color": "red", "$group_0": "kiki"},
)
- with freeze_time("2020-01-05 19:06:34"):
+ with time_machine.travel("2020-01-05 19:06:34", tick=False):
self._create_event(
team=self.team,
event="viewed video",
@@ -360,7 +360,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_trends_per_day(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
# with self.assertNumQueries(16):
response = self._run(
Filter(
@@ -387,7 +387,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
type=PropertyDefinition.Type.EVENT,
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
self._run(
Filter(
team=self.team,
@@ -435,7 +435,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
type=PropertyDefinition.Type.EVENT,
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
self._run(
Filter(
team=self.team,
@@ -483,7 +483,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
type=PropertyDefinition.Type.EVENT,
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
self._run(
Filter(
team=self.team,
@@ -525,7 +525,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_trends_per_day_48hours(self):
self._create_events()
- with freeze_time("2020-01-03T13:00:01Z"):
+ with time_machine.travel("2020-01-03T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -544,7 +544,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_trends_per_day_cumulative(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -566,7 +566,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_trends_per_day_dau_cumulative(self):
self._create_events()
- with freeze_time("2020-01-03T13:00:01Z"):
+ with time_machine.travel("2020-01-03T13:00:01Z", tick=False):
self._create_person(
team_id=self.team.pk,
distinct_ids=["new_user"],
@@ -579,7 +579,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$bool_prop": False},
)
flush_persons_and_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -609,7 +609,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
group_type_index=0,
)
self._create_event_count_per_actor_events()
- with freeze_time("2020-01-06T13:00:01Z"):
+ with time_machine.travel("2020-01-06T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -641,7 +641,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
group_type_index=0,
)
self._create_event_count_per_actor_events()
- with freeze_time("2020-01-06T13:00:01Z"):
+ with time_machine.travel("2020-01-06T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -668,7 +668,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_trends_breakdown_cumulative(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -698,7 +698,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
def test_trends_breakdown_normalize_url(self):
self._create_breakdown_url_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -720,7 +720,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_trends_single_aggregate_dau(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -733,7 +733,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -759,7 +759,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -791,7 +791,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$math_prop": 3},
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -805,7 +805,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$math_prop": 4},
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -824,7 +824,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -929,7 +929,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# Fourth session lasted 15 seconds
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -948,7 +948,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -1052,7 +1052,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# Fourth session lasted 15 seconds
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -1097,7 +1097,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
name="cohort3",
groups=[{"properties": [{"key": "name", "value": "Jill", "type": "person"}]}],
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1129,7 +1129,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$browser": "Safari"},
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1142,7 +1142,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_id="Jane",
properties={"$some_property": "value", "$browser": "Safari"},
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -1172,7 +1172,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1204,7 +1204,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$browser": "Safari"},
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1218,7 +1218,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$browser": "Safari"},
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1243,7 +1243,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1275,7 +1275,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$browser": "Safari", "$variant": "2"},
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1289,7 +1289,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$browser": "Safari", "$variant": "2"},
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -1327,7 +1327,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1380,7 +1380,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
person_id="00000000-0000-0000-0000-000000000000",
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1408,7 +1408,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
person_id="00000000-0000-0000-0000-000000000000",
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1428,7 +1428,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result["aggregated_value"], 5)
# multiple
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1453,7 +1453,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1485,7 +1485,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$math_prop": 3},
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -1504,7 +1504,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$some_property"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1524,7 +1524,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -1645,7 +1645,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
# Fourth session lasted 15 seconds
# single breakdown
- with freeze_time("2020-01-04T13:00:33Z"):
+ with time_machine.travel("2020-01-04T13:00:33Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1674,7 +1674,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual([resp["aggregated_value"] for resp in daily_response], [12.5, 10, 1])
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -1704,7 +1704,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# multiple breakdowns
- with freeze_time("2020-01-04T13:00:33Z"):
+ with time_machine.travel("2020-01-04T13:00:33Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1733,7 +1733,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual([resp["aggregated_value"] for resp in daily_response], [12.5, 10, 1])
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -1856,7 +1856,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# Fourth session lasted 15 seconds
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1885,7 +1885,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(sorted([resp["aggregated_value"] for resp in daily_response]), [5.0, 10.0])
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1916,7 +1916,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_trends_any_event_total_count(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response1 = self._run(
Filter(
team=self.team,
@@ -1944,7 +1944,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$math_prop", "$some_property"])
def test_trends_breakdown_with_math_func(self):
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
for i in range(20):
self._create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"])
self._create_event(
@@ -1969,7 +1969,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# single breakdown
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -1993,7 +1993,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertTrue("value_21" in breakdown_vals)
# multiple breakdown
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -2019,7 +2019,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_trends_compare_day_interval_relative_range(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -2070,7 +2070,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[1]["labels"][4], "25-Dec-2019")
self.assertEqual(response[1]["data"][4], 0.0)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
no_compare_response = self._run(
Filter(
team=self.team,
@@ -2087,7 +2087,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_trends_compare_day_interval_fixed_range_single(self):
self._create_events(use_time=True)
- with freeze_time("2020-01-02T20:17:00Z"):
+ with time_machine.travel("2020-01-02T20:17:00Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -2127,7 +2127,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_trends_compare_hour_interval_relative_range(self):
self._create_events(use_time=True)
- with freeze_time("2020-01-02T20:17:00Z"):
+ with time_machine.travel("2020-01-02T20:17:00Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -2257,7 +2257,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def _test_events_with_dates(self, dates: list[str], result, query_time=None, **filter_params):
self._create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
for time in dates:
- with freeze_time(time):
+ with time_machine.travel(time, tick=False):
self._create_event(
event="event_name",
team=self.team,
@@ -2266,7 +2266,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
if query_time:
- with freeze_time(query_time):
+ with time_machine.travel(query_time, tick=False):
response = self._run(
Filter(
team=self.team,
@@ -2978,7 +2978,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$some_property"])
def test_property_filtering(self):
self._create_events()
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -3018,7 +3018,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
timestamp="2020-01-02 00:06:45",
)
- with freeze_time("2020-01-04T12:01:01Z"):
+ with time_machine.travel("2020-01-04T12:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -3135,7 +3135,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# Fifth session lasted 5 seconds
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -3153,7 +3153,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -3293,7 +3293,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
else {"breakdowns": [{"property": "$some_property"}]}
)
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -3312,7 +3312,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team,
)
- with freeze_time("2020-01-04T13:00:05Z"):
+ with time_machine.travel("2020-01-04T13:00:05Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -3426,7 +3426,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# Second session lasted 96 hours = a lot of seconds
- with freeze_time("2020-01-06T13:00:01Z"):
+ with time_machine.travel("2020-01-06T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -3523,7 +3523,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_person_on_events_v2
@snapshot_clickhouse_queries
def test_filter_events_by_precalculated_cohort(self):
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
self._create_person(
team_id=self.team.pk,
distinct_ids=["person_1"],
@@ -3579,7 +3579,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_interval_filtering_hour(self):
self._create_events(use_time=True)
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
response = self._run(
Filter(
data={
@@ -3598,7 +3598,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_interval_filtering_week(self):
self._create_events(use_time=True)
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -3620,7 +3620,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_interval_filtering_month(self):
self._create_events(use_time=True)
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -3642,10 +3642,10 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_interval_filtering_today_hourly(self):
self._create_events(use_time=True)
- with freeze_time("2020-01-02 23:30"):
+ with time_machine.travel("2020-01-02 23:30", tick=False):
self._create_event(team=self.team, event="sign up", distinct_id="blabla")
- with freeze_time("2020-01-02T23:31:00Z"):
+ with time_machine.travel("2020-01-02T23:31:00Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -3819,11 +3819,11 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(action_response[0]["data"], [0, 1, 1, 0, 0, 0, 0])
def test_trends_for_non_existing_action(self):
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(Filter(data={"actions": [{"id": 50000000}]}), self.team)
self.assertEqual(len(response), 0)
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(Filter(data={"events": [{"id": "DNE"}]}), self.team)
self.assertEqual(response[0]["data"], [0, 0, 0, 0, 0, 0, 0, 0])
@@ -3846,7 +3846,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
self._create_person(team_id=self.team.pk, properties={"bar": "aa"}, distinct_ids=["d4"])
- with freeze_time("2020-01-02 16:34:34"):
+ with time_machine.travel("2020-01-02 16:34:34", tick=False):
self._create_event(team=self.team, event="$pageview", distinct_id="d1")
self._create_event(team=self.team, event="$pageview", distinct_id="d2")
self._create_event(team=self.team, event="$pageview", distinct_id="d3")
@@ -3863,7 +3863,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
],
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -3874,7 +3874,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response), 1)
self.assertEqual(response[0]["count"], 3)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response_with_email_filter = self._run(
Filter(
team=self.team,
@@ -3898,11 +3898,11 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_dau_filtering(self):
sign_up_action, person = self._create_events()
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
self._create_person(team_id=self.team.pk, distinct_ids=["someone_else"])
self._create_event(team=self.team, event="sign up", distinct_id="someone_else")
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -4058,7 +4058,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$some_property"])
def test_per_entity_filtering(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4177,7 +4177,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_person_property_filtering(self):
self._create_multiple_people()
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4200,7 +4200,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
# This test needs to choose the right materialised column for it to pass.
# For resiliency, we reverse the filter as well.
self._create_multiple_people()
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4217,7 +4217,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
self.assertEqual(response[0]["data"][5], 0)
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4237,7 +4237,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(person_properties=["name"])
def test_entity_person_property_filtering(self):
self._create_multiple_people()
- with freeze_time("2020-01-04"):
+ with time_machine.travel("2020-01-04", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4272,7 +4272,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
timestamp="2020-01-04T12:00:00Z",
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -4313,7 +4313,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
action = _create_action(name="watched movie", team=self.team)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -4384,7 +4384,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
timestamp="2020-01-04T12:00:00Z",
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4414,7 +4414,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# test hour
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4434,7 +4434,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0]["data"][192], 3.0)
# test week
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4457,7 +4457,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0]["data"][:5], [0.0, 0.0, 0.0, 0.0, 1.0])
# test month
- with freeze_time("2020-01-02"):
+ with time_machine.travel("2020-01-02", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4476,11 +4476,11 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0]["labels"][4], "Jan 2020")
self.assertEqual(response[0]["data"][4], 4.0)
- with freeze_time("2020-01-02 23:30"):
+ with time_machine.travel("2020-01-02 23:30", tick=False):
self._create_event(team=self.team, event="sign up", distinct_id="blabla")
# test today + hourly
- with freeze_time("2020-01-02T23:31:00Z"):
+ with time_machine.travel("2020-01-02T23:31:00Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4518,7 +4518,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
}
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -4613,7 +4613,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
timestamp="2020-01-04T12:00:00Z",
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -4640,7 +4640,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
person1, person2, person3, person4 = self._create_multiple_people()
# single breakdown
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -4676,7 +4676,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response["count"], 3)
# multiple breakdowns
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -4747,7 +4747,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
timestamp=datetime(2020, 1, 1, 12),
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -4782,7 +4782,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
if response["breakdown_value"] == "person3":
self.assertEqual(response["count"], 3)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -4822,7 +4822,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response["count"], 3)
def test_breakdown_by_property_pie(self):
- with freeze_time("2020-01-01T12:00:00Z"): # Fake created_at for easier assertions
+ with time_machine.travel("2020-01-01T12:00:00Z", tick=False): # Fake created_at for easier assertions
self._create_person(team_id=self.team.pk, distinct_ids=["person1"], immediate=True)
self._create_person(team_id=self.team.pk, distinct_ids=["person2"], immediate=True)
self._create_person(team_id=self.team.pk, distinct_ids=["person3"], immediate=True)
@@ -4874,7 +4874,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"fake_prop": "value_1"},
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
filters = {
"date_from": "-14d",
"breakdown": "fake_prop",
@@ -4912,7 +4912,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_breakdown_by_person_property_pie(self):
self._create_multiple_people()
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -4945,7 +4945,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdown_value": "person3", "aggregated_value": 1}.items(), event_response[2].items()
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -5004,7 +5004,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
}
# single breakdown
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
data={
@@ -5025,7 +5025,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# multiple breakdowns
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
data={
@@ -5167,7 +5167,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_bar_chart_by_value(self):
self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
# with self.assertNumQueries(16):
response = self._run(
Filter(
@@ -5194,7 +5194,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
self._create_person(team_id=self.team.pk, distinct_ids=["third"])
- with freeze_time("2019-12-24 03:45:34"):
+ with time_machine.travel("2019-12-24 03:45:34", tick=False):
self._create_event(team=self.team, event="sign up", distinct_id="blabla")
self._create_event(
team=self.team, event="sign up", distinct_id="blabla"
@@ -5203,7 +5203,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self._create_event(team=self.team, event="sign up", distinct_id="third")
with override_instance_config("AGGREGATE_BY_DISTINCT_IDS_TEAMS", f"{self.team.pk},4"):
- with freeze_time("2019-12-31T13:00:01Z"):
+ with time_machine.travel("2019-12-31T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -5217,7 +5217,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(daily_response[0]["data"][0], 3)
- with freeze_time("2019-12-31T13:00:01Z"):
+ with time_machine.travel("2019-12-31T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -5238,7 +5238,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(daily_response[0]["data"][0], 2)
# single breakdown person props
- with freeze_time("2019-12-31T13:00:01Z"):
+ with time_machine.travel("2019-12-31T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -5257,7 +5257,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(daily_response[1]["label"], "$$_posthog_breakdown_null_$$")
# multiple breakdown person props
- with freeze_time("2019-12-31T13:00:01Z"):
+ with time_machine.travel("2019-12-31T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -5275,7 +5275,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(daily_response[1]["label"], "$$_posthog_breakdown_null_$$")
# MAU
- with freeze_time("2019-12-31T13:00:03Z"):
+ with time_machine.travel("2019-12-31T13:00:03Z", tick=False):
monthly_response = self._run(
Filter(
team=self.team,
@@ -5288,7 +5288,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(monthly_response[0]["data"][0], 3) # this would be 2 without the aggregate hack
- with freeze_time("2019-12-31T13:00:01Z"):
+ with time_machine.travel("2019-12-31T13:00:01Z", tick=False):
weekly_response = self._run(
Filter(
team=self.team,
@@ -5308,7 +5308,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
property_type="String",
type=PropertyDefinition.Type.EVENT,
)
- with freeze_time("2019-12-31T13:00:01Z"):
+ with time_machine.travel("2019-12-31T13:00:01Z", tick=False):
daily_response = self._run(
Filter(
team=self.team,
@@ -5324,7 +5324,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$some_property"])
def test_breakdown_filtering_limit(self):
self._create_breakdown_events()
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5394,7 +5394,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
}
# single breakdown
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -5421,7 +5421,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEntityResponseEqual(event_response, action_response)
# multiple
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -5464,7 +5464,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
}
# test breakdown filtering
# single breakdown
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5487,7 +5487,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(sum(response[3]["data"]), 1)
# test breakdown filtering
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5515,7 +5515,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- with freeze_time("2020-01-01 00:06:34"):
+ with time_machine.travel("2020-01-01 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -5553,7 +5553,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$some_property": "value", "$browser": "Safari", "$variant": ""},
)
- with freeze_time("2020-01-02 00:06:34"):
+ with time_machine.travel("2020-01-02 00:06:34", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -5586,7 +5586,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
],
}
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5607,7 +5607,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[5]["label"], "sign up - Safari::$$_posthog_breakdown_null_$$")
# should group to "other" breakdowns
- with freeze_time("2020-01-04T13:00:01Z"):
+ with time_machine.travel("2020-01-04T13:00:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5752,7 +5752,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$current_url", "$os", "$browser"])
def test_breakdown_filtering_with_properties(self):
- with freeze_time("2020-01-03T13:01:01Z"):
+ with time_machine.travel("2020-01-03T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -5773,7 +5773,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
"$os": "Windows",
},
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -5797,7 +5797,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
filters: list[dict[str, Any]] = [{"breakdown": "$current_url"}, {"breakdowns": [{"property": "$current_url"}]}]
for breakdown_filter in filters:
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5837,7 +5837,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_breakdown_filtering_with_properties_in_new_format(self):
- with freeze_time("2020-01-03T13:01:01Z"):
+ with time_machine.travel("2020-01-03T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -5858,7 +5858,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
"$os": "Mac",
},
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -5885,7 +5885,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$current_url"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5923,7 +5923,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response[0]["breakdown_value"], ["second url"])
# AND filter properties with disjoint set means results should be empty
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -5972,11 +5972,11 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla3"],
properties={"$some_prop": "some_val2", "filter_prop": "filter_val"},
)
- with freeze_time("2020-01-02T13:01:01Z"):
+ with time_machine.travel("2020-01-02T13:01:01Z", tick=False):
self._create_event(team=self.team, event="sign up", distinct_id="blabla")
self._create_event(team=self.team, event="sign up", distinct_id="blabla2")
self._create_event(team=self.team, event="sign up", distinct_id="blabla3")
- with freeze_time("2020-01-03T13:01:01Z"):
+ with time_machine.travel("2020-01-03T13:01:01Z", tick=False):
self._create_event(team=self.team, event="sign up", distinct_id="blabla")
self._create_event(team=self.team, event="sign up", distinct_id="blabla2")
self._create_event(team=self.team, event="sign up", distinct_id="blabla3")
@@ -5986,7 +5986,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$some_prop", "type": "person"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
event_response = self._run(
Filter(
team=self.team,
@@ -6018,7 +6018,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$some_property"])
def test_dau_with_breakdown_filtering(self):
sign_up_action, _ = self._create_events()
- with freeze_time("2020-01-02T13:01:01Z"):
+ with time_machine.travel("2020-01-02T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -6031,7 +6031,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$some_property"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -6068,7 +6068,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_dau_with_breakdown_filtering_with_sampling(self):
sign_up_action, _ = self._create_events()
- with freeze_time("2020-01-02T13:01:01Z"):
+ with time_machine.travel("2020-01-02T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -6081,7 +6081,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$some_property"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -6120,7 +6120,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$os", "$some_property"])
def test_dau_with_breakdown_filtering_with_prop_filter(self):
sign_up_action, _ = self._create_events()
- with freeze_time("2020-01-02T13:01:01Z"):
+ with time_machine.travel("2020-01-02T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -6133,7 +6133,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$some_property"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -6185,7 +6185,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
{"breakdowns": [{"property": "$some_prop", "type": "person"}]},
]
for breakdown_filter in filters:
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -6242,7 +6242,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
],
)
- with freeze_time("2020-01-02T13:01:01Z"):
+ with time_machine.travel("2020-01-02T13:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -6250,7 +6250,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"$current_url": "https://posthog.com/feedback/1234"},
)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -6308,7 +6308,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
cohort.calculate_people_ch(pending_version=0)
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
action_response = self._run(
Filter(
team=self.team,
@@ -6830,7 +6830,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
group_type_index=0,
)
self._create_event_count_per_actor_events()
- with freeze_time("2020-01-19"):
+ with time_machine.travel("2020-01-19", tick=False):
self._create_event(
team=self.team,
event="viewed video",
@@ -7409,7 +7409,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self._create_events()
# test breakdown filtering
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -7481,7 +7481,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
cohort2.calculate_people_ch(pending_version=0)
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True): # Normally this is False in tests
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
res = self._run(
Filter(
team=self.team,
@@ -7537,7 +7537,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
cohort1.calculate_people_ch(pending_version=0)
with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True): # Normally this is False in tests
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
res = self._run(
Filter(
team=self.team,
@@ -7667,7 +7667,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
query_time = datetime(2020, 1, 5, 10, 1, 1, tzinfo=ZoneInfo(self.team.timezone))
- with freeze_time(query_time):
+ with time_machine.travel(query_time, tick=False):
response = self._run(
Filter(
team=self.team,
@@ -7862,7 +7862,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
timestamp="2020-01-06T00:30:01", # Shouldn't be included anywhere
)
- with freeze_time(datetime(2020, 1, 5, 5, 0, tzinfo=ZoneInfo(self.team.timezone))):
+ with time_machine.travel(datetime(2020, 1, 5, 5, 0, tzinfo=ZoneInfo(self.team.timezone)), tick=False):
response = self._run(
Filter(
data={
@@ -7890,7 +7890,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# DAU
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -7926,7 +7926,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
],
)
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -7959,7 +7959,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
],
)
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -7987,7 +7987,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
)
# breakdown + DAU
- with freeze_time("2020-01-05T13:01:01Z"):
+ with time_machine.travel("2020-01-05T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -8012,7 +8012,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team.save()
self._create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- with freeze_time("2022-11-03T01:01:01Z"):
+ with time_machine.travel("2022-11-03T01:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -8024,7 +8024,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2022-11-10T01:01:01Z"):
+ with time_machine.travel("2022-11-10T01:01:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -8036,7 +8036,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2022-11-17T08:30:01Z"):
+ with time_machine.travel("2022-11-17T08:30:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -8048,7 +8048,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2022-11-24T08:30:01Z"):
+ with time_machine.travel("2022-11-24T08:30:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -8060,7 +8060,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2022-11-30T08:30:01Z"):
+ with time_machine.travel("2022-11-30T08:30:01Z", tick=False):
self._create_event(
team=self.team,
event="sign up",
@@ -8072,7 +8072,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2022-11-30T13:01:01Z"):
+ with time_machine.travel("2022-11-30T13:01:01Z", tick=False):
response = self._run(
Filter(
team=self.team,
@@ -8130,7 +8130,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team.save()
# TRICKY: This is the previous UTC day in Asia/Tokyo
- with freeze_time(datetime(2020, 1, 26, 3, 0, tzinfo=ZoneInfo(self.team.timezone))):
+ with time_machine.travel(datetime(2020, 1, 26, 3, 0, tzinfo=ZoneInfo(self.team.timezone)), tick=False):
# Total volume query
response_sunday = self._run(
Filter(
@@ -8151,7 +8151,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team.save()
# TRICKY: This is the previous UTC day in Asia/Tokyo
- with freeze_time(datetime(2020, 1, 26, 3, 0, tzinfo=ZoneInfo(self.team.timezone))):
+ with time_machine.travel(datetime(2020, 1, 26, 3, 0, tzinfo=ZoneInfo(self.team.timezone)), tick=False):
# Total volume query
response_monday = self._run(
Filter(
@@ -8367,7 +8367,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
# 1. Having a JOIN
# 2. Having multiple properties that filter on the same value
- with freeze_time("2020-01-04T13:01:01Z"):
+ with time_machine.travel("2020-01-04T13:01:01Z", tick=False):
self._run(
Filter(
team=self.team,
@@ -8717,7 +8717,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.team.save()
self._create_event_count_per_actor_events()
- with freeze_time("2020-01-03 19:06:34"):
+ with time_machine.travel("2020-01-03 19:06:34", tick=False):
self._create_person(team_id=self.team.pk, distinct_ids=["another_user"])
self._create_event(
team=self.team,
@@ -9035,7 +9035,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(res[0][0]["distinct_ids"], ["person1"])
- @freeze_time("2020-01-01")
+ @time_machine.travel("2020-01-01", tick=False)
@snapshot_clickhouse_queries
def test_breakdown_by_group_props_person_on_events(self):
self._create_groups()
@@ -9351,7 +9351,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
response = self._run(filter, self.team)
self.assertEqual(response[0]["count"], 1)
- @freeze_time("2020-01-01")
+ @time_machine.travel("2020-01-01", tick=False)
@snapshot_clickhouse_queries
def test_filtering_by_multiple_groups_person_on_events(self):
create_group_type_mapping_without_created_at(
@@ -9474,7 +9474,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time("2020-01-03 13:06:02"):
+ with time_machine.travel("2020-01-03 13:06:02", tick=False):
response = self._run(filter, self.team)
self.assertEqual(len(response), 1)
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py
index 5c00998adaca..91c04d050015 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_actors_query_builder.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Optional, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from parameterized import parameterized
@@ -228,7 +228,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2022-06-15T12:00:00.000Z"):
+ with time_machine.travel("2022-06-15T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query),
"greaterOrEquals(timestamp, toDateTime('2022-06-07 22:00:00.000000')), lessOrEquals(timestamp, toDateTime('2022-06-15 21:59:59.999999'))",
@@ -266,7 +266,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2022-06-15T12:00:00.000Z"):
+ with time_machine.travel("2022-06-15T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, compare_value=Compare.CURRENT),
"greaterOrEquals(timestamp, toDateTime('2022-06-07 22:00:00.000000')), lessOrEquals(timestamp, toDateTime('2022-06-15 21:59:59.999999'))",
@@ -287,7 +287,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2022-06-15T12:00:00.000Z"):
+ with time_machine.travel("2022-06-15T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, compare_value=Compare.CURRENT),
"greaterOrEquals(timestamp, toDateTime('2022-06-07 22:00:00.000000')), lessOrEquals(timestamp, toDateTime('2022-06-15 21:59:59.999999'))",
@@ -303,7 +303,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
update={"series": [EventsNode(event="$pageview", math=BaseMathType.WEEKLY_ACTIVE)]}, deep=True
)
- with freeze_time("2024-05-30T12:00:00.000Z"):
+ with time_machine.travel("2024-05-30T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, time_frame="2024-05-27"),
"greaterOrEquals(timestamp, minus(toDateTime('2024-05-26 22:00:00.000000'), toIntervalDay(6))), less(timestamp, toDateTime('2024-05-27 22:00:00.000000'))",
@@ -319,7 +319,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2024-05-30T12:00:00.000Z"):
+ with time_machine.travel("2024-05-30T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(
trends_query=trends_query, time_frame="2024-05-27", compare_value=Compare.CURRENT
@@ -343,7 +343,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2024-05-30T12:00:00.000Z"):
+ with time_machine.travel("2024-05-30T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(
trends_query=trends_query, time_frame="2024-05-27", compare_value=Compare.CURRENT
@@ -367,7 +367,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2024-05-30T12:00:00.000Z"):
+ with time_machine.travel("2024-05-30T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query),
"greaterOrEquals(timestamp, minus(toDateTime('2024-05-30 21:59:59.999999'), toIntervalDay(6))), lessOrEquals(timestamp, toDateTime('2024-05-30 21:59:59.999999'))",
@@ -384,7 +384,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
deep=True,
)
- with freeze_time("2024-05-30T12:00:00.000Z"):
+ with time_machine.travel("2024-05-30T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, compare_value=Compare.PREVIOUS),
"greaterOrEquals(timestamp, minus(toDateTime('2024-05-23 21:59:59.999999'), toIntervalDay(6))), lessOrEquals(timestamp, toDateTime('2024-05-23 21:59:59.999999'))",
@@ -396,7 +396,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
update={"series": [EventsNode(event="$pageview", math=BaseMathType.MONTHLY_ACTIVE)]}, deep=True
)
- with freeze_time("2024-05-30T12:00:00.000Z"):
+ with time_machine.travel("2024-05-30T12:00:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, time_frame="2024-05-27"),
"greaterOrEquals(timestamp, minus(toDateTime('2024-05-26 22:00:00.000000'), toIntervalDay(29))), less(timestamp, toDateTime('2024-05-27 22:00:00.000000'))",
@@ -409,7 +409,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
update={"dateRange": DateRange(date_from="2024-05-08T14:29:13.634000Z", date_to=None, explicitDate=True)},
deep=True,
)
- with freeze_time("2024-05-08T15:32:00.000Z"):
+ with time_machine.travel("2024-05-08T15:32:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, time_frame="2024-05-08"),
"greaterOrEquals(timestamp, toDateTime('2024-05-08 14:29:13.634000')), lessOrEquals(timestamp, toDateTime('2024-05-08 15:32:00.000000'))",
@@ -424,7 +424,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
},
deep=True,
)
- with freeze_time("2024-05-08T15:32:00.000Z"):
+ with time_machine.travel("2024-05-08T15:32:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, time_frame="2024-05-08"),
"greaterOrEquals(timestamp, toDateTime('2024-05-08 14:29:13.634000')), lessOrEquals(timestamp, toDateTime('2024-05-08 14:32:57.692000'))",
@@ -441,7 +441,7 @@ class TestTrendsActorsQueryBuilder(BaseTest):
},
deep=True,
)
- with freeze_time("2024-05-08T15:32:00.000Z"):
+ with time_machine.travel("2024-05-08T15:32:00.000Z", tick=False):
self.assertEqual(
self._get_date_where_sql(trends_query=trends_query, time_frame="2024-05-08"),
"greaterOrEquals(timestamp, greatest(minus(toDateTime('2024-05-07 22:00:00.000000'), toIntervalDay(29)), toDateTime('2024-05-08 14:29:13.634000'))), less(timestamp, least(toDateTime('2024-05-08 22:00:00.000000'), toDateTime('2024-05-08 14:32:57.692000')))",
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_breakdown_empty_null_properties.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_breakdown_empty_null_properties.py
index f3500a95b951..29458788c832 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_breakdown_empty_null_properties.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_breakdown_empty_null_properties.py
@@ -8,7 +8,7 @@ with these property states are correctly counted and returned.
Regression test for: https://github.com/PostHog/posthog/issues/40577
"""
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from django.test import override_settings
@@ -33,7 +33,7 @@ from products.product_analytics.backend.hogql_queries.trends.trends_query_runner
class TestTrendsBreakdownEmptyNullProperties(ClickhouseTestMixin, APIBaseTest):
"""Test breakdown behavior with null, empty string, and missing properties."""
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_breakdown_with_null_empty_and_missing_properties(self):
"""
Test that breakdown correctly handles:
@@ -166,7 +166,7 @@ class TestTrendsBreakdownEmptyNullProperties(ClickhouseTestMixin, APIBaseTest):
"Actors query should return all users with null, empty string, or missing property",
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_multiple_breakdown_with_null_empty_and_missing_properties(self):
"""
Test that multiple breakdowns correctly handle null/empty/missing properties.
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py
index bb1fab907a92..32f7a88eda39 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_data_warehouse_query.py
@@ -1,7 +1,7 @@
from datetime import datetime
from pathlib import Path
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
BaseTest,
ClickhouseTestMixin,
@@ -153,7 +153,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -204,7 +204,10 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with override_instance_config("AGGREGATE_BY_DISTINCT_IDS_TEAMS", f"{self.team.pk}"), freeze_time("2023-01-07"):
+ with (
+ override_instance_config("AGGREGATE_BY_DISTINCT_IDS_TEAMS", f"{self.team.pk}"),
+ time_machine.travel("2023-01-07", tick=False),
+ ):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -229,7 +232,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -255,7 +258,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -298,7 +301,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -330,7 +333,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
properties=[DataWarehousePropertyFilter(key="prop_1", value="a", operator=PropertyOperator.EXACT)],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -356,7 +359,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
breakdownFilter=BreakdownFilter(breakdown_type=BreakdownType.DATA_WAREHOUSE, breakdown="prop_1"),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -394,7 +397,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
assert len(response.results) == 4
@@ -442,7 +445,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
assert len(response.results) == 2
@@ -550,7 +553,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -605,7 +608,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
breakdownFilter=BreakdownFilter(breakdown_type=BreakdownType.DATA_WAREHOUSE, breakdown="prop_2"),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
assert len(response.results) == 4
@@ -647,7 +650,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
breakdownFilter=BreakdownFilter(breakdown_type=BreakdownType.DATA_WAREHOUSE, breakdown="prop_2"),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
assert len(response.results) == 4
@@ -671,7 +674,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
breakdownFilter=BreakdownFilter(breakdown_type=BreakdownType.DATA_WAREHOUSE, breakdown="prop_1"),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -699,7 +702,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
trendsFilter=TrendsFilter(display=display_type),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query)
assert response.columns is not None
@@ -747,7 +750,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = self.get_response(trends_query=trends_query)
assert response.columns is not None
@@ -784,7 +787,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
self.assertEqual(1, len(response.results))
@@ -822,7 +825,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
self.assertEqual(2, len(response.results))
@@ -866,7 +869,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
TrendsQueryRunner(team=self.team, query=trends_query).calculate()
@override_settings(IN_UNIT_TESTING=True)
@@ -898,7 +901,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
# 3 of 5 rows have timestamps in range (2023-01-01, 2023-01-02, 2023-01-04)
@@ -969,7 +972,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
],
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
response = TrendsQueryRunner(team=self.team, query=trends_query).calculate()
assert len(response.results) == 1
@@ -1007,7 +1010,7 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
with self.assertRaises(ExposedHogQLError):
TrendsQueryRunner(team=self.team, query=trends_query).calculate()
@@ -1045,6 +1048,6 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):
),
)
- with freeze_time("2023-01-07"):
+ with time_machine.travel("2023-01-07", tick=False):
with self.assertRaises(ExposedHogQLError):
TrendsQueryRunner(team=self.team, query=trends_query).calculate()
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py
index d80bda1c1f19..94f96dc771b5 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py
@@ -1,7 +1,7 @@
from typing import Optional, Union
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.case import skip
@@ -737,7 +737,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
)
- with freeze_time("2023-05-01T20:00:00.000Z"):
+ with time_machine.travel("2023-05-01T20:00:00.000Z", tick=False):
# note: total value actors should be called without day
result = self._get_actors(trends_query=source_query)
@@ -771,7 +771,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
)
- with freeze_time("2023-05-01T20:00:00.000Z"):
+ with time_machine.travel("2023-05-01T20:00:00.000Z", tick=False):
result = self._get_actors(trends_query=source_query)
self.assertEqual(len(result), 1)
@@ -1248,7 +1248,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_handles_multiple_ids(self):
timestamp = "2020-01-11T12:00:00Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["anon1", "p1"],
@@ -1334,7 +1334,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_matches_first_event_only(self):
timestamp = "2020-01-11T12:00:00Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["anon1", "p1"],
@@ -1395,7 +1395,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_matches_all_first_events(self):
timestamp = "2020-01-11T12:00:00Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["anon1", "p1"],
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_builder.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_builder.py
index 8fecb366b8f7..ce08cd8438e1 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_builder.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_builder.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest, _create_event, _create_person
from posthog.schema import (
@@ -29,7 +29,7 @@ class TestTrendsQueryBuilder(BaseTest):
def setUp(self):
super().setUp()
- with freeze_time("2023-02-01"):
+ with time_machine.travel("2023-02-01", tick=False):
_create_person(
distinct_ids=["some_id"],
team_id=self.team.pk,
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
index a80ffdd865ae..8ea4e5f3f1d6 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
@@ -7,7 +7,7 @@ from itertools import groupby
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -129,7 +129,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
type = "String"
properties_to_create[key] = type
- with freeze_time(first_timestamp):
+ with time_machine.travel(first_timestamp, tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -789,7 +789,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_exclude_incomplete_periods_drops_current_bucket(self):
self._create_test_events()
- with freeze_time("2020-01-15T12:00:00Z"):
+ with time_machine.travel("2020-01-15T12:00:00Z", tick=False):
query = TrendsQuery(
series=[EventsNode(event="$pageview")],
dateRange=DateRange(date_from="-7d", excludeIncompletePeriods=True),
@@ -804,7 +804,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# 2020-01-19 is a Sunday (default week start), so -13d starts mid-week on Jan 6: the
# partial Jan 6-11 bucket is dropped alongside the current week, leaving Jan 12-18 only
- with freeze_time("2020-01-19T12:00:00Z"):
+ with time_machine.travel("2020-01-19T12:00:00Z", tick=False):
query = TrendsQuery(
series=[EventsNode(event="$pageview")],
dateRange=DateRange(date_from="-13d", excludeIncompletePeriods=True),
@@ -1990,7 +1990,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self._create_test_events()
utc = zoneinfo.ZoneInfo("UTC")
- with freeze_time("2020-01-15T12:00:00Z"):
+ with time_machine.travel("2020-01-15T12:00:00Z", tick=False):
response = self._run_trends_query(
date_from,
date_to,
@@ -2010,7 +2010,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_trends_compare_weeks(self):
self._create_test_events()
- with freeze_time("2020-01-24"):
+ with time_machine.travel("2020-01-24", tick=False):
response = self._run_trends_query(
"-7d",
None,
@@ -6128,7 +6128,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_handles_multiple_ids(self):
timestamp = "2020-01-11T12:00:00Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["anon1", "p1"],
@@ -6206,7 +6206,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_filters_first_events(self):
timestamp = "2020-01-11T12:00:00Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["anon1", "p1"],
@@ -6309,7 +6309,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_prioritizes_first_event(self):
timestamp = "2020-01-11T12:00:00Z"
- with freeze_time(timestamp):
+ with time_machine.travel(timestamp, tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=["p1"],
@@ -6423,7 +6423,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self._create_test_events()
flush_persons_and_events()
- with freeze_time("2020-01-20"):
+ with time_machine.travel("2020-01-20", tick=False):
response = self._run_trends_query(
"-180d",
None,
@@ -6441,7 +6441,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[0]["count"] == 4
assert len(response.results[0]["days"]) == 7
- with freeze_time("2020-01-20"):
+ with time_machine.travel("2020-01-20", tick=False):
response = self._run_trends_query(
"-180d",
None,
@@ -6459,7 +6459,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[0]["count"] == 4
assert len(response.results[0]["days"]) == 27
- with freeze_time("2020-01-20"):
+ with time_machine.travel("2020-01-20", tick=False):
response = self._run_trends_query(
"-30d",
None,
@@ -6477,7 +6477,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[0]["count"] == 4
assert len(response.results[0]["days"]) == 721
- with freeze_time("2020-01-11T12:30:00Z"):
+ with time_machine.travel("2020-01-11T12:30:00Z", tick=False):
response = self._run_trends_query(
"-1h",
None,
@@ -6499,7 +6499,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self._create_test_events()
flush_persons_and_events()
- with freeze_time("2020-01-20"):
+ with time_machine.travel("2020-01-20", tick=False):
response = self._run_trends_query(
"-180d",
None,
@@ -7104,7 +7104,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
# Test line graph with explicit_date=False (whole day periods)
- with freeze_time(freeze_time_at.isoformat()):
+ with time_machine.travel(freeze_time_at.isoformat(), tick=False):
response = TrendsQueryRunner(
query=self._create_trends_query(
date_from="-7d",
@@ -7139,7 +7139,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(11, response.results[1]["data"][0])
# Test line graph with explicit_date=True (rolling window with current time)
- with freeze_time(freeze_time_at.isoformat()):
+ with time_machine.travel(freeze_time_at.isoformat(), tick=False):
response = TrendsQueryRunner(
query=self._create_trends_query(
date_from="-7d",
@@ -7178,7 +7178,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(1, response.results[1]["data"][-1])
# Test with bold number and explicit_date=False (whole day periods)
- with freeze_time(freeze_time_at.isoformat()):
+ with time_machine.travel(freeze_time_at.isoformat(), tick=False):
response = TrendsQueryRunner(
query=self._create_trends_query(
date_from="-7d",
@@ -7199,7 +7199,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(25, result["aggregated_value"])
# Test with bold number and explicit_date=True (rolling window with current time)
- with freeze_time(freeze_time_at.isoformat()):
+ with time_machine.travel(freeze_time_at.isoformat(), tick=False):
response = TrendsQueryRunner(
query=self._create_trends_query(
date_from="-7d",
@@ -7337,7 +7337,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
flush_persons_and_events()
# Test 1: Without explicitDate, filtering last 7 days with monthly interval only includes events in range
- with freeze_time("2020-01-31 23:59:59"):
+ with time_machine.travel("2020-01-31 23:59:59", tick=False):
response_default = TrendsQueryRunner(
query=TrendsQuery(
series=[EventsNode(event="$pageview")],
@@ -7355,7 +7355,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
# Test 2: With explicitDate=True and explicit dates, STILL has issues (gets 6 instead of 7)
- with freeze_time("2020-01-31 23:59:59"):
+ with time_machine.travel("2020-01-31 23:59:59", tick=False):
response_explicit = TrendsQueryRunner(
query=TrendsQuery(
series=[EventsNode(event="$pageview")],
@@ -7374,7 +7374,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
# Test 3: With explicitDate=True and relative dates, should only include events within the 7-day filter
- with freeze_time("2020-01-31 23:59:59"):
+ with time_machine.travel("2020-01-31 23:59:59", tick=False):
response_exact = TrendsQueryRunner(
query=TrendsQuery(
series=[EventsNode(event="$pageview")],
@@ -8028,7 +8028,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2020-01-20T00:00:00Z")
+ @time_machine.travel("2020-01-20T00:00:00Z", tick=False)
def test_group_node_property_filter_types(self, _name, property_filter, expected_count):
self._create_test_events()
flush_persons_and_events()
@@ -8109,7 +8109,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
("median", PropertyMathType.MEDIAN),
]
)
- @freeze_time("2020-01-20T00:00:00Z")
+ @time_machine.travel("2020-01-20T00:00:00Z", tick=False)
def test_session_duration_math_with_event_property_filter(self, _name, math_type):
self._create_test_events()
flush_persons_and_events()
@@ -8175,7 +8175,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @freeze_time("2020-01-20T00:00:00Z")
+ @time_machine.travel("2020-01-20T00:00:00Z", tick=False)
def test_week_interval_boundaries_with_week_start_day(
self, _name, date_from, date_to, week_start_day, expected_count
):
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index d0f4bfdcf6af..c6e5ac9da151 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from typing import Any, Optional
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -250,7 +250,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# Newly created insight should have created_at being the current time, and same last_modified_at
# Fields created_by and last_modified_by should be set to the current user
- with freeze_time("2021-08-23T12:00:00Z"):
+ with time_machine.travel("2021-08-23T12:00:00Z", tick=False):
response_1 = self.client.post(
f"/api/projects/{self.team.id}/insights/",
{"name": "test", "query": default_pageview_query()},
@@ -297,7 +297,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# Updating fields that don't change the substance of the insight should affect updated_at
# BUT NOT last_modified_at or last_modified_by
- with freeze_time("2021-09-20T12:00:00Z"):
+ with time_machine.travel("2021-09-20T12:00:00Z", tick=False):
response_2 = self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}",
{"favorited": True},
@@ -344,7 +344,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# Updating fields that DO change the substance of the insight should affect updated_at
# AND last_modified_at plus last_modified_by
- with freeze_time("2021-10-21T12:00:00Z"):
+ with time_machine.travel("2021-10-21T12:00:00Z", tick=False):
response_3 = self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}",
{
@@ -364,7 +364,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
}.items(),
response_3.json().items(),
)
- with freeze_time("2021-12-23T12:00:00Z"):
+ with time_machine.travel("2021-12-23T12:00:00Z", tick=False):
response_4 = self.client.patch(f"/api/projects/{self.team.id}/insights/{insight_id}", {"name": "XYZ"})
self.assertEqual(response_4.status_code, status.HTTP_200_OK)
self.assertLessEqual(
@@ -380,7 +380,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# Field last_modified_by is updated when another user makes a material change
self.client.force_login(alt_user)
- with freeze_time("2022-01-01T12:00:00Z"):
+ with time_machine.travel("2022-01-01T12:00:00Z", tick=False):
response_5 = self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}",
{"description": "Lorem ipsum."},
@@ -1302,7 +1302,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
matched_insights = [insight["id"] for insight in any_on_dashboard_one.json()["results"]]
assert sorted(matched_insights) == [insight_one_id]
- @freeze_time("2012-01-14T03:21:34.000Z")
+ @time_machine.travel("2012-01-14T03:21:34.000Z", tick=False)
def test_create_insight_items(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/insights",
@@ -1351,7 +1351,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
],
)
- @freeze_time("2012-01-14T03:21:34.000Z")
+ @time_machine.travel("2012-01-14T03:21:34.000Z", tick=False)
def test_create_insight_with_no_names_logs_no_activity(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/insights",
@@ -1763,7 +1763,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
dashboard_one_id
] # removed dashboard is removed
- @freeze_time("2012-01-14T03:21:34.000Z")
+ @time_machine.travel("2012-01-14T03:21:34.000Z", tick=False)
def test_create_insight_logs_derived_name_if_there_is_no_name(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/insights",
@@ -1797,11 +1797,11 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
def test_update_insight(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z") as frozen_time:
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False) as frozen_time:
insight_id, insight = self.dashboard_api.create_insight({"name": "insight name"})
short_id = insight["short_id"]
- frozen_time.tick(delta=timedelta(minutes=10))
+ frozen_time.shift(timedelta(minutes=10))
response = self.client.patch(
f"/api/projects/{self.team.id}/insights/{insight_id}",
@@ -1947,7 +1947,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def test_insight_refreshing_query(self, properties_filter, spy_execute_hogql_query) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"filters": {"date_from": "-14d"}})
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
_create_event(
team=self.team,
event="$pageview",
@@ -1976,7 +1976,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties=properties_filter,
).model_dump()
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights",
data={
@@ -1996,7 +1996,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z")
self.assertFalse(response["is_cached"])
- with freeze_time("2012-01-15T05:01:34.000Z"):
+ with time_machine.travel("2012-01-15T05:01:34.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight_id}/?refresh=true").json()
self.assertNotIn("code", response)
@@ -2006,7 +2006,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z") # did not change
self.assertFalse(response["is_cached"])
- with freeze_time("2012-01-15T05:17:34.000Z"):
+ with time_machine.travel("2012-01-15T05:17:34.000Z", tick=False):
response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight_id}/").json()
self.assertNotIn("code", response)
self.assertEqual(spy_execute_hogql_query.call_count, 2)
@@ -2015,7 +2015,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z") # did not change
self.assertTrue(response["is_cached"])
- with freeze_time("2012-01-15T05:17:39.000Z"):
+ with time_machine.travel("2012-01-15T05:17:39.000Z", tick=False):
# Make sure the /query/ endpoint reuses the same cached result
response = self.client.post(f"/api/projects/{self.team.id}/query/", {"query": query_dict}).json()
self.assertNotIn("code", response)
@@ -2024,7 +2024,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response["last_refresh"], "2012-01-15T05:01:34Z") # Using cached result
self.assertTrue(response["is_cached"])
- with freeze_time("2012-01-16T05:01:34.000Z"):
+ with time_machine.travel("2012-01-16T05:01:34.000Z", tick=False):
# load it in the context of the dashboard, so has last 14 days as filter
response = self.client.get(
f"/api/projects/{self.team.id}/insights/{insight_id}/?refresh=true&from_dashboard={dashboard_id}"
@@ -2064,7 +2064,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"date_from": "-14d",
},
)
- with freeze_time("2012-01-16T05:01:34.000Z"):
+ with time_machine.travel("2012-01-16T05:01:34.000Z", tick=False):
response = self.client.get(
f"/api/projects/{self.team.id}/insights/{insight_id}/?refresh=true&from_dashboard={dashboard_id}"
).json()
@@ -2116,7 +2116,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def test_insight_refreshing_query_async(self, properties_filter, spy_execute_hogql_query) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"filters": {"date_from": "-14d"}})
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
_create_event(
team=self.team,
event="$pageview",
@@ -2145,7 +2145,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties=properties_filter,
).model_dump()
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights",
data={
@@ -2165,7 +2165,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response["last_modified_at"], "2012-01-15T04:01:34Z")
self.assertFalse(response["is_cached"])
- with freeze_time("2012-01-15T05:17:39.000Z"):
+ with time_machine.travel("2012-01-15T05:17:39.000Z", tick=False):
# Make sure the /query/ endpoint reuses the same cached result - ASYNC EXECUTION HERE!
response = self.client.post(
f"/api/projects/{self.team.id}/query/", {"query": query_dict, "refresh": "async"}
@@ -2177,7 +2177,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response["last_refresh"], "2012-01-15T04:01:34Z") # Using cached result
self.assertTrue(response["is_cached"])
- with freeze_time("2012-01-15T05:17:39.000Z"):
+ with time_machine.travel("2012-01-15T05:17:39.000Z", tick=False):
# Now with force async requested - cache should be ignored
response = self.client.post(
f"/api/projects/{self.team.id}/query/", {"query": query_dict, "refresh": "force_async"}
@@ -2292,11 +2292,11 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# BASIC TESTING OF ENDPOINTS. /queries as in depth testing for each insight
def test_insight_trends_basic(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
_create_event(team=self.team, event="$pageview", distinct_id="2")
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend/?events={json.dumps([{'id': '$pageview'}])}"
).json()
@@ -2375,7 +2375,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
def test_insight_trends_compare(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
for i in range(25):
_create_event(
team=self.team,
@@ -2384,7 +2384,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties={"$some_property": f"value{i}"},
)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend/",
data={"events": json.dumps([{"id": "$pageview"}]), "compare": "true"},
@@ -2396,7 +2396,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(result["result"][1]["compare_label"], "previous")
def test_insight_trends_breakdown_pagination(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
for i in range(25):
_create_event(
team=self.team,
@@ -2405,7 +2405,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
properties={"$some_property": f"value{i}"},
)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend/",
data={
@@ -2748,11 +2748,11 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response_correct_token_list.json()["count"], 0)
def test_insight_trends_csv(self) -> None:
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="1")
_create_event(team=self.team, event="$pageview", distinct_id="2")
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_event(team=self.team, event="$pageview", distinct_id="2")
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend.csv/?events={json.dumps([{'id': '$pageview', 'custom_name': 'test custom'}])}&export_name=Pageview count&export_insight_id=test123"
@@ -2778,7 +2778,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
return cohort_one_id
@parameterized.expand([("single_id", 1), ("bulk_ids", 3)])
- @freeze_time("2022-03-22T00:00:00.000Z")
+ @time_machine.travel("2022-03-22T00:00:00.000Z", tick=False)
def test_create_insight_viewed(self, _name: str, count: int) -> None:
filter_dict = {"events": [{"id": "$pageview"}]}
insights = [
@@ -2824,14 +2824,14 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
team=self.team,
short_id="12345678",
)
- with freeze_time("2022-03-22T00:00:00.000Z"):
+ with time_machine.travel("2022-03-22T00:00:00.000Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights/viewed",
{"insight_ids": [insight.id]},
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- with freeze_time("2022-03-23T00:00:00.000Z"):
+ with time_machine.travel("2022-03-23T00:00:00.000Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights/viewed",
{"insight_ids": [insight.id]},
@@ -2887,14 +2887,14 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
]
# Pre-create rows for the first two insights at T1.
- with freeze_time("2022-03-22T00:00:00.000Z"):
+ with time_machine.travel("2022-03-22T00:00:00.000Z", tick=False):
self.client.post(
f"/api/projects/{self.team.id}/insights/viewed",
{"insight_ids": [insights[0].id, insights[1].id]},
)
# Submit all three at T2 — the first two should be UPDATEd, the third INSERTed.
- with freeze_time("2022-03-23T00:00:00.000Z"):
+ with time_machine.travel("2022-03-23T00:00:00.000Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights/viewed",
{"insight_ids": [insight.id for insight in insights]},
@@ -3398,7 +3398,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@snapshot_clickhouse_queries
def test_insight_trend_hogql_global_filters(self) -> None:
_create_person(team=self.team, distinct_ids=["1"], properties={"fish": "there is no fish"})
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
for i in range(25):
_create_event(
team=self.team,
@@ -3406,7 +3406,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
distinct_id="1",
properties={"int_value": i},
)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
# 25 events total
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend/",
@@ -3464,7 +3464,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@snapshot_clickhouse_queries
def test_insight_trend_hogql_local_filters(self) -> None:
_create_person(team=self.team, distinct_ids=["1"], properties={"fish": "there is no fish"})
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
for i in range(25):
_create_event(
team=self.team,
@@ -3472,7 +3472,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
distinct_id="1",
properties={"int_value": i},
)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
# test trends local property filter
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend/",
@@ -3505,7 +3505,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@snapshot_clickhouse_queries
def test_insight_trend_hogql_breakdown(self) -> None:
_create_person(team=self.team, distinct_ids=["1"], properties={"fish": "there is no fish"})
- with freeze_time("2012-01-14T03:21:34.000Z"):
+ with time_machine.travel("2012-01-14T03:21:34.000Z", tick=False):
for i in range(25):
_create_event(
team=self.team,
@@ -3513,7 +3513,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
distinct_id="1",
properties={"int_value": i},
)
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
# test trends breakdown
response = self.client.get(
f"/api/projects/{self.team.id}/insights/trend/",
@@ -3532,7 +3532,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@snapshot_clickhouse_queries
@also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
def test_insight_funnels_hogql_global_filters(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(
team=self.team,
distinct_ids=["1"],
@@ -3584,7 +3584,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@snapshot_clickhouse_queries
@also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
def test_insight_funnels_hogql_local_filters(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(
team=self.team,
distinct_ids=["1"],
@@ -3656,7 +3656,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@snapshot_clickhouse_queries
@also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
def test_insight_funnels_hogql_breakdown(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(
team=self.team,
distinct_ids=["1"],
@@ -3711,7 +3711,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# @snapshot_clickhouse_queries
@also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
def test_insight_funnels_hogql_breakdown_single(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(
team=self.team,
distinct_ids=["1"],
@@ -3764,7 +3764,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response_json["timezone"], "UTC")
def test_insight_funnels_hogql_aggregating_steps(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(team=self.team, distinct_ids=["1"], properties={"int_value": 1})
_create_event(
team=self.team,
@@ -3826,7 +3826,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@skip("Compatibility issue CH 23.12 (see #21318)")
def test_insight_funnels_hogql_aggregating_time_to_convert(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(team=self.team, distinct_ids=["1"], properties={"int_value": 1})
_create_event(
team=self.team,
@@ -3834,21 +3834,21 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
distinct_id="1",
properties={"$browser": "Chrome"},
)
- with freeze_time("2012-01-15T04:01:36.500Z"):
+ with time_machine.travel("2012-01-15T04:01:36.500Z", tick=False):
_create_event(
team=self.team,
event="user signed up",
distinct_id="1",
properties={"$browser": "Firefox"},
)
- with freeze_time("2012-01-15T04:01:38.200Z"):
+ with time_machine.travel("2012-01-15T04:01:38.200Z", tick=False):
_create_event(
team=self.team,
event="user did things",
distinct_id="1",
properties={"$browser": "Chrome"},
)
- with freeze_time("2012-01-16T04:01:38.200Z"):
+ with time_machine.travel("2012-01-16T04:01:38.200Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights/funnel/",
{
@@ -3889,7 +3889,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response_json["timezone"], "UTC")
def test_insight_funnels_hogql_aggregating_trends(self) -> None:
- with freeze_time("2012-01-15T04:01:34.000Z"):
+ with time_machine.travel("2012-01-15T04:01:34.000Z", tick=False):
_create_person(team=self.team, distinct_ids=["1"], properties={"int_value": 1})
_create_event(
team=self.team,
@@ -3897,21 +3897,21 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
distinct_id="1",
properties={"$browser": "Chrome"},
)
- with freeze_time("2012-01-15T04:01:36.500Z"):
+ with time_machine.travel("2012-01-15T04:01:36.500Z", tick=False):
_create_event(
team=self.team,
event="user signed up",
distinct_id="1",
properties={"$browser": "Firefox"},
)
- with freeze_time("2012-01-15T04:01:38.200Z"):
+ with time_machine.travel("2012-01-15T04:01:38.200Z", tick=False):
_create_event(
team=self.team,
event="user did things",
distinct_id="1",
properties={"$browser": "Chrome"},
)
- with freeze_time("2012-01-16T04:01:38.200Z"):
+ with time_machine.travel("2012-01-16T04:01:38.200Z", tick=False):
response = self.client.post(
f"/api/projects/{self.team.id}/insights/funnel/",
{
diff --git a/products/reminders/backend/test/test_firing.py b/products/reminders/backend/test/test_firing.py
index f6c64ff3b514..6edef98795ec 100644
--- a/products/reminders/backend/test/test_firing.py
+++ b/products/reminders/backend/test/test_firing.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -9,7 +9,7 @@ from products.reminders.backend.models import Reminder
class TestProcessDueReminders(BaseTest):
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification")
def test_one_off_fires_and_completes(self, mock_create: MagicMock) -> None:
reminder = Reminder.objects.create(
@@ -26,7 +26,7 @@ class TestProcessDueReminders(BaseTest):
self.assertEqual(reminder.status, Reminder.Status.COMPLETED)
self.assertEqual(reminder.last_fired_at, datetime(2026, 6, 15, 9, 0, tzinfo=UTC))
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification")
def test_recurring_advances_and_stays_active(self, mock_create: MagicMock) -> None:
reminder = Reminder.objects.create(
@@ -42,7 +42,7 @@ class TestProcessDueReminders(BaseTest):
self.assertEqual(reminder.status, Reminder.Status.ACTIVE)
self.assertEqual(reminder.next_fire_at, datetime(2026, 6, 16, 8, 59, tzinfo=UTC))
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification")
def test_not_yet_due_is_skipped(self, mock_create: MagicMock) -> None:
Reminder.objects.create(
@@ -56,7 +56,7 @@ class TestProcessDueReminders(BaseTest):
process_due_reminders()
mock_create.assert_not_called()
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification")
def test_recurring_catch_up_fires_once(self, mock_create: MagicMock) -> None:
reminder = Reminder.objects.create(
@@ -73,7 +73,7 @@ class TestProcessDueReminders(BaseTest):
assert reminder.next_fire_at is not None
self.assertGreater(reminder.next_fire_at, datetime(2026, 6, 15, 9, 0, tzinfo=UTC))
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification", side_effect=RuntimeError("boom"))
def test_one_off_errors_after_retries(self, mock_create: MagicMock) -> None:
reminder = Reminder.objects.create(
@@ -90,7 +90,7 @@ class TestProcessDueReminders(BaseTest):
self.assertEqual(reminder.status, Reminder.Status.ERRORED)
self.assertIn("boom", reminder.last_error or "")
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification", side_effect=RuntimeError("boom"))
def test_recurring_resets_retry_budget_after_advance(self, mock_create: MagicMock) -> None:
reminder = Reminder.objects.create(
@@ -110,7 +110,7 @@ class TestProcessDueReminders(BaseTest):
self.assertIsNone(reminder.last_error)
self.assertEqual(reminder.next_fire_at, datetime(2026, 6, 16, 8, 59, tzinfo=UTC))
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
@patch("products.reminders.backend.firing.create_notification")
def test_org_level_fires_and_completes(self, mock_create: MagicMock) -> None:
reminder = Reminder.objects.create(
diff --git a/products/replay_vision/backend/tests/test_action_volume.py b/products/replay_vision/backend/tests/test_action_volume.py
index 30a2ce6e4e20..8b7e4515562b 100644
--- a/products/replay_vision/backend/tests/test_action_volume.py
+++ b/products/replay_vision/backend/tests/test_action_volume.py
@@ -1,7 +1,7 @@
import datetime as dt
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events
from posthog.models import Team
@@ -27,8 +27,12 @@ def _action(team, name: str, event: str) -> Action:
return Action.objects.create(team=team, name=name, steps_json=[{"event": event}])
-@freeze_time(_FROZEN_TIME)
class TestRecentActionSessions(ClickhouseTestMixin):
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_FROZEN_TIME, tick=False):
+ yield
+
@pytest.mark.django_db
def test_a_dead_action_separates_from_a_live_one_by_its_session_count(self, team) -> None:
live = _action(team, "Completed checkout", "checkout completed")
diff --git a/products/replay_vision/backend/tests/test_excluded_sessions.py b/products/replay_vision/backend/tests/test_excluded_sessions.py
index 1b3330623082..a6f9e1c6031e 100644
--- a/products/replay_vision/backend/tests/test_excluded_sessions.py
+++ b/products/replay_vision/backend/tests/test_excluded_sessions.py
@@ -1,7 +1,7 @@
import datetime as dt
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event
from posthog.schema import EventPropertyFilter, FilterLogicalOperator, PropertyOperator, RecordingsQuery
@@ -49,8 +49,12 @@ def _event(team, session_id: str, at: dt.datetime, **props) -> None:
)
-@freeze_time(_FROZEN_TIME)
class TestExcludedSessions(ClickhouseTestMixin):
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_FROZEN_TIME, tick=False):
+ yield
+
@pytest.mark.django_db
def test_excludes_only_the_sessions_carrying_a_disqualifying_event(self, team) -> None:
_event(team, "dirty", _NOW - dt.timedelta(hours=2), **{"$host": "internal.example.com"})
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index 899aeb998cc6..e9ffcda57d35 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -1,7 +1,7 @@
import uuid
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -814,7 +814,7 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
assert snapshot.projected_monthly_credits == 0
- @freeze_time("2026-09-16T00:00:00Z")
+ @time_machine.travel("2026-09-16T00:00:00Z", tick=False)
def test_a_capped_scanner_projects_at_most_its_remaining_limit(self) -> None:
self._make_scanner(team=self.team, name="capped", estimate=100, credit_limit=200) # 1500 uncapped
self._make_scanner(team=self.team, name="roomy", estimate=10, credit_limit=9000) # 150, under its cap
@@ -884,7 +884,7 @@ class TestVisionSpendSeriesEndpoint(_VisionQuotaTestCase):
credits=credits,
)
- @freeze_time("2026-03-10T12:00:00Z")
+ @time_machine.travel("2026-03-10T12:00:00Z", tick=False)
def test_zero_filled_daily_credits_from_period_start_through_today(self) -> None:
self.organization.usage = {"period": ["2026-03-01T00:00:00+00:00", "2026-04-01T00:00:00+00:00"]}
self.organization.save()
diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
index 466981a0b86c..a40682b3b033 100644
--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
@@ -1,7 +1,7 @@
import datetime as dt
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin, _create_event
from posthog.schema import (
@@ -232,8 +232,12 @@ def test_matches_on_events_covers_test_account_filters(team) -> None:
# Integration: actual ClickHouse query.
-@freeze_time(_FROZEN_TIME)
class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_FROZEN_TIME, tick=False):
+ yield
+
def setup_method(self, _method) -> None:
sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
@@ -782,8 +786,12 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
).run()
-@freeze_time(_FROZEN_TIME)
class TestWindowedCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_FROZEN_TIME, tick=False):
+ yield
+
def setup_method(self, _method) -> None:
sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
diff --git a/products/replay_vision/backend/tests/test_search.py b/products/replay_vision/backend/tests/test_search.py
index 2edb8bc4cfbd..8ba290ddc282 100644
--- a/products/replay_vision/backend/tests/test_search.py
+++ b/products/replay_vision/backend/tests/test_search.py
@@ -3,7 +3,7 @@ import uuid
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
@@ -61,7 +61,7 @@ class TestParseDateBound:
assert parse_date_bound("2026-09-01", None, end_of_range=True).hour == 23
@parameterized.expand([("lowercase", "now"), ("mixed_case", "Now"), ("padded", " now ")])
- @freeze_time("2026-09-01T10:30:00Z")
+ @time_machine.travel("2026-09-01T10:30:00Z", tick=False)
def test_now_is_the_current_time_even_as_an_upper_bound(self, _name: str, value: str) -> None:
# `now` must not widen to end of day the way a date-only bound does, or an upper bound of
# `now` reaches into the future.
diff --git a/products/replay_vision/backend/tests/test_vision_alerts_engine.py b/products/replay_vision/backend/tests/test_vision_alerts_engine.py
index db2f6c580280..91fb53659872 100644
--- a/products/replay_vision/backend/tests/test_vision_alerts_engine.py
+++ b/products/replay_vision/backend/tests/test_vision_alerts_engine.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -204,7 +204,7 @@ class TestVisionAlertEngine(BaseTest):
def test_first_cycle_retry_is_uuid_stable_without_next_check_at(self) -> None:
start = datetime.now(UTC)
- with freeze_time(start):
+ with time_machine.travel(start, tick=False):
alert = self._make_alert(next_check_at=None)
# The window bound is completed_at < now, so frozen-now observations need backdating.
self._make_observation(completed_at=start - timedelta(minutes=5))
@@ -218,7 +218,7 @@ class TestVisionAlertEngine(BaseTest):
state=VisionAlertState.NOT_FIRING, next_check_at=None, last_checked_at=None, last_notified_at=None
)
alert.refresh_from_db()
- with freeze_time(start + timedelta(seconds=61)):
+ with time_machine.travel(start + timedelta(seconds=61), tick=False):
_, produce = self._run_batch(alert)
assert produce.call_args.kwargs["uuid"] == first_uuid
diff --git a/products/replay_vision/backend/tests/test_visited_paths.py b/products/replay_vision/backend/tests/test_visited_paths.py
index 19702678b171..57ef592a93d7 100644
--- a/products/replay_vision/backend/tests/test_visited_paths.py
+++ b/products/replay_vision/backend/tests/test_visited_paths.py
@@ -1,7 +1,7 @@
import datetime as dt
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import ClickhouseTestMixin
from posthog.schema import RecordingsQuery
@@ -44,8 +44,12 @@ def _produce(
)
-@freeze_time(_NOW.strftime("%Y-%m-%dT%H:%M:%SZ"))
class TestVisitedPaths(ClickhouseTestMixin):
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_NOW.strftime("%Y-%m-%dT%H:%M:%SZ"), tick=False):
+ yield
+
def setup_method(self, _method) -> None:
sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
@@ -167,7 +171,6 @@ class TestVisitedPaths(ClickhouseTestMixin):
assert [r.pathname for r in results] == ["/billing"]
-@freeze_time(_NOW.strftime("%Y-%m-%dT%H:%M:%SZ"))
class TestVisitedPageFilterSemantics(ClickhouseTestMixin):
"""One `visited_page` property holding several values ORs them; several properties AND.
@@ -177,6 +180,11 @@ class TestVisitedPageFilterSemantics(ClickhouseTestMixin):
quietly match almost nothing and no test of our own output would show it.
"""
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_NOW.strftime("%Y-%m-%dT%H:%M:%SZ"), tick=False):
+ yield
+
def setup_method(self, _method) -> None:
sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
diff --git a/products/revenue_analytics/backend/views/sources/test/events/test_events_mrr.py b/products/revenue_analytics/backend/views/sources/test/events/test_events_mrr.py
index 22c917b0d09f..b839da039c65 100644
--- a/products/revenue_analytics/backend/views/sources/test/events/test_events_mrr.py
+++ b/products/revenue_analytics/backend/views/sources/test/events/test_events_mrr.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from products.revenue_analytics.backend.views.core import SourceHandle
from products.revenue_analytics.backend.views.schemas.mrr import SCHEMA as MRR_SCHEMA
@@ -15,7 +15,7 @@ class TestMRREventsBuilder(EventsSourceBaseTest):
def test_build_mrr_query(self):
"""Test building MRR query for an event."""
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
handle = SourceHandle(type="events", team=self.team, event=self.events[0])
query = build(handle)
diff --git a/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer.py b/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer.py
index fc226d9535c9..7c8eaa092fcd 100644
--- a/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer.py
+++ b/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer.py
@@ -1,6 +1,6 @@
import json
-from freezegun import freeze_time
+import time_machine
from parameterized import parameterized
@@ -186,7 +186,7 @@ class TestCustomerStripeMetadataResolution(RevenueAnalyticsTestBase):
self.view_name = f"stripe.posthog_test.{CUSTOMER_SCHEMA.source_suffix}"
def _query_metadata(self) -> dict[str, dict]:
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = execute_hogql_query(
parse_select(f"SELECT id, metadata FROM {self.view_name} ORDER BY id"),
self.team,
diff --git a/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer_metadata_resolution.py b/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer_metadata_resolution.py
index 5b9172b53025..9fd79c483ea2 100644
--- a/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer_metadata_resolution.py
+++ b/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_customer_metadata_resolution.py
@@ -1,7 +1,7 @@
import tempfile
from pathlib import Path
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from posthog.schema import CurrencyCode, HogQLQueryModifiers, HogQLQueryResponse
@@ -192,7 +192,7 @@ class TestStripeCustomerMetadataResolution(ClickhouseTestMixin, APIBaseTest):
super().tearDown()
def _select_all_from_view(self, view_name: str) -> HogQLQueryResponse:
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = ast.SelectQuery(
select=[ast.Field(chain=["*"])],
select_from=ast.JoinExpr(table=ast.Field(chain=[view_name])),
diff --git a/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_mrr.py b/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_mrr.py
index 5534e91896bd..62ee9427996e 100644
--- a/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_mrr.py
+++ b/products/revenue_analytics/backend/views/sources/test/stripe/test_stripe_mrr.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from products.revenue_analytics.backend.views.schemas.mrr import SCHEMA as MRR_SCHEMA
from products.revenue_analytics.backend.views.sources.stripe.mrr import build
@@ -13,7 +13,7 @@ class TestMRRStripeBuilder(StripeSourceBaseTest):
self.setup_stripe_external_data_source()
def test_build_mrr_query(self):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = build(self.stripe_handle)
expected_key = f"{self.external_data_source.id}-mrr"
diff --git a/products/revenue_analytics/backend/views/test/test_mrr_views.py b/products/revenue_analytics/backend/views/test/test_mrr_views.py
index 9327d5ac03f3..d24c49260c5d 100644
--- a/products/revenue_analytics/backend/views/test/test_mrr_views.py
+++ b/products/revenue_analytics/backend/views/test/test_mrr_views.py
@@ -1,7 +1,7 @@
from decimal import Decimal
from pathlib import Path
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -119,7 +119,7 @@ class TestMRRViewsE2E(ClickhouseTestMixin, QueryMatchingTest, APIBaseTest):
def _create_purchase_events(self, data):
person_result = []
for distinct_id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person = _create_person(
team_id=self.team.pk,
distinct_ids=[distinct_id],
@@ -150,7 +150,7 @@ class TestMRRViewsE2E(ClickhouseTestMixin, QueryMatchingTest, APIBaseTest):
return person_result
def _execute_query(self, query: ast.SelectQuery) -> HogQLQueryResponse:
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
return execute_hogql_query(
query=query,
team=self.team,
diff --git a/products/revenue_analytics/dags/tests/test_exchange_rate.py b/products/revenue_analytics/dags/tests/test_exchange_rate.py
index 4d84eea59931..0082c861e4c7 100644
--- a/products/revenue_analytics/dags/tests/test_exchange_rate.py
+++ b/products/revenue_analytics/dags/tests/test_exchange_rate.py
@@ -2,7 +2,7 @@ import datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import dagster
@@ -255,7 +255,7 @@ class TestExchangeRateClickhouse:
class TestExchangeRateSchedules:
- @freeze_time("2023-01-15 01:30:00")
+ @time_machine.travel("2023-01-15 01:30:00", tick=False)
def test_daily_exchange_rates_schedule(self):
# Mock the scheduled execution context
context = dagster.build_schedule_context(scheduled_execution_time=datetime.datetime(2023, 1, 15, 1, 30))
@@ -270,7 +270,7 @@ class TestExchangeRateSchedules:
assert result.partition_key == "2023-01-14"
assert result.run_key == "2023-01-14"
- @freeze_time("2023-01-15 10:00:00")
+ @time_machine.travel("2023-01-15 10:00:00", tick=False)
def test_hourly_exchange_rates_schedule(self):
# Mock the scheduled execution context
context = dagster.build_schedule_context(scheduled_execution_time=datetime.datetime(2023, 1, 15, 10, 0))
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index 383200cb5cb7..87ac6fb94ea4 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from django.utils import timezone
@@ -145,7 +145,7 @@ class TestRecentReviewsAPI(APIBaseTest):
# (stale, never completed) run must not appear — a filter regression would leak other users'
# review activity or show a dead run as forever in progress.
mine = self._report(pr_number=1, acting_user=self.user)
- with freeze_time(timezone.now() - timedelta(hours=2)):
+ with time_machine.travel(timezone.now() - timedelta(hours=2), tick=False):
self._report(pr_number=2, acting_user=self.user, completed=False)
other = User.objects.create_and_join(self.organization, "[email protected]", None)
self._report(pr_number=3, acting_user=other)
@@ -531,7 +531,7 @@ class TestRecentReviewsAPI(APIBaseTest):
# redelivered foreign verdict, not a previous run's verdict for a re-queued thread, and not
# a judged thread whose GitHub writes haven't landed.
report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.ACTIVE)
- with freeze_time(timezone.now() - timedelta(hours=1)):
+ with time_machine.travel(timezone.now() - timedelta(hours=1), tick=False):
# A previous run already judged PRRT_3; a new comment re-queued it, so only a verdict
# written during THIS run may count toward its progress.
self._thread_verdict(report, "PRRT_3", "fixed")
@@ -566,7 +566,7 @@ class TestRecentReviewsAPI(APIBaseTest):
# closing note is the completion marker), and a crashed run must yield the row to a newer
# review turn's own progress instead of pinning a stale "didn't finish" on it.
report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.ACTIVE, head_sha="sha1")
- with freeze_time(timezone.now() - timedelta(hours=2)):
+ with time_machine.travel(timezone.now() - timedelta(hours=2), tick=False):
self._resolution_run(report, ["PRRT_1"])
self._thread_verdict(report, "PRRT_1", "fixed")
if scenario == "completed_run_via_closing_note":
@@ -589,7 +589,7 @@ class TestRecentReviewsAPI(APIBaseTest):
# The silent-death mode: a resolution that dies partway used to leave no trace anywhere.
# With the run anchor present, no closing note, and activity past the staleness window, the
# row must say where it stopped instead of nothing.
- with freeze_time(timezone.now() - timedelta(hours=2)):
+ with time_machine.travel(timezone.now() - timedelta(hours=2), tick=False):
report = self._report(pr_number=5, acting_user=self.user, status=ReviewReport.Status.IDLE)
self._resolution_run(report, ["PRRT_1", "PRRT_2", "PRRT_3"])
self._thread_verdict(report, "PRRT_1", "fixed")
diff --git a/products/signals/backend/test/test_daily_limit.py b/products/signals/backend/test/test_daily_limit.py
index f594625a1db5..5c96eae138c6 100644
--- a/products/signals/backend/test/test_daily_limit.py
+++ b/products/signals/backend/test/test_daily_limit.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -53,7 +53,7 @@ class TestDailyReportLimitGate(BaseTest):
def test_only_reports_stamped_today_count(self):
self._set_limit(1)
- with freeze_time("2026-08-10T12:00:00Z"):
+ with time_machine.travel("2026-08-10T12:00:00Z", tick=False):
self._visible_report(datetime(2026, 8, 9, 12, 0, tzinfo=UTC))
# A pre-migration (or never-surfaced) row has no stamp and must never count.
self._visible_report(None)
@@ -70,7 +70,7 @@ class TestDailyReportLimitGate(BaseTest):
self._set_limit(1)
self._visible_report(datetime(2026, 8, 9, 8, 0, tzinfo=UTC))
self._visible_report(datetime(2026, 8, 9, 6, 0, tzinfo=UTC))
- with freeze_time("2026-08-10T05:00:00Z"):
+ with time_machine.travel("2026-08-10T05:00:00Z", tick=False):
# Fresh instance: timezone_info is a cached property on the pre-save one.
gate = daily_report_limit_gate(Team.objects.get(pk=self.team.pk))
assert gate.reports_today == 1
@@ -121,7 +121,7 @@ class TestFirstVisibleStamp(BaseTest):
# once and must not consume the daily limit again.
report.transition_to(SignalReport.Status.CANDIDATE)
report.transition_to(SignalReport.Status.IN_PROGRESS, signals_at_run_increment=3)
- with freeze_time(datetime.now(UTC) + timedelta(days=1)):
+ with time_machine.travel(datetime.now(UTC) + timedelta(days=1), tick=False):
updated_fields = report.transition_to(SignalReport.Status.READY, title="t2", summary="s2")
assert report.first_visible_at == original
assert "first_visible_at" not in updated_fields
diff --git a/products/signals/backend/test/test_dismissal_scout_notes.py b/products/signals/backend/test/test_dismissal_scout_notes.py
index 9d4046b907da..c207e4341c95 100644
--- a/products/signals/backend/test/test_dismissal_scout_notes.py
+++ b/products/signals/backend/test/test_dismissal_scout_notes.py
@@ -5,7 +5,7 @@ from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -14,9 +14,6 @@ from django.apps import apps
from parameterized import parameterized
from rest_framework import status
-# Load the API URLconf (and its pydantic.v1 import chain) before any freeze_time window:
-# first-importing date-subclassing modules under freezegun's fake date raises a metaclass conflict.
-import posthog.api.rest_router # noqa: F401
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -269,7 +266,7 @@ class TestDismissalScoutNotes(APIBaseTest):
# The artefact is the record of truth either way, so a resolve still keeps the feedback.
assert self._dismissal_notes_on(report) == ["context the scout should have"]
- @freeze_time(_REFUND_NOW)
+ @time_machine.travel(_REFUND_NOW, tick=False)
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_refund_feedback_reaches_the_authoring_scout(self, _flag) -> None:
self._create_scout_skill()
@@ -292,7 +289,7 @@ class TestDismissalScoutNotes(APIBaseTest):
# `pr_incorrect` is what tells the scout its report promised something the PR did not deliver.
assert "pr_incorrect" in note.content
- @freeze_time(_REFUND_NOW)
+ @time_machine.travel(_REFUND_NOW, tick=False)
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_a_repeat_refund_does_not_forward_a_second_time(self, _flag) -> None:
self._create_scout_skill()
@@ -310,7 +307,7 @@ class TestDismissalScoutNotes(APIBaseTest):
# Refund button must not teach the scout the same verdict twice.
assert len(self._notes()) == 1
- @freeze_time(_REFUND_NOW)
+ @time_machine.travel(_REFUND_NOW, tick=False)
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_refund_without_a_note_forwards_nothing(self, _flag) -> None:
self._create_scout_skill()
@@ -326,7 +323,7 @@ class TestDismissalScoutNotes(APIBaseTest):
assert self._notes() == []
assert self._dismissal_notes_on(report) == [None]
- @freeze_time(_REFUND_NOW)
+ @time_machine.travel(_REFUND_NOW, tick=False)
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_no_note_when_a_refund_leaves_a_merged_pr_report_resolved(self, _flag) -> None:
self._create_scout_skill()
diff --git a/products/signals/backend/test/test_refunds.py b/products/signals/backend/test/test_refunds.py
index 061c27eed9e3..b265b4b5b094 100644
--- a/products/signals/backend/test/test_refunds.py
+++ b/products/signals/backend/test/test_refunds.py
@@ -2,7 +2,7 @@ import json
from datetime import UTC, datetime, timedelta
from decimal import Decimal
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import patch
@@ -12,10 +12,6 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-# Load the API URLconf (and its pydantic.v1 import chain) before any freeze_time window:
-# first-importing date-subclassing modules under freezegun's fake date raises a metaclass
-# conflict, which standalone runs of this file otherwise hit on the first request.
-import posthog.api.rest_router # noqa: F401
from posthog.models import Organization, Team
from products.signals.backend.billing import SIGNALS_CREDITS_PER_REPORT_WITH_PR
@@ -80,7 +76,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
def _refund(self, report: SignalReport, body: dict | None = None):
return self.client.post(self._refund_url(str(report.id)), body or {"reason": "pr_not_useful"}, format="json")
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_earlier_in_period_goes_credited_and_archives(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, 9, 30, tzinfo=UTC))
response = self._refund(report, {"reason": "pr_incorrect", "note": "does not fix the bug"})
@@ -112,14 +108,14 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert content["reason"] == "refunded"
assert content["note"] == "does not fix the bug"
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_on_pr_run_day_goes_excluded(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 15, 8, 0, tzinfo=UTC))
response = self._refund(report)
assert response.status_code == status.HTTP_200_OK
assert response.json()["billing_path"] == "excluded"
- @freeze_time("2026-06-15T00:30:00Z")
+ @time_machine.travel("2026-06-15T00:30:00Z", tick=False)
def test_refund_just_after_utc_midnight_goes_credited(self, _flag):
# The path rule is the PR run's UTC day, not "before the 03:45 send" — a 23:50 PR refunded
# at 00:30 must go credited even though the usage report hasn't shipped yet.
@@ -128,14 +124,14 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["billing_path"] == "credited"
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_without_billable_pr_is_rejected(self, _flag):
report = _make_report(self.team)
response = self._refund(report)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "no billable implementation PR" in response.json()["error"]
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_for_previous_period_pr_is_rejected(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 5, 20, tzinfo=UTC))
response = self._refund(report)
@@ -148,7 +144,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
("pr_in_previous_month", datetime(2026, 5, 20, tzinfo=UTC), status.HTTP_400_BAD_REQUEST),
]
)
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_missing_billing_period_falls_back_to_calendar_month(self, _flag, _name, pr_created_at, expected_status):
self.organization.usage = None
self.organization.save()
@@ -165,7 +161,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
("billing_exempt", "billing_exempt"),
]
)
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_report_response_carries_refund_ineligibility_reason(self, _flag, case, expected):
# The serializer field shares the refund endpoint's eligibility decision (billable moment +
# period context + helper); a wiring regression would re-enable buttons that only 400.
@@ -194,7 +190,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
listed = {row["id"]: row for row in list_response.json()["results"]}
assert listed[str(report.id)]["refund_ineligibility_reason"] == expected
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_on_exempt_report_is_rejected(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
SignalReport.objects.filter(id=report.id).update(
@@ -204,7 +200,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "never-billable" in response.json()["error"]
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_second_refund_is_idempotent(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
first = self._refund(report, {"reason": "pr_incorrect"})
@@ -218,7 +214,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert second.json()["id"] == first.json()["id"]
assert SignalReportRefund.objects.filter(report=report).count() == 1
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_reaches_already_archived_report(self, _flag):
# An archived-but-charged report must still be refundable (suppressed reports are hidden
# from most by-id actions); it stays suppressed.
@@ -239,7 +235,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
("resolved_without_merge", {"pr_url": "https://github.com/x/y/pull/1"}, SignalReport.Status.SUPPRESSED),
]
)
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_of_resolved_report_suppresses_unless_pr_merged(self, _flag, _name, output, expected_status):
report = _make_report(self.team, status=SignalReport.Status.RESOLVED)
_make_pr_run(self.team, report, created_at=datetime(2026, 6, 10, tzinfo=UTC), output=output)
@@ -252,14 +248,14 @@ class TestSignalReportRefundAPI(APIBaseTest):
report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL
).exists()
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_invalid_reason_is_rejected(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
response = self._refund(report, {"reason": "because"})
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert not SignalReportRefund.objects.filter(report=report).exists()
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_credited_refund_enqueues_billing_sync_on_commit(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
with patch("products.signals.backend.views.sync_signals_refund_credit.delay") as mock_delay:
@@ -268,7 +264,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
mock_delay.assert_called_once_with(str(report.refund.id))
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_excluded_refund_never_calls_billing(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 15, 8, 0, tzinfo=UTC))
with patch("products.signals.backend.views.sync_signals_refund_credit.delay") as mock_delay:
@@ -277,7 +273,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
mock_delay.assert_not_called()
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_fires_analytics_event(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
with patch("products.signals.backend.views.report_user_action") as mock_report:
@@ -308,7 +304,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
),
]
)
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_analytics_pr_merged_reflects_merge_flag_not_status(self, _flag, _name, report_status, output, expected):
report = _make_report(self.team, status=report_status)
_make_pr_run(self.team, report, created_at=datetime(2026, 6, 10, tzinfo=UTC), output=output)
@@ -316,7 +312,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert self._refund(report).status_code == status.HTTP_200_OK
assert mock_report.call_args.kwargs["properties"]["pr_merged"] is expected
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_later_merged_pr_does_not_vouch_for_the_refunded_one(self, _flag):
# The refund reverses the charge for the first billable PR, and it's that PR which must be
# closed if it never merged. A different, later PR on the same report merging says nothing
@@ -342,7 +338,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_merge_flag_on_non_github_run_does_not_attest_a_merge(self, _flag):
# A billable GitHub run makes the report refundable, while a second implementation run
# carries a merge flag on a URL the billing path never counts. That flag must not attest a
@@ -368,7 +364,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_restore_of_refunded_report_is_blocked(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
assert self._refund(report).status_code == status.HTTP_200_OK
@@ -379,7 +375,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_snooze_of_refunded_resolved_report_is_blocked(self, _flag):
# A merged-PR report stays RESOLVED through its refund, so the guard can't key on SUPPRESSED:
# snoozing it to POTENTIAL would put a refunded report back where grouping re-promotes it to
@@ -401,7 +397,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.RESOLVED
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_resolve_of_refunded_report_is_blocked(self, _flag):
# A refunded report is suppressed; resolving would undo that suppression — and the PR close
# it triggers — so the refund guard must cover resolve too (not just restore to potential).
@@ -414,7 +410,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
report.refresh_from_db()
assert report.status == SignalReport.Status.SUPPRESSED
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_resolve_then_refund_suppresses_report(self, _flag):
# The exploit path the refund must close: a task:write caller resolves a ready report through
# the API while its PR is still open, then refunds it. If the refund left it RESOLVED the
@@ -431,7 +427,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
reopen = self.client.post(self._state_url(str(report.id)), {"state": "resolved"}, format="json")
assert reopen.status_code == status.HTTP_409_CONFLICT
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_bulk_restore_of_refunded_report_is_blocked(self, _flag):
refunded = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
assert self._refund(refunded).status_code == status.HTTP_200_OK
@@ -452,7 +448,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
refunded.refresh_from_db()
assert refunded.status == SignalReport.Status.SUPPRESSED
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_report_response_includes_refund_and_exemption_fields(self, _flag):
report = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
self._refund(report)
@@ -463,7 +459,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert body["refund"]["reason"] == "pr_not_useful"
assert body["billing_exempt_reason"] is None
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_summary_aggregates_credited_refunds_org_wide(self, _flag):
# Two teams in the org contribute; excluded-path, out-of-period, and foreign-org refunds don't.
report_a = self._report_with_pr(pr_created_at=datetime(2026, 6, 10, tzinfo=UTC))
@@ -496,7 +492,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
"quota_limited": False,
}
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_summary_counts_unreported_prs_live_until_excluded_refund(self, _flag):
# A PR created today hasn't shipped to billing yet but must count in the live number,
# and a same-day (excluded-path) refund must visibly un-count it.
@@ -507,7 +503,7 @@ class TestSignalReportRefundAPI(APIBaseTest):
assert self._refund(report).json()["billing_path"] == "excluded"
assert self.client.get(url).json()["period_billable_credits"] == 0
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_refund_summary_reports_quota_limited_from_the_gate(self, _flag):
# The widget's "agents are paused" banner keys off this field, so it must reflect the
# same gate the pipeline enforces, not the widget's own usage math.
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index a6ef1fc6824c..ba617207bda3 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -6,7 +6,7 @@ from typing import Any
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import AsyncMock, patch
from django.test import override_settings
@@ -1002,7 +1002,7 @@ async def test_stamp_activity_advances_dispatched_configs_to_their_slot_anchor(a
ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440, last_run_at=old
)
- with freeze_time(_DISPATCHED_AT):
+ with time_machine.travel(_DISPATCHED_AT, tick=False):
env = ActivityEnvironment()
await env.run(
stamp_dispatched_signals_scout_runs_activity,
@@ -1037,7 +1037,7 @@ async def test_stamp_activity_keeps_the_wall_clock_for_cron_and_probed_configs(a
ateam, "signals-scout-foo", run_interval_minutes=1440, **config_kwargs
)
- with freeze_time(_DISPATCHED_AT):
+ with time_machine.travel(_DISPATCHED_AT, tick=False):
env = ActivityEnvironment()
await env.run(
stamp_dispatched_signals_scout_runs_activity,
@@ -1062,7 +1062,7 @@ async def test_stamp_activity_falls_back_to_the_wall_clock_when_slot_alignment_i
)
payload = {**_allowlist_payload(), "slot_aligned_dispatch": False}
- with freeze_time(_DISPATCHED_AT), patch(_PAYLOAD_PATH, side_effect=lambda *a, **k: payload):
+ with time_machine.travel(_DISPATCHED_AT, tick=False), patch(_PAYLOAD_PATH, side_effect=lambda *a, **k: payload):
env = ActivityEnvironment()
await env.run(
stamp_dispatched_signals_scout_runs_activity,
diff --git a/products/signals/backend/test/test_scout_status.py b/products/signals/backend/test/test_scout_status.py
index fd0a660be7e4..586fefc053d8 100644
--- a/products/signals/backend/test/test_scout_status.py
+++ b/products/signals/backend/test/test_scout_status.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -271,44 +271,44 @@ class TestScoutStatusEnabledReconciliation(BaseTest):
class TestScoutColdStartGrace(BaseTest):
def test_grace_follows_creation_then_expires(self) -> None:
- with freeze_time("2026-07-01T00:00:00Z"):
+ with time_machine.travel("2026-07-01T00:00:00Z", tick=False):
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
- with freeze_time("2026-07-10T00:00:00Z"):
+ with time_machine.travel("2026-07-10T00:00:00Z", tick=False):
assert config.in_cold_start_grace() is True
- with freeze_time("2026-07-16T00:00:00Z"):
+ with time_machine.travel("2026-07-16T00:00:00Z", tick=False):
assert config.in_cold_start_grace() is False
def test_human_reactivation_grants_a_fresh_window(self) -> None:
- with freeze_time("2026-06-01T00:00:00Z"):
+ with time_machine.travel("2026-06-01T00:00:00Z", tick=False):
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=False)
- with freeze_time("2026-07-15T00:00:00Z"):
+ with time_machine.travel("2026-07-15T00:00:00Z", tick=False):
serializer = SignalScoutConfigUpdateSerializer(
config, data={"enabled": True}, partial=True, context={"request": self._request_stub()}
)
assert serializer.is_valid()
config = serializer.save()
- with freeze_time("2026-07-20T00:00:00Z"):
+ with time_machine.travel("2026-07-20T00:00:00Z", tick=False):
assert config.in_cold_start_grace() is True
def test_any_reactivation_grants_a_fresh_window(self) -> None:
# Deliberately independent of attribution, so the window survives the re-enabling
# user's account being deleted (the FK is SET_NULL).
- with freeze_time("2026-06-01T00:00:00Z"):
+ with time_machine.travel("2026-06-01T00:00:00Z", tick=False):
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=False)
- with freeze_time("2026-07-15T00:00:00Z"):
+ with time_machine.travel("2026-07-15T00:00:00Z", tick=False):
config.enabled = True
config.save(update_fields=["enabled"])
- with freeze_time("2026-07-20T00:00:00Z"):
+ with time_machine.travel("2026-07-20T00:00:00Z", tick=False):
assert config.in_cold_start_grace() is True
def test_a_system_transition_does_not_re_anchor(self) -> None:
# A sweep's own pending_pause warning re-anchoring grace would put the scout back
# under protection and the sweep could never pause anything.
- with freeze_time("2026-06-01T00:00:00Z"):
+ with time_machine.travel("2026-06-01T00:00:00Z", tick=False):
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
- with freeze_time("2026-07-15T00:00:00Z"):
+ with time_machine.travel("2026-07-15T00:00:00Z", tick=False):
config.transition_status_by_system(Status.PENDING_PAUSE, pause_reason=Reason.NO_OUTPUT)
- with freeze_time("2026-07-20T00:00:00Z"):
+ with time_machine.travel("2026-07-20T00:00:00Z", tick=False):
assert config.in_cold_start_grace() is False
def _request_stub(self):
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index 9073f125367e..b1648b0628da 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime
from typing import Any
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from django.core.cache import cache
@@ -705,7 +705,7 @@ class TestInsightAlertSnooze(TestCase):
)
@parameterized.expand(["1h", "6h", "1d", "1w"])
- @freeze_time("2026-07-21T12:34:56Z")
+ @time_machine.travel("2026-07-21T12:34:56Z", tick=False)
@patch("products.slack_app.backend.api._is_org_member")
@patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
@@ -745,7 +745,7 @@ class TestInsightAlertSnooze(TestCase):
assert all(el.get("action_id") != "insight_alert_snooze" for el in actions_block["elements"])
assert mock_requests_post.call_args.kwargs["json"]["replace_original"] is True
- @freeze_time("2026-07-21T12:34:56Z")
+ @time_machine.travel("2026-07-21T12:34:56Z", tick=False)
@patch("products.slack_app.backend.api._is_org_member")
@patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
@@ -764,7 +764,7 @@ class TestInsightAlertSnooze(TestCase):
"1d", ZoneInfo("UTC"), increase=True, always_truncate=True
)
- @freeze_time("2026-07-21T12:34:56Z")
+ @time_machine.travel("2026-07-21T12:34:56Z", tick=False)
@patch("products.slack_app.backend.api._is_org_member")
@patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
@@ -787,7 +787,7 @@ class TestInsightAlertSnooze(TestCase):
("beyond_31_days", 32 * 24 * 3600),
]
)
- @freeze_time("2026-07-21T12:34:56Z")
+ @time_machine.travel("2026-07-21T12:34:56Z", tick=False)
@patch("products.slack_app.backend.api._is_org_member")
@patch("products.slack_app.backend.services.inbox_interactivity.requests.post")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
@@ -1125,7 +1125,7 @@ class TestInsightAlertSnoozeModal(TestCase):
assert self.alert.state == AlertState.FIRING
assert self.alert.snoozed_until is None
- @freeze_time("2026-07-21T12:00:00Z")
+ @time_machine.travel("2026-07-21T12:00:00Z", tick=False)
@patch("products.slack_app.backend.api.SlackIntegration")
@patch("products.slack_app.backend.api._is_org_member")
def test_modal_submit_snoozes_to_picked_time(self, mock_is_org_member, mock_slack):
@@ -1140,7 +1140,7 @@ class TestInsightAlertSnoozeModal(TestCase):
mock_slack.return_value.client.chat_postMessage.assert_called_once()
@parameterized.expand([("past", "2020-01-01", "09:00"), ("beyond_31_days", "2026-09-30", "09:00")])
- @freeze_time("2026-07-21T12:00:00Z")
+ @time_machine.travel("2026-07-21T12:00:00Z", tick=False)
@patch("products.slack_app.backend.api.SlackIntegration")
@patch("products.slack_app.backend.api._is_org_member")
def test_modal_submit_rejects_out_of_bounds(self, _name, sel_date, sel_time, mock_is_org_member, mock_slack):
@@ -1153,7 +1153,7 @@ class TestInsightAlertSnoozeModal(TestCase):
assert self.alert.state == AlertState.FIRING
assert self.alert.snoozed_until is None
- @freeze_time("2026-07-21T12:00:00Z")
+ @time_machine.travel("2026-07-21T12:00:00Z", tick=False)
@patch("products.slack_app.backend.api.SlackIntegration")
@patch("products.slack_app.backend.api._is_org_member")
def test_modal_submit_refuses_non_org_member(self, mock_is_org_member, mock_slack):
diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.py
index e3b7e6400c1c..ee3634f55200 100644
--- a/products/stamphog/backend/tests/test_digest.py
+++ b/products/stamphog/backend/tests/test_digest.py
@@ -4,7 +4,7 @@ from types import SimpleNamespace
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from django.db import OperationalError
@@ -610,7 +610,7 @@ def test_previous_run_slot(now: str, expected: str) -> None:
ids=["first_digest_cadence_window", "established_audience_week_floor"],
)
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
-@freeze_time("2026-07-15T08:00:00+00:00") # a Wednesday; previous slot = Tue 07:00 UTC
+@time_machine.travel("2026-07-15T08:00:00+00:00", tick=False) # a Wednesday; previous slot = Tue 07:00 UTC
def test_digest_claim_floor(team, has_history: bool, claimed_offset: timedelta, unclaimed_offset: timedelta) -> None:
# An audience's first digest must cover only the natural cadence window (what it would have
# received had it been routable one run earlier), never an arbitrary backlog; an established
diff --git a/products/stamphog/packages/pr-approval-agent/test_review_local.py b/products/stamphog/packages/pr-approval-agent/test_review_local.py
index 9a0fd4b4e8ec..b425ae677700 100644
--- a/products/stamphog/packages/pr-approval-agent/test_review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/test_review_local.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock
# review_local pulls in review_pr, whose reviewer.py imports claude_agent_sdk (installed by
@@ -343,7 +343,7 @@ def test_absent_review_threads_key_is_a_clean_no_op(monkeypatch) -> None:
assert pr.review_comments == []
-@freeze_time("2026-01-01T12:00:00Z")
+@time_machine.travel("2026-01-01T12:00:00Z", tick=False)
def test_fresh_trusted_bot_eyes_reach_pr_data_and_flag_in_flight(monkeypatch) -> None:
# The hosted context now carries raw PR reactions; a fresh 👀 from an allowlisted reviewer bot
# must reach PRData so the offline WAIT check can fire — hard-coding pr_reactions=[] meant
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 8d206df06d63..f2eb14db75ee 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -5,7 +5,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
import pytest
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -3053,7 +3053,7 @@ class TestSurvey(APIBaseTest):
updated_survey_deletes_targeting_flag.json()["detail"] == "There is already another survey with this name."
)
- @freeze_time("2023-05-01 12:00:00")
+ @time_machine.travel("2023-05-01 12:00:00", tick=False)
def test_update_survey_targeting_flag_filters_records_activity(self):
linked_flag = FeatureFlag.objects.create(team=self.team, key="linked-flag", created_by=self.user)
targeting_flag = FeatureFlag.objects.create(team=self.team, key="targeting-flag", created_by=self.user)
@@ -3117,7 +3117,7 @@ class TestSurvey(APIBaseTest):
self._assert_survey_activity(expected_activity_log)
- @freeze_time("2023-05-01 12:00:00")
+ @time_machine.travel("2023-05-01 12:00:00", tick=False)
def test_create_survey_records_activity(self):
response = self.client.post(
f"/api/projects/{self.team.id}/surveys/",
@@ -3149,7 +3149,7 @@ class TestSurvey(APIBaseTest):
],
)
- @freeze_time("2023-05-01 12:00:00")
+ @time_machine.travel("2023-05-01 12:00:00", tick=False)
def test_update_survey_records_activity(self):
survey = Survey.objects.create(
team=self.team,
@@ -3215,7 +3215,7 @@ class TestSurvey(APIBaseTest):
)
@patch("products.surveys.backend.api.survey.report_user_action")
- @freeze_time("2023-05-01 12:00:00")
+ @time_machine.travel("2023-05-01 12:00:00", tick=False)
def test_update_survey_dates_calls_report_user_action(self, mock_report_user_action):
survey = Survey.objects.create(
team=self.team,
@@ -3294,7 +3294,7 @@ class TestSurvey(APIBaseTest):
request=ANY,
)
- @freeze_time("2023-05-01 12:00:00")
+ @time_machine.travel("2023-05-01 12:00:00", tick=False)
def test_delete_survey_records_activity(self):
survey = Survey.objects.create(
team=self.team,
@@ -4997,7 +4997,7 @@ class TestGetSurveyConditionsActionSanitization(SimpleTestCase):
assert value["name"] == "person subscribed"
-@freeze_time("2024-12-12 00:00:00")
+@time_machine.travel("2024-12-12 00:00:00", tick=False)
class TestSurveyResponseSampling(APIBaseTest):
def _create_survey_with_sampling_limits(
self,
@@ -5194,7 +5194,7 @@ class TestSurveysRecurringIterations(APIBaseTest):
assert survey.internal_targeting_flag.filters == user_submitted_dismissed_filter
- @freeze_time("2024-05-22 14:40:09")
+ @time_machine.travel("2024-05-22 14:40:09", tick=False)
def test_iterations_always_start_from_start_date(self):
survey = self._create_recurring_survey()
response = self.client.patch(
@@ -5339,7 +5339,7 @@ class TestSurveyAPITokens(PersonalAPIKeysBaseTest, APIBaseTest):
self.key.scopes = ["survey:read"]
self.key.save()
- @freeze_time("2024-05-01 14:40:09")
+ @time_machine.travel("2024-05-01 14:40:09", tick=False)
def test_responses_count_works_with_survey_read(self):
survey_counts = {
"d63bb580-01af-4819-aae5-edcf7ef2044f": 3,
@@ -5370,7 +5370,7 @@ class TestSurveyAPITokens(PersonalAPIKeysBaseTest, APIBaseTest):
class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
- @freeze_time("2024-05-01 14:40:09")
+ @time_machine.travel("2024-05-01 14:40:09", tick=False)
def test_responses_count(self):
survey_counts = {
"d63bb580-01af-4819-aae5-edcf7ef2044f": 3,
@@ -5399,7 +5399,7 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(data, survey_counts)
@snapshot_clickhouse_queries
- @freeze_time("2024-05-01 14:40:09")
+ @time_machine.travel("2024-05-01 14:40:09", tick=False)
def test_responses_count_only_after_first_survey_started(self):
survey_counts = {
"d63bb580-01af-4819-aae5-edcf7ef2044f": 3,
@@ -5440,7 +5440,7 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(data, {})
@snapshot_clickhouse_queries
- @freeze_time("2024-06-11 11:00:00")
+ @time_machine.travel("2024-06-11 11:00:00", tick=False)
def test_responses_count_with_partial_responses(self):
survey1_id = str(uuid.uuid4())
survey2_id = str(uuid.uuid4())
@@ -5537,7 +5537,7 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(data, expected_counts)
- @freeze_time("2024-05-01 14:40:09")
+ @time_machine.travel("2024-05-01 14:40:09", tick=False)
def test_responses_count_returns_more_surveys_than_the_hogql_default_limit(self):
Survey.objects.create(team_id=self.team.id, start_date=datetime.now() - timedelta(days=1))
survey_ids = [str(uuid.uuid4()) for _ in range(DEFAULT_RETURNED_ROWS + 1)]
@@ -5555,7 +5555,7 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), dict.fromkeys(survey_ids, 1))
- @freeze_time("2024-05-01 14:40:09")
+ @time_machine.travel("2024-05-01 14:40:09", tick=False)
def test_responses_count_excludes_archived_responses(self):
survey_id = str(uuid.uuid4())
response_uuid = str(uuid.uuid4())
@@ -5594,7 +5594,7 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
data = response.json()
self.assertEqual(data.get(survey_id, 0), 0)
- @freeze_time("2024-05-01 14:40:09")
+ @time_machine.travel("2024-05-01 14:40:09", tick=False)
def test_responses_count_filters_by_survey_ids(self):
survey_id_1 = str(uuid.uuid4())
survey_id_2 = str(uuid.uuid4())
@@ -5776,7 +5776,7 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(rates["response_rate"], 100.0) # 1 sent / 1 shown
self.assertEqual(rates["dismissal_rate"], 0.0) # 0 dismissed / 1 shown
- @freeze_time("2024-06-10 10:00:00")
+ @time_machine.travel("2024-06-10 10:00:00", tick=False)
def test_survey_stats_partial_responses(self):
survey = Survey.objects.create(
team=self.team,
@@ -5900,7 +5900,7 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):
# (Unique persons dismissed / Unique persons shown) * 100 = (1 / 3) * 100 = 33.33
self.assertEqual(rates_reassigned["dismissal_rate"], 33.33)
- @freeze_time("2024-06-10 10:00:00")
+ @time_machine.travel("2024-06-10 10:00:00", tick=False)
def test_survey_stats_uses_created_at_when_start_date_is_missing(self):
survey = Survey.objects.create(
team=self.team,
@@ -5934,7 +5934,7 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(data["stats"]["survey sent"]["total_count"], 1)
self.assertEqual(data["stats"]["survey sent"]["unique_persons"], 1)
- @freeze_time("2024-05-01 12:00:00")
+ @time_machine.travel("2024-05-01 12:00:00", tick=False)
def test_survey_stats_excludes_archived_responses(self):
survey = Survey.objects.create(
team=self.team,
@@ -6683,7 +6683,7 @@ class TestSurveyBulkDuplication(APIBaseTest):
def test_bulk_duplicate_multiple_times_to_same_team(self):
"""Test that multiple duplications to the same team create surveys with different timestamps"""
- with freeze_time("2024-01-01 00:00:00") as frozen_time:
+ with time_machine.travel("2024-01-01 00:00:00", tick=False) as frozen_time:
# Create first duplicate
response1 = self.client.post(
f"/api/projects/{self.team.project_id}/surveys/{self.source_survey.id}/duplicate_to_projects/",
@@ -6694,7 +6694,7 @@ class TestSurveyBulkDuplication(APIBaseTest):
# Advance the clock so the second duplicate's name timestamp differs (the
# duplicate name embeds datetime.now() at second precision)
- frozen_time.tick(timedelta(seconds=1))
+ frozen_time.shift(timedelta(seconds=1))
# Try to create another duplicate (should succeed because timestamp is different)
response2 = self.client.post(
@@ -6924,7 +6924,7 @@ class TestSurveyResponseArchive(ClickhouseTestMixin, APIBaseTest):
item.pop(envelope_key, None)
self.assertEqual(results, expected)
- @freeze_time("2024-05-01 12:00:00")
+ @time_machine.travel("2024-05-01 12:00:00", tick=False)
def test_archive_response(self):
response = self.client.post(
f"/api/projects/{self.team.id}/surveys/{self.survey.id}/responses/{self.response_uuid}/archive"
@@ -6977,7 +6977,7 @@ class TestSurveyResponseArchive(ClickhouseTestMixin, APIBaseTest):
# Should still have only one record
self.assertEqual(SurveyResponseArchive.objects.count(), initial_count)
- @freeze_time("2024-05-01 12:00:00")
+ @time_machine.travel("2024-05-01 12:00:00", tick=False)
def test_unarchive_response(self):
# First archive it
SurveyResponseArchive.objects.create(team=self.team, survey=self.survey, response_uuid=self.response_uuid)
diff --git a/products/surveys/backend/summarization/test_fetch.py b/products/surveys/backend/summarization/test_fetch.py
index c56e5e59591b..9a84a81a2dc9 100644
--- a/products/surveys/backend/summarization/test_fetch.py
+++ b/products/surveys/backend/summarization/test_fetch.py
@@ -3,13 +3,13 @@
import uuid
from datetime import datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from .fetch import fetch_responses
-@freeze_time("2025-01-15 12:00:00")
+@time_machine.travel("2025-01-15 12:00:00", tick=False)
class TestFetchResponses(ClickhouseTestMixin, APIBaseTest):
def test_deduplicates_responses_by_submission_id(self):
"""Multiple survey sent events with the same submission ID should return only one response."""
diff --git a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
index f32318ace434..7c5182445aa9 100644
--- a/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
+++ b/products/tasks/backend/logic/services/tests/test_sandbox_usage.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
from decimal import Decimal
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -264,9 +264,9 @@ class TestSandboxSessionWrites(SandboxUsageBase):
run = self._run(state={"await_user_message": True})
open_sandbox_session(run_id=run.id, sandbox_id="sb-msgs", config=_config())
- with freeze_time("2026-01-02T10:00:00Z"):
+ with time_machine.travel("2026-01-02T10:00:00Z", tick=False):
record_task_run_user_activity(run.id, self.team.id)
- with freeze_time("2026-01-02T11:00:00Z"):
+ with time_machine.travel("2026-01-02T11:00:00Z", tick=False):
record_task_run_user_activity(run.id, self.team.id)
session = SandboxSession.objects.unscoped().get(sandbox_id="sb-msgs")
@@ -522,7 +522,7 @@ class TestSandboxUsageAggregation(SandboxUsageBase):
ttl_seconds=6 * 60 * 60,
)
- with freeze_time("2026-01-05T00:00:00Z"):
+ with time_machine.travel("2026-01-05T00:00:00Z", tick=False):
usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
# Cleanup never ran; the sandbox died at created_at + 6h regardless.
@@ -585,7 +585,7 @@ class TestSandboxUsageAggregation(SandboxUsageBase):
sandbox_backend=sandbox_backend,
)
- with freeze_time("2026-01-05T00:00:00Z"):
+ with time_machine.travel("2026-01-05T00:00:00Z", tick=False):
usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
if expected_seconds is None:
@@ -600,7 +600,7 @@ class TestSandboxUsageAggregation(SandboxUsageBase):
ended_at=None,
)
- with freeze_time("2026-01-02T03:00:00Z"):
+ with time_machine.travel("2026-01-02T03:00:00Z", tick=False):
usage = get_task_sandbox_usage_by_team(self.BEGIN, self.END)
assert usage.seconds == [(self.team.id, 2 * 3600)]
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 18a08942d678..2147fea70df8 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -1,7 +1,7 @@
from typing import Literal
import pytest
-from freezegun import freeze_time
+import time_machine
from django.db import OperationalError
@@ -36,7 +36,7 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
)
-@freeze_time("2026-08-06T12:01:30Z")
+@time_machine.travel("2026-08-06T12:01:30Z", tick=False)
def test_record_boot_total_excludes_wizard_time_and_labels_runtime(mocker) -> None:
record_metric = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.record_boot_total_ms"
diff --git a/products/tasks/backend/tests/test_loop_github_events.py b/products/tasks/backend/tests/test_loop_github_events.py
index bb71e15d2fb6..bb2d43cf8831 100644
--- a/products/tasks/backend/tests/test_loop_github_events.py
+++ b/products/tasks/backend/tests/test_loop_github_events.py
@@ -1,7 +1,7 @@
import json
from typing import ClassVar
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from django.test import TestCase
@@ -428,7 +428,10 @@ class TestHandleGithubEventForLoops(TestCase):
)
payload = self._event_payload("push", installation_id=998877, repository="acme/repo")
- with freeze_time("2026-01-02 03:04:05"), patch(f"{LOOP_GITHUB_EVENTS_MODULE}._EVENT_THROTTLE_LIMIT", 2):
+ with (
+ time_machine.travel("2026-01-02 03:04:05", tick=False),
+ patch(f"{LOOP_GITHUB_EVENTS_MODULE}._EVENT_THROTTLE_LIMIT", 2),
+ ):
for i in range(4):
handle_github_event_for_loops("push", payload, delivery_id=f"del-flood-{i}")
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 7c24db0d1368..473fb9fe6a29 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -1,7 +1,7 @@
from datetime import timedelta
from typing import Any
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -771,7 +771,9 @@ class TestCreateTaskWarmReuse(APIBaseTest):
retry_token += "invalid"
if outcome == "retry_workflow_changed":
TaskRun.update_state_atomic(run.id, updates={"workflow_id": "replacement-workflow"})
- with freeze_time(django_timezone.now() + timedelta(seconds=61 if outcome == "retry_expired" else 0)):
+ with time_machine.travel(
+ django_timezone.now() + timedelta(seconds=61 if outcome == "retry_expired" else 0), tick=False
+ ):
retry = self.client.post(url, payload, format="json", HTTP_X_POSTHOG_WARM_RETRY=retry_token)
if outcome != "retry":
assert retry.status_code == 503, retry.content
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index 340714996c0f..52cd9f412662 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -7,7 +7,7 @@ import datetime
from typing import Any
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import Mock, patch
@@ -642,7 +642,7 @@ class TestInterviewStartCall(APIBaseTest):
response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- @freeze_time("2026-05-14 12:00:00")
+ @time_machine.travel("2026-05-14 12:00:00", tick=False)
@override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
def test_rejects_expired_rotated_token(self):
# Simulate the post-grace-period state of a rotated SharingConfiguration:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
index 86ab049e38e1..4931f6d9badd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
@@ -5,7 +5,7 @@ from typing import Any
from urllib.parse import urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -219,8 +219,12 @@ class TestGetRows:
assert list(get_rows("na", "cid", "sec", "rt", "sp_campaigns", mock.MagicMock())) == []
-@freeze_time(_TODAY)
class TestReportRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(_TODAY, tick=False):
+ yield
+
def _run(self, manager: mock.MagicMock | None = None, **kwargs: Any) -> list[list[dict[str, Any]]]:
return list(
get_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
index ab7edb550da4..8cfbb68dc451 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -223,7 +223,7 @@ class TestIterExportWindow:
class TestEventsWindowing:
- @freeze_time("2026-06-04 12:00:00")
+ @time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_windows_advance_and_state_is_saved_per_window(self) -> None:
manager = mock.MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
@@ -262,7 +262,7 @@ class TestEventsWindowing:
datetime(2026, 6, 4, 11, tzinfo=UTC).isoformat(),
]
- @freeze_time("2026-06-04 12:00:00")
+ @time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_resume_state_takes_precedence_over_incremental_value(self) -> None:
manager = mock.MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = True
@@ -290,7 +290,7 @@ class TestEventsWindowing:
manager.load_state.assert_called_once()
assert windows == [("20260604T09", "20260604T10")]
- @freeze_time("2026-06-04 12:00:00")
+ @time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_full_refresh_starts_from_lookback_window(self) -> None:
manager = mock.MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
index 02fc03504c34..1e08e2037912 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
@@ -5,7 +5,7 @@ from datetime import UTC, date, datetime, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import jwt
@@ -256,7 +256,7 @@ class TestNormalizePrivateKey:
class TestTokenProvider:
def test_mints_es256_token_with_key_id_and_apple_claims(self) -> None:
- with freeze_time("2026-03-04 10:00:00"):
+ with time_machine.travel("2026-03-04 10:00:00", tick=False):
token = AppStoreConnectTokenProvider("issuer-1", "KEY123", PRIVATE_KEY_PEM).token()
header = jwt.get_unverified_header(token)
@@ -271,19 +271,19 @@ class TestTokenProvider:
def test_token_is_cached_until_it_nears_expiry(self) -> None:
provider = AppStoreConnectTokenProvider("issuer-1", "KEY123", PRIVATE_KEY_PEM)
- with freeze_time("2026-03-04 10:00:00") as frozen:
+ with time_machine.travel("2026-03-04 10:00:00", tick=False) as frozen:
first = provider.token()
- frozen.tick(60)
+ frozen.shift(60)
assert provider.token() == first
# Past the refresh margin the provider mints a fresh token.
- frozen.tick(JWT_LIFETIME_SECONDS)
+ frozen.shift(JWT_LIFETIME_SECONDS)
assert provider.token() != first
def test_force_refresh_mints_a_new_token(self) -> None:
provider = AppStoreConnectTokenProvider("issuer-1", "KEY123", PRIVATE_KEY_PEM)
- with freeze_time("2026-03-04 10:00:00") as frozen:
+ with time_machine.travel("2026-03-04 10:00:00", tick=False) as frozen:
first = provider.token()
- frozen.tick(1)
+ frozen.shift(1)
assert provider.token(force_refresh=True) != first
def test_unusable_key_raises_auth_error(self) -> None:
@@ -1326,7 +1326,7 @@ class TestSalesReports:
with pytest.raises(ValueError, match="vendor number"):
_collect("sales_reports", _FakeApi({}), _FakeManager(), vendor_number=None)
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_walks_dates_forward_from_the_watermark_and_skips_empty_days(self) -> None:
api = self._api({"2026-03-02": "SKU\tUnits\nacme\t1\n", "2026-03-04": "SKU\tUnits\nacme\t2\n"})
@@ -1346,7 +1346,7 @@ class TestSalesReports:
]
assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-02", "2026-03-03", "2026-03-04"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_subscription_report_tolerates_apples_misleading_400(self) -> None:
# Apple 400s (instead of 404) a subscription-family report request for a date with no report
# available yet — a documented Apple API quirk, not a real credentials failure. It must not
@@ -1365,7 +1365,7 @@ class TestSalesReports:
assert [(row["report_date"], row["units"]) for row in rows] == [(date(2026, 3, 4), 1)]
assert api.report_dates("SUBSCRIPTION") == ["2026-03-02", "2026-03-03", "2026-03-04"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_unknown_vendor_number_fails_instead_of_completing_empty(self) -> None:
# Apple words a vendor number it doesn't know exactly like an empty subscription day, so a
# typo used to be tolerated across the whole lookback and complete with zero rows. The sales
@@ -1382,7 +1382,7 @@ class TestSalesReports:
db_incremental_field_last_value=date(2026, 3, 2),
)
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_vendor_number_is_checked_once_per_run(self) -> None:
# The check costs an extra request. Repeating it per tolerated day would add one for every
# day of the lookback window.
@@ -1400,7 +1400,7 @@ class TestSalesReports:
assert api.report_dates("SUBSCRIPTION") == ["2026-03-02", "2026-03-03", "2026-03-04"]
assert api.report_dates("SALES") == ["2026-03-02"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_unreadable_sales_report_leaves_the_day_tolerated(self) -> None:
# A key with a Finance role but no Sales role can read the subscription report and not the
# sales one. The check can't run, so it must not fail a sync it cannot judge.
@@ -1418,7 +1418,7 @@ class TestSalesReports:
assert rows == []
assert api.report_dates("SUBSCRIPTION") == ["2026-03-02", "2026-03-03", "2026-03-04"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_sales_report_400_is_not_tolerated(self) -> None:
# SALES reports don't carry the subscription-family quirk, so a 400 there is a real error and
# must still surface rather than being silently treated as an empty day.
@@ -1441,7 +1441,7 @@ class TestSalesReports:
)
)
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_subscription_report_unrecognized_400_fails_loudly(self) -> None:
# A 400 whose body is not Apple's "no data" quirk is a genuinely malformed request (a wrong
# version or sub type). It must fail rather than read as an empty day across the whole
@@ -1462,7 +1462,7 @@ class TestSalesReports:
db_incremental_field_last_value=date(2026, 3, 4),
)
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_all_empty_run_logs_a_warning(self) -> None:
# Every day tolerated as empty and no rows anywhere: log once at the end so an operator can
# tell an account with no subscription data from a request Apple keeps rejecting.
@@ -1486,7 +1486,7 @@ class TestSalesReports:
assert "days_tolerated_as_empty=3" in run_summary[0]
assert "Invalid vendor number specified" in run_summary[0]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_run_with_rows_does_not_log_the_empty_warning(self) -> None:
api = _FakeReportApi({"2026-03-04": "SKU\tUnits\nacme\t1\n"}, missing_status_code=400)
logger = MagicMock()
@@ -1503,7 +1503,7 @@ class TestSalesReports:
assert not any("produced no rows" in call.args[0] for call in logger.warning.call_args_list)
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_unparseable_values_are_nulled_with_counted_warnings(self) -> None:
# Three bad units and one bad date must produce one first-occurrence warning per column
# plus one end-of-run summary, never one log line per value.
@@ -1528,7 +1528,7 @@ class TestSalesReports:
assert "'units': 3" in warning_messages[-1]
assert "'begin_date': 1" in warning_messages[-1]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_sends_the_report_type_filters_from_settings(self) -> None:
api = self._api({"2026-03-04": "SKU\tUnits\nacme\t1\n"})
@@ -1548,7 +1548,7 @@ class TestSalesReports:
assert params["filter[version]"] == "1_4"
assert params["filter[vendorNumber]"] == "85234567"
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_first_sync_starts_one_retention_window_back(self) -> None:
api = self._api({})
@@ -1557,7 +1557,7 @@ class TestSalesReports:
first_requested = api.calls[0][1]["filter[reportDate]"]
assert first_requested == (date(2026, 3, 5) - timedelta(days=SALES_REPORT_LOOKBACK_DAYS)).isoformat()
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_future_watermark_is_clamped_to_the_newest_published_date(self) -> None:
api = self._api({})
@@ -1572,7 +1572,7 @@ class TestSalesReports:
assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-04"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_bookmark_advances_to_the_next_unfetched_date(self) -> None:
api = self._api({"2026-03-02": "SKU\tUnits\nacme\t1\n"})
manager = _FakeManager()
@@ -1588,7 +1588,7 @@ class TestSalesReports:
assert [state.report_date for state in manager.saved] == ["2026-03-03", "2026-03-04"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_resumes_from_the_saved_report_date(self) -> None:
api = self._api({})
manager = _FakeManager(AppStoreConnectResumeConfig(report_date="2026-03-04"))
@@ -1604,7 +1604,7 @@ class TestSalesReports:
assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-04"]
- @freeze_time("2026-03-05 09:00:00")
+ @time_machine.travel("2026-03-05 09:00:00", tick=False)
def test_per_run_day_cap_stops_the_walk(self) -> None:
api = self._api({})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py
index 450ac1383940..4606fc1f91fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py
@@ -6,7 +6,7 @@ from typing import Any
from urllib.parse import urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -286,7 +286,7 @@ class TestAppdynamicsClient:
with _patch_session(session):
client = AppdynamicsClient(BASE_URL, OAUTH_AUTH, mock.MagicMock())
- with freeze_time("2024-01-31T00:00:00Z") as frozen:
+ with time_machine.travel("2024-01-31T00:00:00Z", tick=False) as frozen:
client.get_json("/controller/rest/applications", {})
client.get_json("/controller/rest/applications", {})
assert len(session.post_calls) == 1
@@ -306,7 +306,7 @@ class TestAppdynamicsClient:
with _patch_session(session):
client = AppdynamicsClient(BASE_URL, OAUTH_AUTH, mock.MagicMock())
- with freeze_time("2024-01-31T00:00:00Z") as frozen:
+ with time_machine.travel("2024-01-31T00:00:00Z", tick=False) as frozen:
client.get_json("/controller/rest/applications", {})
assert len(session.post_calls) == 1
frozen.move_to("2024-01-31T00:00:06Z") # past the 5s cache window (10 - min(60, 5))
@@ -496,7 +496,7 @@ class TestGetRows:
batches, _ = _run_get_rows(responder, "tiers", manager)
assert [row["application_id"] for batch in batches for row in batch] == [1]
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_windowed_full_refresh_uses_lookback_and_chunks(self) -> None:
def responder(path: str, params: dict[str, Any]) -> FakeResponse:
if path == "/controller/rest/applications":
@@ -518,7 +518,7 @@ class TestGetRows:
# each window's state is saved after its rows are yielded
assert [s.window_start for s in manager.saved] == [end for _, end in window_calls]
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_windowed_incremental_starts_one_ms_after_watermark(self) -> None:
watermark = FROZEN_NOW_MS - MILLIS_PER_DAY
@@ -541,7 +541,7 @@ class TestGetRows:
assert params["end-time"] == FROZEN_NOW_MS
assert len(session.get_calls) == 2
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_windowed_resume_uses_saved_window_for_bookmarked_app_only(self) -> None:
resume_start = FROZEN_NOW_MS - MILLIS_PER_DAY
@@ -567,7 +567,7 @@ class TestGetRows:
assert "/applications/2/" in app_2_call[0]
assert app_2_call[1]["start-time"] == FROZEN_NOW_MS - 2 * MILLIS_PER_DAY + 1
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_metric_data_flattens_metric_values_per_path(self) -> None:
metric = {
"metricId": 42,
@@ -611,7 +611,7 @@ class TestGetRows:
assert rows[0]["metricId"] == 42
assert rows[0]["value"] == 12
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_capped_window_is_bisected_until_every_slice_fits(self) -> None:
# `events` returns at most 600 rows for a window and offers no cursor to reach the rest,
# so a full response means rows were dropped: the window has to be halved and refetched.
@@ -650,7 +650,7 @@ class TestGetRows:
assert event_times == sorted(event_times)
assert len(event_times) == 8
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_window_that_cannot_be_split_further_warns_and_keeps_its_rows(self) -> None:
def responder(path: str, params: dict[str, Any]) -> FakeResponse:
if path == "/controller/rest/applications":
@@ -673,7 +673,7 @@ class TestGetRows:
assert len(batches[0]) == MAX_ROWS_PER_TIME_WINDOW
assert logger.warning.call_count == 1
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_splitting_draws_from_the_sync_wide_request_allowance(self) -> None:
# Splitting is per window but the fan-out limit is per sync, so a controller that
# returns a full response every time must not multiply an accepted sync by the
@@ -705,7 +705,7 @@ class TestGetRows:
("request_snapshots", {"maximum-results": MAX_ROWS_PER_TIME_WINDOW}),
]
)
- @freeze_time("2024-01-31T00:00:00Z")
+ @time_machine.travel("2024-01-31T00:00:00Z", tick=False)
def test_windowed_endpoint_sends_its_required_params(self, endpoint: str, expected: dict[str, Any]) -> None:
# The Controller rejects an events request with no `event-types`/`severities`, and caps
# snapshots at its own default unless `maximum-results` is asked for.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
index 14ab24e4e644..b7ae7ee075b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures import appfigures
@@ -206,7 +206,7 @@ class TestIterPaged:
class TestIterReport:
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_windows_date_range_into_chunks(self):
body_by_window: dict[str, dict] = {
"2024-01-01": {"2024-01-01": {"downloads": 1}},
@@ -235,7 +235,7 @@ class TestIterReport:
# State saved after the first window, pointing at the next window's start.
manager.save_state.assert_called_once_with(AppfiguresResumeConfig(window_start="2024-01-31"))
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_report_request_sets_group_by_and_granularity(self):
with mock.patch(f"{_MODULE}._fetch", return_value={}) as fetch:
list(
@@ -252,7 +252,7 @@ class TestIterReport:
assert params["group_by"] == "dates"
assert params["granularity"] == "daily"
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_resume_starts_from_saved_window(self):
with mock.patch(f"{_MODULE}._fetch", return_value={}) as fetch:
list(
@@ -352,7 +352,7 @@ class TestFlattenRanks:
class TestIterRanks:
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_fans_out_over_product_chunks_and_yields_dates_ascending(self):
products = {str(index): {"id": index, "type": "app"} for index in range(1, 4)}
# An in-app purchase never holds a store category rank, so it must not reach the /ranks path.
@@ -403,7 +403,7 @@ class TestIterRanks:
assert [batch[0]["date"] for batch in batches] == ["2024-02-14", "2024-02-15"]
assert [sorted(row["product_id"] for row in batch) for batch in batches] == [[1, 2, 3], [1, 2, 3]]
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_walks_date_windows_and_saves_state_after_each(self):
windows: list[tuple[str, str]] = []
@@ -432,7 +432,7 @@ class TestIterRanks:
assert windows == [("2024-01-01", "2024-01-30"), ("2024-01-31", "2024-02-15")]
manager.save_state.assert_called_once_with(AppfiguresResumeConfig(window_start="2024-01-31"))
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_resume_starts_from_saved_window(self):
starts: list[str] = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py
index c36a4aca07c0..414b3244cb47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any, Protocol
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -143,16 +143,16 @@ class TestDateFormatting:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_is_clamped(self):
assert _clamp_future_value_to_now(datetime(2027, 1, 1, tzinfo=UTC)) == datetime(2026, 6, 15, 12, 0, tzinfo=UTC)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_is_unchanged(self):
value = datetime(2024, 3, 4, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_date_is_clamped(self):
assert _clamp_future_value_to_now(date(2027, 1, 1)) == date(2026, 6, 15)
@@ -440,7 +440,7 @@ class TestResolveCountry:
class TestSnapshotFanOut:
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
def test_rankings_requests_today_once_per_app_and_stamps_the_key_fields(self, monkeypatch):
# `/meta/rankings` has no pagination and no date range, so one request per app is the whole
# walk. `ext_id` and `date` are stamped because the primary key and partition key need them.
@@ -451,7 +451,7 @@ class TestSnapshotFanOut:
assert len(params) == 1
assert params[0] == {"ext_id": "111", "date": "2026-06-15"}
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
def test_a_row_that_carries_its_own_date_is_not_overwritten(self, monkeypatch):
api = _fanout_api([[{"keyword": "photos", "date": "2026-06-14"}]], envelope="keywords")
rows = _collect("keywords", _FakeManager(), monkeypatch, api)
@@ -520,7 +520,7 @@ class TestCountryScopedFanOut:
class TestWindowedFanOut:
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
def test_full_refresh_opens_the_whole_window(self, monkeypatch):
api = _fanout_api([[{"date": "2026-06-01", "reviews": 4}]], envelope="stats")
_collect(
@@ -534,7 +534,7 @@ class TestWindowedFanOut:
params = _calls_to(api, "/reviews/stats")[0]
assert params == {"ext_id": "111", "from": DEFAULT_START_DATE, "to": "2026-06-15"}
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
def test_incremental_sync_moves_from_to_the_watermark(self, monkeypatch):
api = _fanout_api([[{"date": "2026-06-11", "reviews": 4}]], envelope="stats")
_collect(
@@ -547,7 +547,7 @@ class TestWindowedFanOut:
)
assert _calls_to(api, "/reviews/stats")[0]["from"] == "2026-06-10"
- @freeze_time("2026-06-15T09:00:00Z")
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
def test_a_future_watermark_is_clamped_so_the_table_cannot_freeze(self, monkeypatch):
api = _fanout_api([[{"date": "2026-06-11"}]], envelope="stats")
_collect(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
index 8cb77f5dfaf6..5a2c7f872a98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -88,7 +88,7 @@ class TestFlattenAnalytics:
class TestAnalyticsWindow:
- @freeze_time("2026-06-15")
+ @time_machine.travel("2026-06-15", tick=False)
def test_first_sync_uses_default_lookback(self) -> None:
# No watermark: pull the configured history window (365 days) rather than an unbounded range.
config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
@@ -96,7 +96,7 @@ class TestAnalyticsWindow:
assert start == "2025-06-15"
assert end == "2026-06-15"
- @freeze_time("2026-06-15")
+ @time_machine.travel("2026-06-15", tick=False)
def test_incremental_run_rewinds_watermark_by_lookback(self) -> None:
# Recent daily aggregates get revised upstream, so each run must re-pull a trailing window;
# advancing straight from the watermark would freeze the last few days at stale values.
@@ -116,13 +116,13 @@ class TestAnalyticsWindow:
)
def test_watermark_accepts_multiple_value_types(self, _name: str, value: Any, expected_start: str) -> None:
config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
- with freeze_time("2026-06-15"):
+ with time_machine.travel("2026-06-15", tick=False):
start, _ = _analytics_window(
config, should_use_incremental_field=True, db_incremental_field_last_value=value
)
assert start == expected_start
- @freeze_time("2026-06-15")
+ @time_machine.travel("2026-06-15", tick=False)
def test_future_watermark_is_clamped_to_today(self) -> None:
# A future-dated watermark would otherwise make start > end and produce an invalid window.
config = AVIATOR_ENDPOINTS["merge_queue_analytics"]
@@ -291,7 +291,7 @@ class TestFanOutExtraction:
captured.update(params or {})
return {"mergequeue_usage": [{"date": "2026-06-14", "total": 5}]}
- with freeze_time("2026-06-15"):
+ with time_machine.travel("2026-06-15", tick=False):
rows = _run_fan_out(
"merge_queue_analytics",
fake_fetch,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.py
index 60b56acead95..5d11ae733b6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -90,7 +90,7 @@ class TestWindowsForAccount:
windows = _windows_for_account(AWIN_ENDPOINTS["programmes"], False, None)
assert windows == [None]
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_reports_use_lookback_window_regardless_of_incremental(self) -> None:
windows = _windows_for_account(AWIN_ENDPOINTS["reports_advertiser"], True, datetime(2020, 1, 1, tzinfo=UTC))
# 30-day rolling snapshot ending now, not the stale 2020 cursor.
@@ -99,14 +99,14 @@ class TestWindowsForAccount:
assert windows[0][0] == datetime(2024, 5, 2, tzinfo=UTC)
assert windows[0][1] == datetime(2024, 6, 1, tzinfo=UTC)
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_transactions_incremental_windows_start_at_last_value(self) -> None:
last_value = datetime(2024, 5, 15, tzinfo=UTC)
windows = _windows_for_account(AWIN_ENDPOINTS["transactions"], True, last_value)
assert windows[0] is not None
assert windows[0][0] == last_value
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_transactions_full_refresh_backfills(self) -> None:
windows = _windows_for_account(AWIN_ENDPOINTS["transactions"], False, None)
# 365-day backfill chunked into 30-day windows.
@@ -114,7 +114,7 @@ class TestWindowsForAccount:
assert windows[0][0] == datetime(2023, 6, 2, tzinfo=UTC)
assert len(windows) >= 12
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_future_cursor_yields_no_windows(self) -> None:
windows = _windows_for_account(AWIN_ENDPOINTS["transactions"], True, datetime(2025, 1, 1, tzinfo=UTC))
assert windows == []
@@ -250,7 +250,7 @@ class TestGetRows:
# A single call to /accounts, no per-publisher fan-out.
assert mock_fetch.call_count == 1
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_fanout_yields_per_account_and_saves_state(self) -> None:
manager = FakeResumableManager()
@@ -273,7 +273,7 @@ class TestGetRows:
# State saved after each account so a crash resumes at the right one.
assert [s.account_id for s in manager.saved] == [10, 20]
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_resume_skips_already_synced_accounts(self) -> None:
manager = FakeResumableManager(state=AwinResumeConfig(account_id=20, window_start=None))
fetched_publishers: list[int] = []
@@ -296,7 +296,7 @@ class TestGetRows:
# Account 10 already synced before the crash; resume starts at 20.
assert fetched_publishers == [20, 30]
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_windowed_fanout_arrives_in_globally_ascending_order(self) -> None:
# Two accounts, multiple 30-day windows each. To keep the asc watermark monotonic, every
# account's window N must be fetched before any account's window N+1 (windows OUTER, accounts
@@ -332,7 +332,7 @@ class TestGetRows:
# Each window's startDate appears once per account (two accounts).
assert all(count == 2 for count in _counts(seen_starts).values())
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_no_publisher_accounts_yields_nothing(self) -> None:
manager = FakeResumableManager()
with (
@@ -342,7 +342,7 @@ class TestGetRows:
batches = list(get_rows("token", "programmes", MagicMock(), manager, region="GB")) # type: ignore[arg-type]
assert batches == []
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_reports_advertiser_request_carries_region(self) -> None:
manager = FakeResumableManager()
seen_params: list[dict[str, Any]] = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.py
index 2c192424f791..70beb0ee9e65 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import Any, Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -305,7 +305,7 @@ class TestSendOperation:
session = mock.MagicMock(spec=requests.Session)
session.post.return_value = make_response(200, {"Budgets": []})
- with freeze_time("2024-03-05T10:00:00Z"):
+ with time_machine.travel("2024-03-05T10:00:00Z", tick=False):
send_operation(
session, aws_budgets.Credentials("AKIAEXAMPLE", "secret"), "DescribeBudgets", {"AccountId": ACCOUNT_ID}
)
@@ -544,8 +544,12 @@ class TestGetBudgetRows:
)
-@freeze_time("2024-06-01T12:00:00Z")
class TestGetFanoutRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-06-01T12:00:00Z", tick=False):
+ yield
+
LISTED = budgets_page(
[
{"BudgetName": "monthly-cost", "TimeUnit": "MONTHLY"},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.py
index d08332add193..65fc4ec510e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_anomaly_detection/tests/test_aws_cost_anomaly_detection.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import Any, Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -316,7 +316,7 @@ class TestSendOperation:
session.post.return_value = make_response(200, {"Anomalies": []})
credentials = aws_cost_anomaly_detection.Credentials("AKIAEXAMPLE", "secret")
- with freeze_time("2024-06-05T10:00:00Z"):
+ with time_machine.travel("2024-06-05T10:00:00Z", tick=False):
send_operation(session, credentials, "GetAnomalies", {"MaxResults": 100})
kwargs = session.post.call_args[1]
@@ -362,8 +362,12 @@ class TestSendOperation:
assert session.post.call_count == 1
-@freeze_time("2024-06-01T12:00:00Z")
class TestGetRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-06-01T12:00:00Z", tick=False):
+ yield
+
def _run(
self,
responses: list[Any],
@@ -567,7 +571,7 @@ class TestValidateCredentials:
):
assert validate_credentials("key", "secret", None) == (False, "Could not reach the AWS Cost Explorer API")
- @freeze_time("2024-06-01T12:00:00Z")
+ @time_machine.travel("2024-06-01T12:00:00Z", tick=False)
def test_a_per_schema_check_probes_that_schemas_own_operation(self) -> None:
with mock.patch.object(aws_cost_anomaly_detection, "send_operation", return_value={"Anomalies": []}) as send:
assert validate_credentials("key", "secret", None, schema_name="anomalies") == (True, None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
index 51eb1df8bf6a..3868c0998d04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cost_explorer/tests/test_aws_cost_explorer.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import Any, Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -352,7 +352,7 @@ class TestSendOperation:
session.post.return_value = make_response(200, {"ResultsByTime": []})
credentials = aws_cost_explorer.Credentials("AKIAEXAMPLE", "secret")
- with freeze_time("2024-03-05T10:00:00Z"):
+ with time_machine.travel("2024-03-05T10:00:00Z", tick=False):
send_operation(session, credentials, "GetCostAndUsage", {"Granularity": "DAILY"})
_, kwargs = session.post.call_args
@@ -441,8 +441,12 @@ class TestValidateCredentials:
)
-@freeze_time("2024-03-03T12:00:00Z")
class TestGetRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-03-03T12:00:00Z", tick=False):
+ yield
+
def _run(
self,
responses: list[dict[str, Any]],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py
index 3629458d5c47..14ac10d7f93c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -152,7 +152,7 @@ class TestSendRequest:
session.get.return_value = make_response(200, {})
credentials = Credentials("AKIAEXAMPLE", "secret")
- with freeze_time("2026-08-07T10:00:00Z"):
+ with time_machine.travel("2026-08-07T10:00:00Z", tick=False):
send_request(session, credentials, "eu-west-1", "/v2/email/account")
assert session.get.call_args[0][0] == "https://email.eu-west-1.amazonaws.com/v2/email/account"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
index 0ef97b1b5758..3e9d2673aa48 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/better_stack/tests/test_better_stack.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -276,7 +276,7 @@ class TestIncrementalParams:
assert snapshots[0]["params"] == expected_params
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@mock.patch(SESSION_PATCH)
def test_future_cursor_is_clamped(self, MockSession) -> None:
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
index 2411304c1c7e..9e8e1940b89c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -2,7 +2,7 @@ from types import SimpleNamespace
from typing import cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from dateutil import parser
@@ -291,7 +291,7 @@ def test_bigquery_build_pipeline_resolves_dataset_routing(
)
with (
- freeze_time("2025-01-01T12:00:00.000Z"),
+ time_machine.travel("2025-01-01T12:00:00.000Z", tick=False),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.delete_all_temp_destination_tables",
) as mock_delete_all,
@@ -1288,7 +1288,7 @@ def test_bigquery_build_pipeline_trims_whitespace_in_destination_table():
)
with (
- freeze_time("2025-01-01T12:00:00.000Z"),
+ time_machine.travel("2025-01-01T12:00:00.000Z", tick=False),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.delete_all_temp_destination_tables",
) as mock_delete_all,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.py
index 4a345355ad4e..f04185d9ff78 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/capsule_crm/tests/test_capsule_crm.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime, timedelta, timezone
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -96,24 +96,24 @@ class TestFormatSinceValue:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42, tzinfo=UTC)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_naive_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_is_unchanged(self) -> None:
value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_date_is_clamped(self) -> None:
assert _clamp_future_value_to_now(date(2027, 2, 5)) == date(2026, 6, 15)
@@ -177,7 +177,7 @@ class TestRequestParams:
assert snapshots[0]["params"]["since"] == "2026-03-04T02:58:14Z"
@mock.patch(SESSION_PATCH)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_watermark_is_clamped_to_now(self, MockSession) -> None:
session = MockSession.return_value
snapshots = _wire(session, [_response({"parties": []})])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
index 04d2b3e3c4ac..f4a63a2c4418 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
@@ -1,7 +1,7 @@
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import pyarrow as pa
@@ -155,8 +155,12 @@ def _source(
)
-@freeze_time(NOW)
class TestPaymentsWindowWalking:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
@mock.patch(PAGE_LIMIT_PATCH, 2)
@mock.patch(SESSION_PATCH)
def test_full_page_subdivides_window_and_yields_ascending(self, mock_make_session):
@@ -306,8 +310,12 @@ class TestPaymentsWindowWalking:
assert "query_required" in logger.error.call_args[0][0]
-@freeze_time(NOW)
class TestPaymentActionsFanout:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
@pytest.mark.parametrize(
"actions_payload",
[
@@ -384,8 +392,12 @@ class TestPaymentActionsFanout:
assert SYNC_BUDGET_EXCEEDED_MARKER in str(excinfo.value)
-@freeze_time(NOW)
class TestCustomersFanout:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
@mock.patch(SESSION_PATCH)
def test_email_only_references_resolve_once_per_customer(self, mock_make_session):
# `/payments/search` returns customers as an email with no `cus_` id; requiring an
@@ -483,8 +495,12 @@ class TestCustomersFanout:
assert "[email protected]" not in logger.error.call_args[0][0]
-@freeze_time(NOW)
class TestInstrumentsFanout:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
@mock.patch(SESSION_PATCH)
def test_resolves_instrument_ids_via_payment_detail(self, mock_make_session):
# `/payments/search` describes a card source (fingerprint, last4) without an
@@ -599,8 +615,12 @@ class TestInstrumentsFanout:
assert manager.saved_states == []
-@freeze_time(NOW)
class TestPaymentsCustomerIdColumn:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
@mock.patch(SESSION_PATCH)
def test_rows_carry_customer_id_resolved_once_per_email(self, mock_make_session):
# Search rows reference their customer by email alone, so without resolution the
@@ -680,8 +700,12 @@ class TestPaymentsCustomerIdColumn:
assert len(session.lookups) == 1
-@freeze_time(NOW)
class TestUnresolvableReferences:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
@pytest.mark.parametrize(
"schema_name, payment",
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.py
index 1537860b610f..338465260808 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.py
@@ -2,7 +2,7 @@ from datetime import date
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -133,7 +133,7 @@ class TestGetRowsData:
with pytest.raises(ValueError):
list(get_rows(endpoint="daily_data", app_key="k", targets=[], unit_of_measure="E", logger=mock.Mock()))
- @freeze_time("2023-01-03 12:00:00")
+ @time_machine.travel("2023-01-03 12:00:00", tick=False)
def test_daily_full_refresh_windows_from_epoch(self, monkeypatch: Any) -> None:
urls: list[str] = []
@@ -151,7 +151,7 @@ class TestGetRowsData:
# No request may reach into the future.
assert all("endDate=2023-01-03" in u for u in urls[-1:])
- @freeze_time("2023-01-10 12:00:00")
+ @time_machine.travel("2023-01-10 12:00:00", tick=False)
def test_daily_incremental_starts_from_last_value(self, monkeypatch: Any) -> None:
urls: list[str] = []
@@ -174,7 +174,7 @@ class TestGetRowsData:
# The first window must begin at the saved watermark, not the epoch.
assert "startDate=2023-01-08" in urls[0]
- @freeze_time("2023-01-02 12:00:00")
+ @time_machine.travel("2023-01-02 12:00:00", tick=False)
def test_no_requests_when_watermark_in_future(self, monkeypatch: Any) -> None:
urls: list[str] = []
@@ -197,7 +197,7 @@ class TestGetRowsData:
assert batches == []
assert urls == []
- @freeze_time("2020-01-01 12:00:00")
+ @time_machine.travel("2020-01-01 12:00:00", tick=False)
def test_hourly_with_many_targets_keeps_each_request_under_cap(self, monkeypatch: Any) -> None:
# 100 hourly targets over a single day would be 2400 records — over the cap — so the source
# must split the target set and keep the date window at a single day.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.py
index 8e07c6599016..416dffc19018 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse_cloud/tests/test_clickhouse_cloud.py
@@ -3,7 +3,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -89,8 +89,12 @@ def _window_params(calls: list[str]) -> list[tuple[date, date]]:
return windows
-@freeze_time("2026-07-15")
class TestUsageCostWindowing:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-15", tick=False):
+ yield
+
def test_full_refresh_windows_are_contiguous_and_capped_at_31_days(self, monkeypatch: Any) -> None:
# A window longer than 31 days is rejected by the API with a 400, and overlapping windows
# would yield duplicate rows within a single sync (merge only dedupes across syncs).
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py
index 4a80920dacd2..69fd23c32cfe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -97,7 +97,7 @@ class TestClampFutureValueToNow:
("past_iso_string", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
]
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_clamp(self, _name: str, value: Any, expected: Any) -> None:
assert _clamp_future_value_to_now(value) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo.py
index a6328ebbf51e..44cee34e4703 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -110,7 +110,7 @@ class TestFormatZ:
class TestEndpointParams:
- @freeze_time("2026-06-29T12:00:00Z")
+ @time_machine.travel("2026-06-29T12:00:00Z", tick=False)
def test_entries_requires_time_window(self) -> None:
params = _endpoint_params("entries", CLOCKODO_ENDPOINTS_V2["entries"])
# Listing entries without a time range is rejected by the API.
@@ -223,7 +223,7 @@ class TestPagination:
manager.save_state.assert_not_called()
@mock.patch(CLIENT_SESSION_PATCH)
- @freeze_time("2026-06-29T12:00:00Z")
+ @time_machine.travel("2026-06-29T12:00:00Z", tick=False)
def test_entries_sends_time_window(self, MockSession) -> None:
session = MockSession.return_value
params, _auths, _urls = _wire(session, [_response([{"id": 1}], data_key="entries", count_pages=1)])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.py
index 9d515131c1d5..6d5390396df8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.py
@@ -5,7 +5,7 @@ from typing import Any, cast
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import urllib3
@@ -156,7 +156,7 @@ class TestCodyTransport:
session.get.return_value = _response(200, text=CSV_BODY)
with (
- freeze_time("2025-06-15"),
+ time_machine.travel("2025-06-15", tick=False),
mock.patch.object(cody, "make_tracked_session", return_value=session),
):
assert validate_credentials("token", "example.com") is True
@@ -272,7 +272,7 @@ class TestCodyTransport:
session.get.side_effect = lambda *args, **kwargs: _response(200, text=CSV_BODY)
with (
- freeze_time("2023-03-15"),
+ time_machine.travel("2023-03-15", tick=False),
mock.patch.object(cody, "make_tracked_session", return_value=session),
):
batches = list(_batches(cody_source("token", "example.com", "usage_by_user_day", mock.Mock(), manager)))
@@ -297,7 +297,7 @@ class TestCodyTransport:
session.get.return_value = _response(200, text=CSV_BODY)
with (
- freeze_time("2023-03-15"),
+ time_machine.travel("2023-03-15", tick=False),
mock.patch.object(cody, "make_tracked_session", return_value=session),
):
list(_batches(cody_source("token", "example.com", "usage_by_user_day", mock.Mock(), manager)))
@@ -312,7 +312,7 @@ class TestCodyTransport:
session.get.side_effect = lambda *args, **kwargs: _response(200, text=CSV_BODY)
with (
- freeze_time("2023-02-10"),
+ time_machine.travel("2023-02-10", tick=False),
mock.patch.object(cody, "make_tracked_session", return_value=session),
):
iterator = _batches(cody_source("token", "example.com", "usage_by_user_day", mock.Mock(), manager))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
index b45c745374c5..528bdf1a2a41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -304,7 +304,7 @@ class TestOffsetPagination:
class TestEventsWindowPagination:
- @freeze_time("2024-01-20")
+ @time_machine.travel("2024-01-20", tick=False)
def test_walks_weekly_windows_with_bounded_range(self):
last_value = int(datetime(2024, 1, 1, tzinfo=UTC).timestamp() * 1000)
_rows, urls, manager = _run(
@@ -320,7 +320,7 @@ class TestEventsWindowPagination:
# windows advance and checkpoint so a crash resumes at the next window
assert manager.saved and manager.saved[-1].window_start_ms is not None
- @freeze_time("2024-01-20")
+ @time_machine.travel("2024-01-20", tick=False)
def test_resumes_from_saved_window(self):
resume_ms = int(datetime(2024, 1, 15, tzinfo=UTC).timestamp() * 1000)
manager = FakeManager(ConcordResumeConfig(window_start_ms=resume_ms))
@@ -353,14 +353,14 @@ class TestEventsWindowPagination:
emitted = [r["id"] for table in tables for r in table.to_pylist()]
return emitted, manager
- @freeze_time("2024-01-20")
+ @time_machine.travel("2024-01-20", tick=False)
def test_mid_window_flush_advances_row_offset_monotonically(self):
_emitted, manager = self._iter_single_window()
window_ms = int(datetime(2024, 1, 18, tzinfo=UTC).timestamp() * 1000)
# flushes after rows 1 and 3 (0-indexed) → committed counts 2 then 4, never rewinding to 0
assert [(s.window_start_ms, s.row_offset) for s in manager.saved] == [(window_ms, 2), (window_ms, 4)]
- @freeze_time("2024-01-20")
+ @time_machine.travel("2024-01-20", tick=False)
def test_resume_skips_already_emitted_window_rows(self):
emitted, _ = self._iter_single_window(start_row_offset=3)
# rows 0–2 were committed last run; the resume must not re-emit them
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py
index 7e2c63ad9014..65960f7511d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock
from parameterized import parameterized
@@ -207,7 +207,7 @@ class TestMetricsRows:
with pytest.raises(MissingResourceIdsError):
_collect(monkeypatch, api, _FakeResumableManager(), endpoint="kafka_metrics", resource_ids=[])
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_windows_metrics_and_rows(self, monkeypatch: Any) -> None:
api = _FakeApi(
metric_descriptors=[_GA_METRIC, _DEPRECATED_METRIC],
@@ -241,7 +241,7 @@ class TestMetricsRows:
"value": 1.0,
}
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_saves_state_after_each_completed_window_except_last(self, monkeypatch: Any) -> None:
api = _FakeApi(metric_descriptors=[_GA_METRIC])
manager = _FakeResumableManager()
@@ -257,7 +257,7 @@ class TestMetricsRows:
assert manager.saved == [ConfluentCloudResumeConfig(window_start="2026-07-15T10:00:00Z")]
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_resumes_from_saved_window(self, monkeypatch: Any) -> None:
api = _FakeApi(metric_descriptors=[_GA_METRIC])
manager = _FakeResumableManager(ConfluentCloudResumeConfig(window_start="2026-07-15T10:00:00Z"))
@@ -274,7 +274,7 @@ class TestMetricsRows:
intervals = [q["body"]["intervals"] for q in api.queries]
assert intervals == [["2026-07-15T10:00:00Z/2026-07-15T12:00:00Z"]]
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
def test_query_pagination_reposts_identical_body_with_page_token(self, monkeypatch: Any) -> None:
api = _FakeApi(
metric_descriptors=[_GA_METRIC],
@@ -316,7 +316,7 @@ class TestValidateCredentials:
session = MagicMock()
session.post.return_value.status_code = status_code
with (
- freeze_time(_NOW),
+ time_machine.travel(_NOW, tick=False),
pytest.MonkeyPatch.context() as mp,
):
mp.setattr(confluent_cloud, "_make_session", lambda *a, **k: session)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py
index b96cd67c8295..cd15b08f79e2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coralogix/tests/test_coralogix.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -251,7 +251,7 @@ class TestGetRows:
)
session.post.assert_not_called()
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_walks_windows_without_double_counting_boundaries(self) -> None:
watermark = NOW - timedelta(hours=2)
boundary = NOW - timedelta(hours=1)
@@ -282,7 +282,7 @@ class TestGetRows:
assert saved == [_format_datetime(boundary), _format_datetime(NOW)]
manager.clear_state.assert_called_once()
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_bisects_windows_that_hit_the_row_cap(self) -> None:
start = NOW - timedelta(hours=2)
server = _FakeServer(
@@ -304,7 +304,7 @@ class TestGetRows:
assert server.calls[0]["start"] == server.calls[1]["start"] # first bisection retried the cursor
assert server.calls[1]["end"] - server.calls[1]["start"] < server.calls[0]["end"] - server.calls[0]["start"]
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_min_window_cap_warns_and_advances(self) -> None:
# A window at the minimum size that still hits the cap must warn (no silent truncation)
# and advance — not bisect forever.
@@ -318,7 +318,7 @@ class TestGetRows:
assert logger.warning.call_count == 1
assert "cap" in logger.warning.call_args.args[0]
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_resumes_inclusively_from_saved_state(self) -> None:
watermark = NOW - timedelta(hours=2)
synced_until = NOW - timedelta(hours=1)
@@ -341,7 +341,7 @@ class TestGetRows:
assert server.calls[0]["start"] == synced_until
assert logids == ["at-resume-point"]
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_initial_sync_covers_the_default_lookback_contiguously(self) -> None:
server = _FakeServer([])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
index 3c9f9315a542..7139cc5ff05a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
@@ -6,7 +6,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, cast
from urllib.parse import quote
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -585,7 +585,7 @@ class TestCustomSourceOAuth2IntegrationWiring(BaseTest):
fresh = CustomOAuth2Integration.objects.for_team(self.team.pk).get(pk=integration.pk)
assert fresh.sensitive_config["refresh_token"] == "rotated-RT"
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
@patch(f"{AUTH_MODULE}.make_tracked_session")
def test_reuses_cached_token_without_minting(self, mock_session):
# A still-valid cached token means no mint at all — the manifest is seeded straight from the row.
@@ -602,7 +602,7 @@ class TestCustomSourceOAuth2IntegrationWiring(BaseTest):
# No refresh material is seeded — the engine treats it as a static bearer and never mints.
assert "refresh_token" not in auth
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
@patch(f"{AUTH_MODULE}.make_tracked_session")
def test_post_injection_manifest_builds_static_bearer_that_never_mints(self, mock_session):
# End-to-end seam: feed the injected client.auth through the engine's own auth construction
@@ -878,7 +878,7 @@ class TestCustomSourceOAuth2SecretAdoption(BaseTest):
# expiry, or the row would just reuse the still-valid cached access token without minting.
self._mock_mint(mock_token_session, mock_probe_session, rotated="rotated-RT-1")
first_config = self._static_config()
- with freeze_time("2025-01-01T00:00:00Z"):
+ with time_machine.travel("2025-01-01T00:00:00Z", tick=False):
ok, err = CustomSource().validate_credentials(
first_config, team_id=self.team.pk, owner_user_id=self.user.pk
)
@@ -886,7 +886,7 @@ class TestCustomSourceOAuth2SecretAdoption(BaseTest):
self._mock_mint(mock_token_session, mock_probe_session, rotated="rotated-RT-2")
second_config = self._static_config()
- with freeze_time("2025-01-01T02:00:00Z"):
+ with time_machine.travel("2025-01-01T02:00:00Z", tick=False):
ok, err = CustomSource().validate_credentials(
second_config, team_id=self.team.pk, owner_user_id=self.user.pk
)
@@ -1133,7 +1133,7 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):
assert ok, err
mock_session.assert_not_called()
- @freeze_time("2025-01-01T00:00:00Z")
+ @time_machine.travel("2025-01-01T00:00:00Z", tick=False)
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")
def test_oauth2_minted_token_joins_probe_redaction(self, mock_session):
# The pre-mint runs before the probe session is built, so the freshly-minted access token
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py
index 74565e0b70f0..7ac845ae2f94 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepgram/tests/test_deepgram.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -87,7 +87,7 @@ class TestFormatStartValue:
def test_format(self, _name: str, value: Any, expected: str) -> None:
assert _format_start_value(value) == expected
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_clamped_to_now(self) -> None:
# Asking for requests created after "now" is pointless; cap it so we don't skip the window.
assert _format_start_value(datetime(2027, 1, 1, tzinfo=UTC)) == "2026-06-15T12:00:00+00:00"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.py
index 1a25575f81c1..a412f45b4c6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.py
@@ -4,7 +4,7 @@ from types import SimpleNamespace
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -120,18 +120,18 @@ class TestPureHelpers:
def test_reshape_analytics_empty_values(self) -> None:
assert _reshape_analytics({"fields": [{"name": "time"}], "values": []}, "a", "s") == []
- @freeze_time("2026-06-01T12:00:00Z")
+ @time_machine.travel("2026-06-01T12:00:00Z", tick=False)
def test_time_window_first_sync_uses_lookback(self) -> None:
start, end = _time_window_params(DENO_DEPLOY_ENDPOINTS["logs"], True, None)
assert start == "2026-05-25T12:00:00Z" # now - 7d default lookback
assert end == "2026-06-01T12:00:00Z"
- @freeze_time("2026-06-01T12:00:00Z")
+ @time_machine.travel("2026-06-01T12:00:00Z", tick=False)
def test_time_window_incremental_subtracts_lookback(self) -> None:
start, _ = _time_window_params(DENO_DEPLOY_ENDPOINTS["logs"], True, datetime(2026, 6, 1, 10, 0, 0, tzinfo=UTC))
assert start == "2026-06-01T09:55:00Z" # watermark - 5min lookback
- @freeze_time("2026-06-01T12:00:00Z")
+ @time_machine.travel("2026-06-01T12:00:00Z", tick=False)
def test_time_window_future_watermark_clamped(self) -> None:
start, end = _time_window_params(DENO_DEPLOY_ENDPOINTS["analytics"], True, datetime(2027, 1, 1, tzinfo=UTC))
assert start == "2026-06-01T11:30:00Z" # min(future, now) - 30min lookback
@@ -210,7 +210,7 @@ class TestFanOut:
]
assert params[1]["limit"] == 100 # child list uses the default page size
- @freeze_time("2026-06-01T12:00:00Z")
+ @time_machine.travel("2026-06-01T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_logs_paginate_via_next_cursor(self, MockSession) -> None:
session = MockSession.return_value
@@ -234,7 +234,7 @@ class TestFanOut:
saved = [c.args[0] for c in manager.save_state.call_args_list]
assert any(s.fanout_state and s.fanout_state.get("child_state") == {"cursor": "c2"} for s in saved)
- @freeze_time("2026-06-01T12:00:00Z")
+ @time_machine.travel("2026-06-01T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_analytics_columnar_explode_with_window(self, MockSession) -> None:
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py
index 2bbf596d5fc0..0f64519c1b7c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -56,13 +56,13 @@ class TestFormatDatetime:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, tzinfo=UTC)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_is_unchanged(self) -> None:
value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
index 6c7f6cd0ae43..477563eea752 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
@@ -4,7 +4,7 @@ from collections.abc import Iterable, Iterator
from typing import Any, Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
import structlog
@@ -252,7 +252,7 @@ class TestEtsyTransport:
assert len(rows) == MAX_OFFSET + PAGE_SIZE
assert max(call[1]["offset"] for call in session.get_calls) == MAX_OFFSET
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_windowed_endpoint_sends_a_created_window_over_all_history(self) -> None:
session = _FakeSession([_page(_rows(2), 2)])
rows, _ = _collect(session, "receipts")
@@ -263,7 +263,7 @@ class TestEtsyTransport:
assert params["limit"] == PAGE_SIZE
assert len(rows) == 2
- @freeze_time("2005-07-01")
+ @time_machine.travel("2005-07-01", tick=False)
def test_windows_advance_until_the_range_is_covered(self) -> None:
session = _FakeSession([_page([], 0) for _ in range(3)])
_collect(session, "receipts")
@@ -276,7 +276,7 @@ class TestEtsyTransport:
assert windows[2][0] == windows[1][1] + 1
assert windows[-1][1] == int(time.time())
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_oversized_window_is_halved_instead_of_hitting_the_offset_ceiling(self) -> None:
# First probe reports more rows than the offset ceiling can reach, so the slice splits.
session = _FakeSession(
@@ -291,7 +291,7 @@ class TestEtsyTransport:
# The oversized probe page is discarded, so only the halves' rows land.
assert len(rows) == 2
- @freeze_time("2005-01-01 00:30:00")
+ @time_machine.travel("2005-01-01 00:30:00", tick=False)
def test_window_that_cannot_be_split_further_stops_at_the_offset_ceiling(self) -> None:
# A one-hour slice is the floor, so an over-full one reads what it can and moves on.
pages = [_page(_rows(PAGE_SIZE), 50_000) for _ in range(MAX_OFFSET // PAGE_SIZE + 1)]
@@ -302,7 +302,7 @@ class TestEtsyTransport:
assert window["max_created"] - window["min_created"] < MIN_WINDOW_SECONDS
assert len(rows) == MAX_OFFSET + PAGE_SIZE
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_resume_finishes_the_saved_window_then_continues_after_it(self) -> None:
saved_end = ETSY_HISTORY_START + 1000
manager = _FakeManager(
@@ -319,7 +319,7 @@ class TestEtsyTransport:
)
assert second["min_created"] == saved_end + 1
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_state_is_saved_after_each_batch_and_cleared_when_the_walk_finishes(self) -> None:
session = _FakeSession([_page(_rows(PAGE_SIZE), 150), _page(_rows(50, start=100), 150)])
_, manager = _collect(session, "receipts")
@@ -328,7 +328,7 @@ class TestEtsyTransport:
assert manager.saved[0].window_start == ETSY_HISTORY_START
assert manager.cleared == 1
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_transactions_are_expanded_out_of_the_receipts_payload(self) -> None:
session = _FakeSession(
[
@@ -346,7 +346,7 @@ class TestEtsyTransport:
assert rows == [{"transaction_id": 10}, {"transaction_id": 11}]
assert session.get_calls[0][0].endswith("/shops/1/receipts")
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_offset_advances_by_parent_rows_not_expanded_children(self) -> None:
# Offset addresses receipts, so a page of 100 receipts advances by 100 even when it
# expands into far more transactions.
@@ -369,7 +369,7 @@ class TestEtsyTransport:
(None, "min_created"),
]
)
- @freeze_time("2006-01-15")
+ @time_machine.travel("2006-01-15", tick=False)
def test_incremental_field_selects_the_matching_etsy_filter(
self, incremental_field: Optional[str], expected_param: str
) -> None:
@@ -387,7 +387,7 @@ class TestEtsyTransport:
assert expected_param in params
assert params[expected_param] == cursor
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_full_refresh_ignores_a_stale_cursor(self) -> None:
session = _FakeSession([_page([], 0)])
_collect(session, "receipts", should_use_incremental_field=False, db_incremental_field_last_value=999_999_999)
@@ -473,7 +473,7 @@ class TestEtsySourceResponse:
# run completes — which is what "desc" buys us.
assert response.sort_mode == "desc"
- @freeze_time("2005-01-15")
+ @time_machine.travel("2005-01-15", tick=False)
def test_items_is_lazy_and_streams_rows(self) -> None:
session = _FakeSession([_page(_rows(3), 3)])
response = etsy_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
index 1408444feae3..6729b5f38ab4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.everhour import (
@@ -68,17 +68,17 @@ class TestFormatDate:
class TestTimeRecordsWindow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_first_sync_spans_all_history(self) -> None:
window = _time_records_window(should_use_incremental_field=True, db_incremental_field_last_value=None)
assert window == {"from": EARLIEST_FROM_DATE, "to": "2026-06-15"}
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_full_refresh_spans_all_history(self) -> None:
window = _time_records_window(should_use_incremental_field=False, db_incremental_field_last_value=None)
assert window == {"from": EARLIEST_FROM_DATE, "to": "2026-06-15"}
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_incremental_floors_from_to_watermark_day(self) -> None:
window = _time_records_window(
should_use_incremental_field=True, db_incremental_field_last_value=date(2026, 5, 1)
@@ -124,7 +124,7 @@ class TestBuildInitialUrls:
urls = _build_initial_urls(EVERHOUR_ENDPOINTS["clients"], None, {}, mock.MagicMock(), mock.MagicMock())
assert urls == [f"{EVERHOUR_BASE_URL}/clients?limit=100"]
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_time_records_bakes_in_date_window(self) -> None:
window = _time_records_window(should_use_incremental_field=True, db_incremental_field_last_value=None)
urls = _build_initial_urls(EVERHOUR_ENDPOINTS["time_records"], window, {}, mock.MagicMock(), mock.MagicMock())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py
index d7573562e425..988802637b95 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock
import requests
@@ -116,8 +116,12 @@ class TestToDate:
assert _to_date(value) == expected
-@freeze_time("2024-06-15")
class TestWindowParams:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-06-15", tick=False):
+ yield
+
def test_non_windowed_endpoint_returns_empty(self) -> None:
config = FINANCIAL_MODELLING_ENDPOINTS["company_profiles"]
assert (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
index 71d676d447fa..9088055bc94f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -111,25 +111,25 @@ class TestRequestParams:
params = _request_params(FINNHUB_ENDPOINTS["basic_financials"], "AAPL", "US", False, None)
assert params == {"symbol": "AAPL", "metric": "all"}
- @freeze_time("2024-06-15")
+ @time_machine.travel("2024-06-15", tick=False)
def test_calendar_window_is_full_rolling_window_when_not_incremental(self) -> None:
# Calendars are full refresh: a backwards lookback plus a forward window, ignoring any cursor.
params = _request_params(FINNHUB_ENDPOINTS["ipo_calendar"], None, "US", False, None)
assert params == {"from": "2023-06-16", "to": "2024-12-12"}
- @freeze_time("2024-06-15")
+ @time_machine.travel("2024-06-15", tick=False)
def test_company_news_window_uses_incremental_cursor(self) -> None:
params = _request_params(FINNHUB_ENDPOINTS["company_news"], "AAPL", "US", True, 1704067200) # 2024-01-01
assert params == {"symbol": "AAPL", "from": "2024-01-01", "to": "2024-06-15"}
- @freeze_time("2024-06-15")
+ @time_machine.travel("2024-06-15", tick=False)
def test_company_news_window_falls_back_to_lookback_without_cursor(self) -> None:
params = _request_params(FINNHUB_ENDPOINTS["company_news"], "AAPL", "US", True, None)
assert params == {"symbol": "AAPL", "from": "2023-06-16", "to": "2024-06-15"}
class TestWindow:
- @freeze_time("2024-06-15")
+ @time_machine.travel("2024-06-15", tick=False)
def test_forward_days_extends_into_future(self) -> None:
window = _window(FINNHUB_ENDPOINTS["earnings_calendar"], None)
assert window.start == "2023-06-16"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py
index df701658766d..e1293959b8d1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -189,7 +189,7 @@ class TestDateWindow:
assert "from" not in params[0]
assert "to" not in params[0]
- @freeze_time("2026-06-15T23:30:00Z")
+ @time_machine.travel("2026-06-15T23:30:00Z", tick=False)
@mock.patch(SESSION_PATCH)
def test_transactions_always_sends_the_required_window(self, MockSession: mock.MagicMock) -> None:
# /transactions documents `from`/`to` as required, so every full refresh sends the whole
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py
index b06fc7f0c8c0..95f451b096da 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py
@@ -4,7 +4,7 @@ from datetime import date, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import urllib3
@@ -372,7 +372,7 @@ class TestNormalizeReportColumn:
class TestGetReportRows:
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.REPORT_REQUEST_INTERVAL_SECONDS", 0)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_incremental_windows_start_one_window_behind_watermark_and_rows_are_normalized(self, mock_session):
@@ -450,7 +450,7 @@ class TestGetReportRows:
"2024-03-15",
]
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.REPORT_REQUEST_INTERVAL_SECONDS", 0)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_conversations_report_uses_weekly_windows_and_keeps_the_natural_key(self, mock_session):
@@ -528,7 +528,7 @@ class TestGetReportRows:
"2024-03-15",
]
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_first_sync_starts_at_the_backfill_horizon(self, mock_session):
mock_session.return_value.post.side_effect = [
@@ -547,7 +547,7 @@ class TestGetReportRows:
assert payload["startAt"] == horizon.isoformat()
assert payload["endAt"] == (horizon + timedelta(days=config.report_window_days - 1)).isoformat()
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.REPORT_REQUEST_INTERVAL_SECONDS", 0)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_resume_state_restarts_at_the_saved_window_and_supersedes_the_watermark(self, mock_session):
@@ -583,7 +583,7 @@ class TestGetReportRows:
"2024-03-15",
]
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_empty_report_body_yields_no_rows_and_advances(self, mock_session):
# A window with no data returns an empty body; urllib3 closes the stream on
@@ -596,7 +596,7 @@ class TestGetReportRows:
assert batches == []
assert manager.save_state.call_args.args[0].last_report_window_end == "2024-03-15"
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_row_ids_are_deterministic_across_syncs(self, mock_session):
csv_text = "Timestamp,Conversation ID\n2024-03-15T01:00:00.000Z,conv-1\n"
@@ -613,7 +613,7 @@ class TestGetReportRows:
# Re-read windows must merge onto the previous sync's rows.
assert row_ids[0] == row_ids[1]
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.MAX_RETRY_ATTEMPTS", 1)
@mock.patch(f"{_MODULE}.make_tracked_session")
@pytest.mark.parametrize(
@@ -634,7 +634,7 @@ class TestGetReportRows:
# A failed window is not recorded as processed.
manager.save_state.assert_not_called()
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_large_report_windows_are_chunked(self, mock_session):
csv_text = (
@@ -649,7 +649,7 @@ class TestGetReportRows:
assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.REPORT_ROW_WARNING_THRESHOLD", 2)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_windows_near_the_report_row_cap_log_a_truncation_warning(self, mock_session):
@@ -665,7 +665,7 @@ class TestGetReportRows:
logger.warning.assert_called_once()
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_blank_lines_before_the_header_do_not_erase_the_columns(self, mock_session):
mock_session.return_value.post.side_effect = [
@@ -678,7 +678,7 @@ class TestGetReportRows:
flat = [row for batch in batches for row in batch]
assert [(row["timestamp"], row["contact_id"]) for row in flat] == [("2024-03-15T09:00:00.000Z", "ct-1")]
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@pytest.mark.parametrize(
"endpoint,body",
[
@@ -697,7 +697,7 @@ class TestGetReportRows:
assert mock_session.return_value.post.call_count == 1
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@pytest.mark.parametrize(
"body",
[
@@ -719,7 +719,7 @@ class TestGetReportRows:
assert mock_session.return_value.post.call_count == 5
manager.save_state.assert_not_called()
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch("time.sleep")
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_an_error_body_in_place_of_the_report_recovers_on_the_next_request(self, mock_session, _sleep):
@@ -735,7 +735,7 @@ class TestGetReportRows:
assert [(row["timestamp"], row["contact_id"]) for row in flat] == [("2024-03-15T09:00:00.000Z", "ct-1")]
manager.save_state.assert_called_once()
- @freeze_time("2024-03-15T10:00:00Z")
+ @time_machine.travel("2024-03-15T10:00:00Z", tick=False)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_a_whitespace_only_body_is_treated_as_an_empty_window(self, mock_session):
mock_session.return_value.post.side_effect = [_csv_response("\r\n")]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.py
index d87cd56c3bb4..9622afde218f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -35,12 +35,12 @@ class TestFormatFromValue:
]
)
def test_format(self, _name: str, value: Any, expected: str | None) -> None:
- with freeze_time("2026-06-01T00:00:00Z"):
+ with time_machine.travel("2026-06-01T00:00:00Z", tick=False):
assert _format_from_value(value) == expected
def test_future_value_capped_to_now(self) -> None:
# A future cursor would filter out every article; capping keeps the request a valid no-op.
- with freeze_time("2026-06-01T12:00:00Z"):
+ with time_machine.travel("2026-06-01T12:00:00Z", tick=False):
assert _format_from_value(datetime(2099, 1, 1, tzinfo=UTC)) == "2026-06-01T12:00:00Z"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
index 83d29db618fa..ed2bf41dd559 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
@@ -6,7 +6,7 @@ import collections.abc
from types import SimpleNamespace
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from django.core.cache import cache
@@ -1553,7 +1553,7 @@ class TestGoogleAdsQueryConstruction:
def test_established_cursor_drains_in_bounded_windows(self):
# An established cursor on a report table is drained in bounded date windows, not the
# open-ended `< 2100` scan that re-extracted the whole backlog every run and OOM-spiralled.
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
response, queries = self._run_source(
self._stats_table(),
should_use_incremental_field=True,
@@ -1573,7 +1573,7 @@ class TestGoogleAdsQueryConstruction:
def test_lookback_overlap_cannot_consume_a_whole_run(self):
# Spending the whole budget on lookback overlap leaves the cursor unmoved, so the next run
# repeats it and a schema behind by more than its lookback never advances.
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
# A budget of zero: the overlap alone would end the run before any new ground.
with mock.patch(f"{self._MODULE}.GOOGLE_ADS_MAX_DRAIN_SECONDS", 0):
_response, queries = self._run_source(
@@ -1615,7 +1615,7 @@ class TestGoogleAdsQueryConstruction:
data_past_gap = cursor + dt.timedelta(days=w * 22) # 2026-06-04, after a run of empty windows
# One second per window drained against a two-second budget: it is spent long before the
# walk reaches the data, so only refusing to arm on the straddle keeps the run going.
- with freeze_time("2026-12-31"):
+ with time_machine.travel("2026-12-31", tick=False):
with mock.patch(f"{self._MODULE}.GOOGLE_ADS_MAX_DRAIN_SECONDS", 2):
_response, queries = self._run_source(
self._stats_table(),
@@ -1638,7 +1638,7 @@ class TestGoogleAdsQueryConstruction:
],
)
def test_drain_starts_at_the_schema_history_start(self, history_start, expected_start: str) -> None:
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
self._stats_table(),
should_use_incremental_field=True,
@@ -1673,7 +1673,7 @@ class TestGoogleAdsQueryConstruction:
def test_a_stated_start_date_is_clamped_to_the_span_that_holds_rows(
self, requested: str, earliest_date: str | None, expected: str
) -> None:
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
self._stats_table(),
should_use_incremental_field=True,
@@ -1694,7 +1694,7 @@ class TestGoogleAdsQueryConstruction:
# Validation rejects these at setup, so reaching the sync means a value stored before that
# check existed. Failing the sync over it is worse than importing the range this source
# would have had without the field.
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
self._stats_table(),
should_use_incremental_field=True,
@@ -1715,7 +1715,7 @@ class TestGoogleAdsQueryConstruction:
) -> None:
# A schema that predates the recorded range reads unbounded: one request locates the start,
# and an account holding nothing has no range to walk.
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
self._stats_table(),
should_use_incremental_field=True,
@@ -1739,7 +1739,7 @@ class TestGoogleAdsQueryConstruction:
table = self._stats_table()
table.extra_where = "metrics.impressions > 0"
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
table,
should_use_incremental_field=True,
@@ -1760,7 +1760,7 @@ class TestGoogleAdsQueryConstruction:
# A full-refresh pipeline persists no cursor, so a budgeted windowed drain restarts from
# the same backfill date every run and the refresh replaces the whole table with that same
# first slice of history. The run must stay a single open-ended scan over the full range.
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
self._stats_table(),
should_use_incremental_field=False,
@@ -1782,7 +1782,7 @@ class TestGoogleAdsQueryConstruction:
(cursor + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS * i)).isoformat(): 1 for i in range(40)
}
# One second of drain per window, so an N-second budget buys N windows.
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
with mock.patch(f"{self._MODULE}.GOOGLE_ADS_MAX_DRAIN_SECONDS", budget):
_response, queries = self._run_source(
self._stats_table(),
@@ -1804,7 +1804,7 @@ class TestGoogleAdsQueryConstruction:
data_window_start = cursor + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS * 3)
window_rows = {data_window_start.isoformat(): 1}
- with freeze_time("2026-07-17"):
+ with time_machine.travel("2026-07-17", tick=False):
_response, queries = self._run_source(
self._stats_table(),
window_rows=window_rows,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.py
index 9734e5559d98..9d15b681b138 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.py
@@ -5,7 +5,7 @@ from typing import Any, cast
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -282,7 +282,7 @@ class TestHttpSampleCapture:
) -> None:
session = _session_with(responses)
with (
- freeze_time(NOW),
+ time_machine.travel(NOW, tick=False),
mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session) as mock_session,
):
list(
@@ -376,7 +376,7 @@ class TestAuditLogRows:
urls = _requested_urls(session)
assert _query_params(urls[2])["from"] == f"log-{AUDIT_LOGS_PAGE_SIZE - 1}"
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_incremental_seeds_from_search(self) -> None:
last_value = datetime(2026, 6, 30, 9, 0, 0, tzinfo=UTC)
manager = _FakeManager()
@@ -394,7 +394,7 @@ class TestAuditLogRows:
assert _query_params(urls[0]) == {"time": str(int(last_value.timestamp()))}
assert [[log["id"] for log in batch] for batch in batches] == [["log-a"], ["log-b"]]
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_incremental_caught_up(self) -> None:
# No log at or after the watermark - the search endpoint 404s.
manager = _FakeManager()
@@ -406,7 +406,7 @@ class TestAuditLogRows:
assert batches == []
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_incremental_watermark_older_than_search_limit_falls_back_to_earliest(self) -> None:
stale_watermark = datetime(2024, 1, 1, tzinfo=UTC)
manager = _FakeManager()
@@ -470,7 +470,7 @@ class TestHistoryRows:
("query_history", "query_history", "/api/v2/history/query"),
]
)
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_incremental_fetches_windows_up_to_now(self, _name: str, endpoint: str, expected_path: str) -> None:
last_value = datetime(2026, 7, 1, 10, 0, 0, tzinfo=UTC)
manager = _FakeManager()
@@ -492,7 +492,7 @@ class TestHistoryRows:
assert batches[0][0]["utc_time"] == datetime(2026, 7, 1, 10, 30, 0, tzinfo=UTC)
assert [state.window_start for state in manager.saved] == [NOW_EPOCH]
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_walks_multiple_windows_and_saves_state_after_each(self) -> None:
# 2.5 windows back from now: expect 3 requests covering contiguous ranges.
last_value = NOW_EPOCH - int(2.5 * 24 * 60 * 60)
@@ -522,7 +522,7 @@ class TestHistoryRows:
NOW_EPOCH,
]
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_full_sync_starts_at_lookback_floor(self) -> None:
manager = _FakeManager()
# Widen the window so the full backfill is a single request.
@@ -533,7 +533,7 @@ class TestHistoryRows:
assert params["start_time"] == str(NOW_EPOCH - MAX_LOOKBACK_DAYS * 24 * 60 * 60)
assert params["end_time"] == str(NOW_EPOCH)
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_incremental_caught_up_makes_no_requests(self) -> None:
manager = _FakeManager()
batches, session = self._get_batches([], manager, db_incremental_field_last_value=NOW)
@@ -541,7 +541,7 @@ class TestHistoryRows:
assert batches == []
assert session.get.call_count == 0
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_resume_starts_at_saved_window(self) -> None:
window_start = NOW_EPOCH - 3600
manager = _FakeManager(resume=HarveyResumeConfig(window_start=window_start))
@@ -549,7 +549,7 @@ class TestHistoryRows:
assert _query_params(_requested_urls(session)[0])["start_time"] == str(window_start)
- @freeze_time(NOW)
+ @time_machine.travel(NOW, tick=False)
def test_incremental_watermark_older_than_api_limit_is_clamped(self) -> None:
manager = _FakeManager()
with mock.patch(f"{HARVEY_MODULE}.HISTORY_WINDOW_SECONDS", 400 * 24 * 60 * 60):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.py b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.py
index fdfcdf44dce8..c3bc8d6f378d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/helicone/tests/test_helicone.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -177,7 +177,7 @@ class TestRequestsRows:
# Helicone's filter AST requires one condition per leaf, wrapped in the table name.
assert body["filter"] == {"request_response_rmt": {"request_created_at": {"gte": "2026-06-01T12:00:00.000Z"}}}
- @freeze_time("2026-06-04 12:00:00")
+ @time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_first_incremental_sync_bounds_backfill_to_lookback(self) -> None:
session = _session_returning([_response(json_body={"data": [], "error": None})])
manager = _no_resume_manager()
@@ -214,7 +214,7 @@ class TestRequestsRows:
class TestSessionsRows:
- @freeze_time("2026-06-04 12:00:00")
+ @time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_sends_required_params_and_pages_until_short_page(self) -> None:
with mock.patch(f"{MODULE}.SESSIONS_PAGE_SIZE", 2):
session = _session_returning(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py
index 7bc5e3c5721e..a6daf26c25bb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact/tests/test_impact.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -119,26 +119,26 @@ class TestRowsFromResponse:
class TestWindowsForActions:
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_full_refresh_backfills_max_lookback(self) -> None:
windows = _windows_for_actions(False, None)
assert windows[0][0] == datetime(2021, 6, 2, tzinfo=UTC)
assert windows[-1][1] == datetime(2024, 6, 1, tzinfo=UTC)
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_incremental_windows_start_at_last_value(self) -> None:
last_value = datetime(2024, 5, 1, tzinfo=UTC)
windows = _windows_for_actions(True, last_value)
assert windows[0][0] == last_value
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_cursor_older_than_max_lookback_is_clamped(self) -> None:
# Impact rejects a StartDate more than 3 years back, so a stale cursor is clamped rather
# than sent as-is.
windows = _windows_for_actions(True, datetime(2015, 1, 1, tzinfo=UTC))
assert windows[0][0] == datetime(2021, 6, 2, tzinfo=UTC)
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_future_cursor_yields_no_windows(self) -> None:
assert _windows_for_actions(True, datetime(2025, 1, 1, tzinfo=UTC)) == []
@@ -328,7 +328,7 @@ class TestGetRowsSimple:
class TestGetRowsActions:
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_fanout_yields_per_campaign_and_saves_state(self) -> None:
manager = FakeResumableManager()
@@ -360,7 +360,7 @@ class TestGetRowsActions:
assert len(manager.saved) == 2 == len(batches)
assert {s.campaign_id for s in manager.saved} == {10, 20}
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_no_campaigns_yields_nothing(self) -> None:
manager = FakeResumableManager()
with (
@@ -370,7 +370,7 @@ class TestGetRowsActions:
batches = list(get_rows("sid", "token", "Actions", MagicMock(), manager)) # type: ignore[arg-type]
assert batches == []
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_resume_skips_campaigns_before_the_bookmark(self) -> None:
# An incremental cursor collapses the run to a single window, starting exactly at the
# cursor value. Bookmarking campaign 20 (the middle of three) re-fetches it plus
@@ -402,7 +402,7 @@ class TestGetRowsActions:
)
assert seen_campaigns == [20, 30]
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_paired_date_params_sent(self) -> None:
manager = FakeResumableManager()
@@ -502,7 +502,7 @@ class TestGetRowsContractsFanout:
class TestGetRowsActionUpdates:
- @freeze_time("2024-06-01")
+ @time_machine.travel("2024-06-01", tick=False)
def test_sends_start_and_end_date_params(self) -> None:
manager = FakeResumableManager()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/impact_partner/tests/test_impact_partner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/impact_partner/tests/test_impact_partner.py
index 71e7ee49b3a6..ba8b4ae60010 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/impact_partner/tests/test_impact_partner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/impact_partner/tests/test_impact_partner.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -73,20 +73,20 @@ class TestValidateCredentials:
class TestWindowsForActions:
- @freeze_time("2026-06-01")
+ @time_machine.travel("2026-06-01", tick=False)
def test_full_refresh_backfills_max_lookback(self) -> None:
windows = _windows_for_actions(False, None)
assert windows[0][0] == datetime(2023, 6, 2, tzinfo=UTC)
assert windows[-1][1] == datetime(2026, 6, 1, tzinfo=UTC)
- @freeze_time("2026-06-01")
+ @time_machine.travel("2026-06-01", tick=False)
def test_cursor_older_than_max_lookback_is_clamped(self) -> None:
# Impact rejects a start date more than 3 years back, so a stale cursor is clamped
# rather than sent as-is.
windows = _windows_for_actions(True, datetime(2015, 1, 1, tzinfo=UTC))
assert windows[0][0] == datetime(2023, 6, 2, tzinfo=UTC)
- @freeze_time("2026-06-01")
+ @time_machine.travel("2026-06-01", tick=False)
def test_future_cursor_yields_no_windows(self) -> None:
assert _windows_for_actions(True, datetime(2027, 1, 1, tzinfo=UTC)) == []
@@ -162,7 +162,7 @@ class TestGetRowsSimple:
class TestGetRowsActions:
- @freeze_time("2026-06-01")
+ @time_machine.travel("2026-06-01", tick=False)
def test_windows_walked_with_paired_date_params_and_no_campaign_filter(self) -> None:
manager = FakeResumableManager()
seen_params: list[dict[str, Any]] = []
@@ -199,7 +199,7 @@ class TestGetRowsActions:
# One save per page, each bookmarking its window.
assert [(s.window_start is not None, s.page) for s in manager.saved] == [(True, 1), (True, 1)]
- @freeze_time("2026-06-01")
+ @time_machine.travel("2026-06-01", tick=False)
def test_resume_skips_earlier_windows_and_starts_at_saved_page(self) -> None:
# Recompute the window grid the run will see, then bookmark the second window at page 2.
cursor = datetime(2026, 4, 2, tzinfo=UTC)
@@ -232,7 +232,7 @@ class TestGetRowsActions:
# Only the bookmarked window is fetched, from its saved page onward.
assert seen == [(impact_partner._format_datetime(windows[1][0]), 2)]
- @freeze_time("2026-06-01")
+ @time_machine.travel("2026-06-01", tick=False)
def test_stale_bookmark_restarts_from_the_first_window(self) -> None:
manager = FakeResumableManager(
state=ImpactPartnerResumeConfig(page=5, window_start="2020-01-01T00:00:00+00:00")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
index 1cff174b7948..53d57af3e3a4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
@@ -2,7 +2,7 @@ import json
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -62,7 +62,7 @@ def _run_rows(
class TestEventWindow:
- @freeze_time("2026-07-14T12:00:00Z")
+ @time_machine.travel("2026-07-14T12:00:00Z", tick=False)
def test_first_sync_backfills_the_max_retention_window(self) -> None:
# received_after defaults to only 1 hour ago server-side, so leaving it off a first sync
# would silently drop everything older than an hour.
@@ -76,12 +76,12 @@ class TestEventWindow:
("iso_string_z", "2026-07-10T08:30:00.500Z", "2026-07-10T08:30:00.500Z"),
]
)
- @freeze_time("2026-07-14T12:00:00Z")
+ @time_machine.travel("2026-07-14T12:00:00Z", tick=False)
def test_incremental_run_advances_from_the_watermark(self, _name: str, value: Any, expected_after: str) -> None:
window = _event_window(should_use_incremental_field=True, db_incremental_field_last_value=value)
assert window.start == expected_after
- @freeze_time("2026-07-14T12:00:00Z")
+ @time_machine.travel("2026-07-14T12:00:00Z", tick=False)
def test_future_watermark_is_clamped_to_now(self) -> None:
# A future-dated watermark would produce an inverted window that returns nothing forever.
window = _event_window(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
index 6b1315d05083..d7c9a9f6c870 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
@@ -4,7 +4,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -135,8 +135,12 @@ def _query(url: str) -> dict[str, list[str]]:
return parse_qs(urlparse(url).query)
-@freeze_time("2026-01-10T00:00:00Z")
class TestEventRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-01-10T00:00:00Z", tick=False):
+ yield
+
NOW_MS = 1768003200000
def test_incremental_run_chunks_from_watermark(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.py
index 2e5571efb62b..70498c3203c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jumpcloud/tests/test_jumpcloud.py
@@ -2,7 +2,7 @@ import json
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -284,7 +284,7 @@ class TestEventRows:
rows.extend(page)
return rows, request_bodies
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_first_sync_queries_the_90_day_retention_window(self, monkeypatch: Any) -> None:
manager = _FakeResumableManager()
_, bodies = self._collect(manager, monkeypatch, [([{"id": "e1"}], None)])
@@ -297,7 +297,7 @@ class TestEventRows:
}
]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_incremental_sync_starts_at_the_watermark(self, monkeypatch: Any) -> None:
from datetime import UTC, datetime
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py
index e005538c689f..a3c95adeeddf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -108,12 +108,12 @@ class TestFormatIncrementalValue:
class TestClampFutureValue:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_clamped_to_now(self) -> None:
clamped = _clamp_future_value_to_now(datetime(2027, 1, 1, tzinfo=UTC))
assert clamped == datetime(2026, 6, 15, 12, 0, 0, tzinfo=UTC)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_untouched(self) -> None:
past = datetime(2026, 1, 1, tzinfo=UTC)
assert _clamp_future_value_to_now(past) == past
@@ -259,7 +259,7 @@ class TestIncrementalFilter:
assert params[0] == {"page": 1, "limit": PAGE_SIZE}
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@patch(CLIENT_SESSION_PATCH)
def test_future_cursor_clamped(self, MockSession: MagicMock) -> None:
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
index 4ef47e98164a..61bb2da5725e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -118,7 +118,7 @@ class TestBuildInitialParams:
assert "+00:00" not in params["filter"]
assert params["filter"].endswith("Z)")
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_cursor_is_clamped_to_now(self) -> None:
# A future-dated cursor would otherwise build greater-than(datetime,<future>),
# which Klaviyo rejects with a 400 and wedges every subsequent sync.
@@ -131,7 +131,7 @@ class TestBuildInitialParams:
)
assert params["filter"] == "greater-than(datetime,2026-06-15T12:00:00.000Z)"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_cursor_is_not_modified(self) -> None:
config = KLAVIYO_ENDPOINTS["events"]
params = _build_initial_params(
@@ -166,7 +166,7 @@ class TestBuildInitialParams:
)
assert "filter" not in params
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_lookback_applies_after_future_clamp(self) -> None:
# Clamping after the lookback would erase the overlap window for a future-dated cursor.
config = KLAVIYO_ENDPOINTS["list_profiles"]
@@ -180,28 +180,28 @@ class TestBuildInitialParams:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42, tzinfo=UTC)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_naive_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_is_unchanged(self) -> None:
value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_date_is_clamped(self) -> None:
assert _clamp_future_value_to_now(date(2027, 2, 5)) == date(2026, 6, 15)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_date_is_unchanged(self) -> None:
assert _clamp_future_value_to_now(date(2026, 3, 4)) == date(2026, 3, 4)
@@ -1104,7 +1104,7 @@ class TestValuesReports:
class TestReportVariants:
# Monday 03:30 UTC, which is still Sunday evening in the account's timezone. A window computed in
# UTC would open a week later and end seven hours ahead of the account's clock.
- @freeze_time("2026-09-14T03:30:00Z")
+ @time_machine.travel("2026-09-14T03:30:00Z", tick=False)
def test_series_report_carries_interval_and_expands_each_bucket_into_a_row(self, monkeypatch: Any) -> None:
# Series reports return each statistic as an array aligned to a top-level date_times list;
# keeping the arrays nested would leave the table unqueryable and collapse the weekly rows.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py
index 706159285e5d..65f6bc80bffc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -52,7 +52,7 @@ class TestBuildBody:
class TestResolveWindow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_incremental_starts_at_watermark(self) -> None:
start, end = _resolve_window(
should_use_incremental_field=True,
@@ -62,7 +62,7 @@ class TestResolveWindow:
assert start == "2026-06-10T08:00:00Z"
assert end == "2026-06-15T12:00:00Z"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_full_refresh_walks_back_lookback_days(self) -> None:
start, end = _resolve_window(
should_use_incremental_field=False,
@@ -72,7 +72,7 @@ class TestResolveWindow:
assert start == "2026-06-08T12:00:00Z"
assert end == "2026-06-15T12:00:00Z"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_watermark_clamped_to_now(self) -> None:
# A future-dated cursor would otherwise produce start > end, wedging every later sync.
start, _ = _resolve_window(
@@ -90,7 +90,7 @@ class TestClampFutureValue:
("future_datetime_clamped", datetime(2027, 1, 1, tzinfo=UTC), True),
]
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_clamp(self, _name: str, value: datetime, should_clamp: bool) -> None:
result = _clamp_future_value_to_now(value)
if should_clamp:
@@ -146,7 +146,7 @@ class TestGetRowsPagination:
saved = manager.save_state.call_args.args[0]
assert saved.offset == MAX_PAGE_SIZE
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@patch.object(kong_konnect, "make_tracked_session")
@patch.object(kong_konnect, "_fetch_page")
def test_resume_reuses_saved_window_not_recomputed(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py
index d483f9152f16..9611f0fce8f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py
@@ -1,7 +1,7 @@
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.kubecost import (
@@ -159,8 +159,12 @@ class TestValidateCredentials:
assert error is None
-@freeze_time("2026-07-15T10:00:00Z")
class TestGetRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-15T10:00:00Z", tick=False):
+ yield
+
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_flattens_result_sets_and_injects_key_and_window(self, mock_session):
mock_session.return_value.get.return_value = _response(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py
index 4aa4e7252693..1a2cdbc7bd7b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lacework/tests/test_lacework.py
@@ -3,7 +3,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -187,7 +187,7 @@ class TestValidateCredentials:
class TestGetRowsWindowing:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_post_search_slices_watermark_to_now_into_windows(self) -> None:
# vulnerabilities_hosts uses 1-day windows; a watermark 2.5 days back must produce three
# consecutive windows ending exactly at now — a slicing bug would skip or overlap data.
@@ -215,7 +215,7 @@ class TestGetRowsWindowing:
]
assert all(url.endswith("/api/v2/Vulnerabilities/Hosts/search") for _m, url, _b, _h in session.data_calls)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_get_endpoint_sends_time_window_as_query_params(self) -> None:
session = _FakeSession([_FakeResponse(200, {"data": [{"alertId": 1}], "paging": {}})])
rows = _collect_rows(
@@ -236,7 +236,7 @@ class TestGetRowsWindowing:
"endTime": ["2026-06-15T12:00:00.000Z"],
}
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_compliance_search_includes_dataset(self) -> None:
session = _FakeSession([_FakeResponse(200, {"data": [], "paging": {}})])
_collect_rows(
@@ -250,7 +250,7 @@ class TestGetRowsWindowing:
assert url.endswith("/api/v2/Configs/ComplianceEvaluations/search")
assert body is not None and body["dataset"] == "AwsCompliance"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_full_refresh_uses_default_lookback(self) -> None:
# agent_info: 7-day lookback with 7-day windows -> exactly one request window.
session = _FakeSession([_FakeResponse(200, {"data": [{"mid": 1}], "paging": {}})])
@@ -264,7 +264,7 @@ class TestGetRowsWindowing:
"endTime": "2026-06-15T12:00:00.000Z",
}
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_watermark_yields_nothing(self) -> None:
session = _FakeSession([])
rows = _collect_rows(
@@ -279,7 +279,7 @@ class TestGetRowsWindowing:
class TestGetRowsPagination:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_follows_next_page_and_checkpoints_after_yield(self) -> None:
next_url = "https://mycompany.lacework.net/api/v2/Alerts/AbCdEf123"
session = _FakeSession(
@@ -308,7 +308,7 @@ class TestGetRowsPagination:
)
]
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_next_page_on_foreign_host_is_not_followed(self) -> None:
session = _FakeSession(
[
@@ -328,7 +328,7 @@ class TestGetRowsPagination:
assert [r["alertId"] for r in rows] == [1]
assert len(session.data_calls) == 1
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_resume_continues_from_saved_window_and_page(self) -> None:
resume_url = "https://mycompany.lacework.net/api/v2/Alerts/ResumeToken"
manager = _FakeResumableManager(
@@ -370,7 +370,7 @@ class TestGetRowsPagination:
)
]
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_resume_url_on_foreign_host_is_ignored(self) -> None:
manager = _FakeResumableManager(
LaceworkResumeConfig(
@@ -393,7 +393,7 @@ class TestGetRowsPagination:
assert method == "GET"
assert urlparse(url).hostname == "mycompany.lacework.net"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_204_no_data_yields_nothing(self) -> None:
session = _FakeSession([_FakeResponse(204, None)])
rows = _collect_rows(
@@ -407,7 +407,7 @@ class TestGetRowsPagination:
class TestAuth:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_token_exchanged_once_and_sent_as_bearer(self) -> None:
next_url = "https://mycompany.lacework.net/api/v2/Alerts/AbCdEf123"
session = _FakeSession(
@@ -427,7 +427,7 @@ class TestAuth:
for _method, _url, _body, headers in session.data_calls:
assert headers["Authorization"] == "Bearer tok-123"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_token_exchange_is_excluded_from_sample_capture(self) -> None:
# The X-LW-UAKS request header and the response's generic `token` field are not caught by
# the name-based sample scrubbers, so the auth session must opt out of capture and redact
@@ -458,7 +458,7 @@ class TestAuth:
assert mock_make.call_args.kwargs.get("capture") is False
assert mock_make.call_args.kwargs.get("redact_values") == ("secret",)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_retries_on_429_using_retry_after(self) -> None:
session = _FakeSession(
[
@@ -476,7 +476,7 @@ class TestAuth:
assert [r["alertId"] for r in rows] == [1]
assert len(session.data_calls) == 2
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_result_set_row_cap_is_logged(self) -> None:
session = _FakeSession(
[_FakeResponse(200, {"data": [{"alertId": 1}], "paging": {"rows": 5000, "totalRows": 500_000}})]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py
index 959d45319c62..64736b96e814 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -150,11 +150,11 @@ class TestToDateStr:
class TestDefaultStartDate:
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_uses_config_start_date_floored(self) -> None:
assert _default_start_date("2023-01-01T12:00:00Z") == "2023-01-01"
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_defaults_to_lookback_window_when_blank(self) -> None:
assert _default_start_date("") == "2025-07-02"
@@ -208,7 +208,7 @@ class TestFanOut:
return _response([_item(i, "accounts") for i in ids], next_url=next_url)
@mock.patch(CLIENT_SESSION_PATCH)
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_iterates_every_account_and_injects_account_id(self, MockSession) -> None:
session = MockSession.return_value
urls, params = _wire(
@@ -234,7 +234,7 @@ class TestFanOut:
assert lead_params["end_date"] == "2026-07-02"
@mock.patch(CLIENT_SESSION_PATCH)
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_incremental_watermark_sets_start_date(self, MockSession) -> None:
session = MockSession.return_value
_, params = _wire(session, [self._accounts_response("1"), _response([_item("100", "leads")])])
@@ -402,7 +402,7 @@ class TestUnifiedRequests:
assert len(requests) == 1
@mock.patch(CLIENT_SESSION_PATCH)
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_leads_fan_out_hits_visitor_companies_with_account_id_query(self, MockSession) -> None:
session = MockSession.return_value
requests = _wire_full(
@@ -422,7 +422,7 @@ class TestUnifiedRequests:
assert company_reqs[0]["params"]["end_date"] == "2026-07-02"
@mock.patch(CLIENT_SESSION_PATCH)
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_visits_fan_out_posts_web_visits_with_date_body(self, MockSession) -> None:
session = MockSession.return_value
requests = _wire_full(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py
index cbe80493517e..d1b672f1e8c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -104,18 +104,18 @@ class TestFormatIncrementalValue:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, tzinfo=UTC)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_unchanged(self) -> None:
value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_date_clamped(self) -> None:
assert _clamp_future_value_to_now(date(2027, 2, 5)) == date(2026, 6, 15)
@@ -163,7 +163,7 @@ class TestRequestParams:
assert params[0]["minDate"] == "2026-05-11T00:00:00Z"
assert params[0]["version"] == "v2"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_activities_first_sync_uses_lookback_window(self, MockSession) -> None:
# No stored watermark -> bound the first sync by the configured lookback instead of full history.
@@ -172,7 +172,7 @@ class TestRequestParams:
_rows(_source("activities", should_use_incremental_field=True, db_incremental_field_last_value=None))
assert params[0]["minDate"] == "2025-06-15T12:00:00Z"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_activities_future_watermark_clamped(self, MockSession) -> None:
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
index d6e66825b0bd..6ba43499c334 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
@@ -4,7 +4,7 @@ from typing import Any
from urllib.parse import urlencode
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from unittest.mock import MagicMock
@@ -102,7 +102,7 @@ class TestToDatetime:
class TestActivityDateWindow:
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_first_sync_uses_lookback_window(self) -> None:
window = _activity_date_window(
should_use_incremental_field=True, db_incremental_field_last_value=None, lookback_days=30
@@ -110,7 +110,7 @@ class TestActivityDateWindow:
assert window.end - window.start == 30 * 24 * 60 * 60
assert window.end == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_full_refresh_uses_lookback_window(self) -> None:
# Activity requires a date window even without an incremental cursor, so a full refresh still
# falls back to the lookback window rather than omitting the bounds.
@@ -119,7 +119,7 @@ class TestActivityDateWindow:
)
assert window.end - window.start == 30 * 24 * 60 * 60
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_incremental_starts_from_last_value(self) -> None:
last = datetime(2026, 6, 20, 12, 0, 0, tzinfo=UTC)
window = _activity_date_window(
@@ -128,7 +128,7 @@ class TestActivityDateWindow:
assert window.start == int(last.timestamp())
assert window.end == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_future_cursor_is_clamped_below_date_to(self) -> None:
# A future-dated cursor would make date_from >= date_to and 422 the request; it must be clamped.
future = datetime(2027, 1, 1, tzinfo=UTC)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
index bd5eed87fc03..50fa56a33145 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
@@ -3,7 +3,7 @@ import datetime as dt
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from django.db import OperationalError
@@ -1476,7 +1476,6 @@ class TestRetryableErrors:
assert not any(pattern in str(exc_info.value) for pattern in patterns)
-@freeze_time("2026-06-16")
class TestTimeRangeClamping:
"""Meta rejects insights time ranges starting beyond ~37 months (error 3018).
@@ -1487,6 +1486,11 @@ class TestTimeRangeClamping:
``dt.date.today()`` read inside ``get_rows`` always agree (no midnight race).
"""
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-06-16", tick=False):
+ yield
+
def _capture_time_range(self, monkeypatch, **source_kwargs: Any) -> dict | None:
integration = mock.MagicMock()
integration.access_token = "token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.py
index 592306bafc70..67a730dccb85 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -147,7 +147,7 @@ class TestHelpers:
class TestGetRows:
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_single_window_rows_tagged_with_station_and_state_saved_after_yield(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": [{"date": "2026-07-18", "tavg": 20.5}]})
@@ -165,7 +165,7 @@ class TestGetRows:
saved = [call.args[0] for call in manager.save_state.call_args_list]
assert saved == [MeteostatResumeConfig(station_index=0, next_start="2026-07-22")]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_multiple_stations_are_each_queried_across_the_full_range(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": [{"date": "2026-07-18", "tavg": 5.0}]})
@@ -176,7 +176,7 @@ class TestGetRows:
assert [p["station"] for p in params] == ["10637", "71508"]
assert [batch[0]["station_id"] for batch in batches] == ["10637", "71508"]
- @freeze_time("2026-08-15")
+ @time_machine.travel("2026-08-15", tick=False)
def test_long_range_is_chunked_into_contiguous_windows_within_the_vendor_cap(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": []})
@@ -193,7 +193,7 @@ class TestGetRows:
assert date.fromisoformat(current["start"]) == date.fromisoformat(previous["end"]) + timedelta(days=1)
assert date.fromisoformat(params[-1]["end"]) == date(2026, 8, 15)
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_incremental_start_uses_overlap_window(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": []})
@@ -210,7 +210,7 @@ class TestGetRows:
# Re-fetches a 7 day trailing overlap so late corrections get picked up; merge dedupes.
assert params == [{"station": "10637", "start": "2026-07-08", "end": "2026-07-21"}]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_resume_state_skips_completed_stations_and_resumes_the_current_one(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": []})
@@ -227,7 +227,7 @@ class TestGetRows:
with pytest.raises(ValueError, match=NO_STATIONS_ERROR):
_run(DAILY_ENDPOINT, mock.MagicMock(spec=requests.Session), station_ids=" , ")
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_station_count_is_capped_at_runtime(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": []})
@@ -244,7 +244,7 @@ class TestGetRows:
("scientific_includes_units_param", "scientific", True),
]
)
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_units_param_only_sent_for_non_default_unit_system(self, _name, units, expect_param):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"data": []})
@@ -256,7 +256,7 @@ class TestGetRows:
if expect_param:
assert params[0]["units"] == units
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_non_ok_status_raises(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(status=500)
@@ -264,7 +264,7 @@ class TestGetRows:
with pytest.raises(requests.HTTPError):
_run(DAILY_ENDPOINT, session, station_ids="10637", start_date="2026-07-20")
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_start_date_before_floor_is_clamped(self):
# A too-old start_date is re-checked (not just rejected at credential validation) so a
# previously stored configuration can't schedule a runaway backfill either.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py
index 5791ee9be145..d096523a3ded 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, Mock, patch
import requests
@@ -258,7 +258,7 @@ class TestMetronomeSourceResponse:
# An unaligned lower bound asks Metronome for part of a period the table already holds, and
# the partial aggregate that comes back upserts as a second row, because the period start
# is part of the primary key.
- with freeze_time(NOW):
+ with time_machine.travel(NOW, tick=False):
metronome_source(
api_key="tok",
endpoint=endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py
index a0d3595b538a..92b92a498284 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py
@@ -3,7 +3,7 @@ from collections.abc import Iterable
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -131,7 +131,7 @@ SAMPLE_PAYLOAD = [
class TestMicrosoftClaritySource:
- @freeze_time("2026-07-23T12:00:00Z")
+ @time_machine.travel("2026-07-23T12:00:00Z", tick=False)
@mock.patch(SESSION_PATCH)
def test_flattens_every_metric_and_information_row(self, MockSession: Any) -> None:
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py
index 367242d33bbc..6804f2c47f14 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import orjson
@@ -205,11 +205,11 @@ class TestParseRetryAfter:
def test_delta_seconds(self, _name: str, value: Optional[str], expected: Optional[float]) -> None:
assert _parse_retry_after(value) == expected
- @freeze_time("2024-06-04T00:00:00Z")
+ @time_machine.travel("2024-06-04T00:00:00Z", tick=False)
def test_http_date_in_the_future(self) -> None:
assert _parse_retry_after("Tue, 04 Jun 2024 00:00:30 GMT") == 30.0
- @freeze_time("2024-06-04T00:00:00Z")
+ @time_machine.travel("2024-06-04T00:00:00Z", tick=False)
def test_http_date_in_the_past_is_ignored(self) -> None:
assert _parse_retry_after("Tue, 04 Jun 2024 00:00:00 GMT") is None
@@ -584,8 +584,12 @@ class TestSingleRequestEndpoints:
assert list(mp._fetch_annotations("us", "u", "s", "123", LOGGER)) == []
-@freeze_time("2024-06-04")
class TestGetRowsExportWindow:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-06-04", tick=False):
+ yield
+
def _captured_window(self, **kwargs) -> tuple[date, date]:
with patch.object(mp, "_iter_export", return_value=iter([])) as mock_iter:
list(mp.get_rows("us", "u", "s", "123", "export", LOGGER, FakeManager(), **kwargs)) # type: ignore[arg-type]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py
index 3d9dd103a4e0..26b97952054e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/monte_carlo/tests/test_monte_carlo.py
@@ -1,7 +1,8 @@
from datetime import UTC, datetime
from typing import Any
-from freezegun import freeze_time
+import pytest
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -211,8 +212,12 @@ class TestUnpaginatedEndpoint:
assert manager.saved == []
-@freeze_time("2026-07-15T12:00:00Z")
class TestAlertsWindowing:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-15T12:00:00Z", tick=False):
+ yield
+
def test_first_sync_walks_year_of_30_day_windows(self) -> None:
empty = _relay_page("getAlerts", [], None)
responses = [empty] * 13 # 365 days / 30-day windows
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.py
index 87994144d3f1..cbff3a53fddc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.py
@@ -1,7 +1,7 @@
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -147,7 +147,7 @@ class TestGet:
class TestHolidayYears:
- @freeze_time("2026-06-15")
+ @time_machine.travel("2026-06-15", tick=False)
def test_spans_the_configured_backfill_and_forward_window(self) -> None:
years = _holiday_years()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.py
index 27578e4d416d..dcca8eaa70f7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/tests/test_new_relic.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -209,8 +209,12 @@ class TestFetchEventWindow:
logger.warning.assert_called_once()
-@freeze_time("2026-01-02 12:00:00")
class TestGetEventRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-01-02 12:00:00", tick=False):
+ yield
+
def _now_ms(self) -> int:
return int(datetime(2026, 1, 2, 12, tzinfo=UTC).timestamp() * 1000)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.py b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.py
index 600195e4088c..c12507bf41b4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/new_york_times/tests/test_new_york_times.py
@@ -1,7 +1,7 @@
from datetime import UTC, date, datetime
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -53,18 +53,18 @@ class TestFormatBeginDate:
class TestResolveBeginDate:
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_uses_watermark_when_incremental(self) -> None:
config = NEW_YORK_TIMES_ENDPOINTS["article_search"]
assert _resolve_begin_date(config, True, datetime(2026, 6, 1, tzinfo=UTC)) == "20260601"
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_falls_back_to_lookback_without_watermark(self) -> None:
# First incremental sync (no watermark) must window to the lookback range, not all of history.
config = NEW_YORK_TIMES_ENDPOINTS["article_search"]
assert _resolve_begin_date(config, True, None) == "20260602"
- @freeze_time("2026-07-02")
+ @time_machine.travel("2026-07-02", tick=False)
def test_full_refresh_uses_lookback(self) -> None:
config = NEW_YORK_TIMES_ENDPOINTS["article_search"]
assert _resolve_begin_date(config, False, None) == "20260602"
@@ -165,7 +165,7 @@ class TestGetRowsArticleSearch:
with (
patch.object(new_york_times, "make_tracked_session", return_value=session),
patch.object(new_york_times.time, "sleep"),
- freeze_time("2026-07-02"),
+ time_machine.travel("2026-07-02", tick=False),
):
batches = list(
get_rows("KEY", "article_search", MagicMock(), manager) # type: ignore[arg-type]
@@ -183,7 +183,7 @@ class TestGetRowsArticleSearch:
with (
patch.object(new_york_times, "make_tracked_session", return_value=session),
patch.object(new_york_times.time, "sleep"),
- freeze_time("2026-07-02"),
+ time_machine.travel("2026-07-02", tick=False),
):
batches = list(
get_rows("KEY", "article_search", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]
@@ -198,7 +198,7 @@ class TestGetRowsArticleSearch:
with (
patch.object(new_york_times, "make_tracked_session", return_value=session),
patch.object(new_york_times.time, "sleep"),
- freeze_time("2026-07-02"),
+ time_machine.travel("2026-07-02", tick=False),
):
batches = list(
get_rows("KEY", "article_search", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]
@@ -225,7 +225,7 @@ class TestGetRowsArticleSearch:
with (
patch.object(new_york_times, "make_tracked_session", return_value=session),
patch.object(new_york_times.time, "sleep"),
- freeze_time("2026-07-02"),
+ time_machine.travel("2026-07-02", tick=False),
):
list(
get_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.py
index 3f945af4e8e3..d1278ca4e841 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -213,7 +213,7 @@ class TestIncrementalFromDate:
assert params[0]["from_date"] == "2024-03-04"
@parameterized.expand([("archive",), ("crypto",)])
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_first_sync_applies_lookback_floor(self, endpoint: str, MockSession: mock.MagicMock) -> None:
# Without a watermark the first sync must floor at the trailing lookback window instead of
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.py
index 0e716e8304ad..093e579cbab6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nocrm/tests/test_nocrm.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -92,13 +92,13 @@ class TestFormatUpdatedAfter:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, 21, 46, 42, tzinfo=UTC)) == datetime(
2026, 6, 15, 12, 0, 0, tzinfo=UTC
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_is_unchanged(self) -> None:
value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py
index 0aa053a9b9b7..a14d822d0c00 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.npm_registry import (
@@ -119,7 +119,7 @@ class TestFirstLicense:
class TestGetRowsDownloads:
- @freeze_time("2016-08-01")
+ @time_machine.travel("2016-08-01", tick=False)
def test_windows_date_range_into_chunks(self):
# First 540-day window from EARLIEST_DOWNLOAD_DATE runs 2015-01-10..2016-07-02; the second
# window then starts 2016-07-03 and is clamped to "today" (frozen at 2016-08-01).
@@ -152,7 +152,7 @@ class TestGetRowsDownloads:
]
assert fetch.call_count == 2
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_incremental_starts_the_day_after_the_watermark(self):
with mock.patch(f"{_MODULE}._fetch_json", return_value={"downloads": []}) as fetch:
list(
@@ -167,7 +167,7 @@ class TestGetRowsDownloads:
)
assert "2024-02-02:2024-02-15" in fetch.call_args_list[0].args[1]
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_resume_starts_from_saved_package_and_window(self):
with mock.patch(f"{_MODULE}._fetch_json", return_value={"downloads": []}) as fetch:
list(
@@ -186,7 +186,7 @@ class TestGetRowsDownloads:
assert "lodash" in url
assert "2024-02-10:2024-02-15" in url
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_missing_package_is_skipped_without_raising(self):
with mock.patch(f"{_MODULE}._fetch_json", return_value=None) as fetch:
batches = list(
@@ -200,7 +200,7 @@ class TestGetRowsDownloads:
assert batches == []
assert fetch.call_count == 1
- @freeze_time("2024-02-15")
+ @time_machine.travel("2024-02-15", tick=False)
def test_saves_state_after_each_window_and_advances_package_on_completion(self):
manager = _manager()
with mock.patch(f"{_MODULE}._fetch_json", return_value={"downloads": [{"day": "2015-01-10", "downloads": 1}]}):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password.py
index 289f98843243..79d30621f665 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password.py
@@ -4,7 +4,7 @@ from datetime import UTC, date, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from unittest.mock import MagicMock
@@ -125,7 +125,7 @@ class TestInitialStartTime:
]
)
def test_initial_start_time(self, _name: str, use_incremental: bool, watermark: Any, expected: str) -> None:
- with freeze_time("2026-07-15T12:00:00Z"):
+ with time_machine.travel("2026-07-15T12:00:00Z", tick=False):
assert _initial_start_time(use_incremental, watermark) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py
index 76a16c794055..40ba98e0c8ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py
@@ -4,7 +4,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -419,7 +419,7 @@ class TestArchiveWindowing:
)
return batches, session
- @freeze_time("2026-03-01")
+ @time_machine.travel("2026-03-01", tick=False)
def test_covers_every_location_within_a_window_before_advancing(self) -> None:
manager = FakeResumeManager()
responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(4)]
@@ -441,7 +441,7 @@ class TestArchiveWindowing:
# One batch per window, holding both locations' rows.
assert [len(batch) for batch in batches] == [2, 2]
- @freeze_time("2026-03-01")
+ @time_machine.travel("2026-03-01", tick=False)
def test_windows_are_contiguous_and_never_overlap(self) -> None:
manager = FakeResumeManager()
responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(4)]
@@ -456,7 +456,7 @@ class TestArchiveWindowing:
assert (first[1] - first[0]).days == ARCHIVE_WINDOW_DAYS - 1
assert (second[0] - first[1]).days == 1
- @freeze_time("2026-03-01")
+ @time_machine.travel("2026-03-01", tick=False)
def test_checkpoints_after_each_window_and_clears_on_completion(self) -> None:
manager = FakeResumeManager()
responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(4)]
@@ -466,7 +466,7 @@ class TestArchiveWindowing:
assert [state.next_start_date for state in manager.saved] == ["2026-02-01", "2026-03-02"]
assert manager.cleared is True
- @freeze_time("2026-03-01")
+ @time_machine.travel("2026-03-01", tick=False)
def test_resumes_from_the_saved_window(self) -> None:
manager = FakeResumeManager(OpenMeteoResumeConfig(next_start_date="2026-02-01"))
responses = [_response(200, _hourly_body(["2026-02-01T00:00"], temperature_2m=[1.0])) for _ in range(2)]
@@ -475,7 +475,7 @@ class TestArchiveWindowing:
assert [_query(url)["start_date"][0] for url in _requested_urls(session)] == ["2026-02-01", "2026-02-01"]
- @freeze_time("2026-03-01")
+ @time_machine.travel("2026-03-01", tick=False)
def test_makes_no_requests_when_the_watermark_is_already_current(self) -> None:
manager = FakeResumeManager()
session = _fake_session([])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
index 9e8a749df4fc..83097317c088 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
@@ -2,7 +2,7 @@ import json
from datetime import UTC, datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -205,7 +205,7 @@ class TestFanOut:
class TestInsights:
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_incremental_windows_from_watermark_to_today(self, MockSession) -> None:
session = MockSession.return_value
@@ -227,7 +227,7 @@ class TestInsights:
assert "campaign.spend" in sent["fields[]"]
assert "metadata.readable_time" in sent["fields[]"]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_full_refresh_windows_from_product_launch_floor(self, MockSession) -> None:
# Without a watermark we still need a bounded window — the API rejects unbounded/future
@@ -267,7 +267,7 @@ class TestInsights:
assert rows[0]["end_time"] == datetime(2026, 4, 26, tzinfo=UTC)
assert rows[0]["impressions"] == 5
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_checkpoint_pins_the_window_alongside_the_cursor(self, MockSession) -> None:
session = MockSession.return_value
@@ -287,7 +287,7 @@ class TestInsights:
cursor="b1", since="2026-07-01", until="2026-07-21"
)
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_resume_reuses_the_pinned_window_with_the_saved_cursor(self, MockSession) -> None:
# A cursor is only valid for the result set it was issued for — recomputing `until` as a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oura/tests/test_oura.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oura/tests/test_oura.py
index 898b3529052c..2661ec61f7f3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/oura/tests/test_oura.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oura/tests/test_oura.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from unittest.mock import MagicMock, patch
@@ -104,15 +104,15 @@ class TestFormatHelpers:
class TestClamp:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_date_clamped_to_today(self) -> None:
assert _clamp_date_to_today("2099-01-01") == "2026-06-15"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_date_unchanged(self) -> None:
assert _clamp_date_to_today("2021-05-01") == "2021-05-01"
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_clamped_to_now(self) -> None:
assert _clamp_datetime_to_now("2099-01-01T00:00:00+00:00") == "2026-06-15T12:00:00+00:00"
@@ -173,7 +173,7 @@ class TestDateWindowParams:
assert "start_datetime" not in params[0]
@mock.patch(CLIENT_SESSION_PATCH)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_cursor_is_clamped(self, MockSession) -> None:
# A future-dated record could push the cursor past today; Oura 400s when start_date > end_date.
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.py
index 3b747676ba39..265f0a96e02f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/perigon/tests/test_perigon.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -93,7 +93,7 @@ class TestClampFutureValueToNow:
("future_iso_string", "2030-01-01T00:00:00Z", datetime(2026, 6, 15, 12, tzinfo=UTC)),
]
)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_clamp(self, _name: str, value: Any, expected: Any) -> None:
assert _clamp_future_value_to_now(value) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.py
index 49501db1ffa7..6d75b7cfe34a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plivo/tests/test_plivo.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from requests import Response
@@ -107,8 +107,12 @@ class TestBuildWindows:
assert all(we - ws <= timedelta(days=30) for ws, we in windows)
-@freeze_time(FROZEN_NOW)
class TestWindowedEndpoints:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(FROZEN_NOW, tick=False):
+ yield
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_full_refresh_walks_retention_in_30_day_windows(self, MockSession: mock.MagicMock) -> None:
calls = _wire(MockSession.return_value, lambda url, params: _page([], 0))
@@ -218,8 +222,12 @@ class TestWindowedEndpoints:
assert calls[1]["params"]["offset"] == 0
-@freeze_time(FROZEN_NOW)
class TestNonWindowedEndpoints:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(FROZEN_NOW, tick=False):
+ yield
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_recordings_incremental_filters_without_windowing(self, MockSession: mock.MagicMock) -> None:
calls = _wire(MockSession.return_value, lambda url, params: _page([{"recording_id": "r1", "add_time": ""}], 1))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 8985d3785fdb..0a66d3b67085 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -8,7 +8,7 @@ from datetime import UTC, date, datetime, time, timedelta, timezone
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from unittest.mock import MagicMock, patch
@@ -7648,7 +7648,7 @@ class TestDeriveUpperBound:
bounds = [(date(2026, 1, 1), date(2026, 2, 1)), (date(2026, 2, 1), date(2026, 3, 1))]
assert derive_upper_bound(IncrementalFieldType.Date, bounds) == date(2026, 3, 1)
- @freeze_time("2026-04-20T12:00:00Z")
+ @time_machine.travel("2026-04-20T12:00:00Z", tick=False)
def test_uses_now_for_datetime_without_bounds(self):
out = derive_upper_bound(IncrementalFieldType.DateTime, [])
assert out == datetime(2026, 4, 20, 12, 0, 0, tzinfo=UTC)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py
index 353f90777b32..c4b0276e1182 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py
@@ -2,7 +2,8 @@ from collections.abc import Iterable
from datetime import UTC, datetime
from typing import Any, Optional, cast
-from freezegun import freeze_time
+import pytest
+import time_machine
from unittest import mock
import requests
@@ -190,8 +191,12 @@ class TestPowerBiAdminClient:
assert session.get.call_count == 2
-@freeze_time("2026-07-26T12:00:00Z")
class TestActivityEvents:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-26T12:00:00Z", tick=False):
+ yield
+
def test_full_refresh_walks_the_whole_retention_window_one_day_per_request(self) -> None:
session = _session([_response(200, {"activityEventEntities": []}) for _ in range(28)])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py
index 6604b02e2740..291c14a21d9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pylon/tests/test_pylon.py
@@ -3,7 +3,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock
import requests
@@ -259,7 +259,7 @@ class TestFanOutEndpoint:
class TestWindowedIssues:
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_first_sync_walks_lookback_in_30_day_windows(self) -> None:
manager = _no_resume_manager()
fetch = MagicMock(return_value=_page([{"id": "i", "created_at": "2026-01-01T00:00:00Z"}]))
@@ -288,7 +288,7 @@ class TestWindowedIssues:
for earlier, later in zip(windows, windows[1:]):
assert earlier["end_time"] == later["start_time"]
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_incremental_starts_from_watermark(self) -> None:
manager = _no_resume_manager()
fetch = MagicMock(return_value=_page([{"id": "i", "created_at": "2026-06-10T00:00:00Z"}]))
@@ -314,7 +314,7 @@ class TestWindowedIssues:
assert windows[0]["start_time"] == ["2026-06-01T00:00:00Z"]
assert windows[0]["end_time"] == ["2026-06-23T00:00:00Z"]
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_future_watermark_is_a_no_op(self) -> None:
manager = _no_resume_manager()
fetch = MagicMock(return_value=_page([]))
@@ -335,7 +335,7 @@ class TestWindowedIssues:
assert fetch.call_count == 0
- @freeze_time("2026-06-23T00:00:00Z")
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_resumes_from_saved_window(self) -> None:
manager = MagicMock()
manager.can_resume.return_value = True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rootly/tests/test_rootly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rootly/tests/test_rootly.py
index 54350f53f4e5..8fc4b167fddd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rootly/tests/test_rootly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rootly/tests/test_rootly.py
@@ -2,7 +2,7 @@ import json
from datetime import UTC, date, datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -103,11 +103,11 @@ class TestFormatIncrementalValue:
class TestClampFutureValueToNow:
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_future_datetime_is_clamped(self) -> None:
assert _clamp_future_value_to_now(datetime(2027, 2, 5, tzinfo=UTC)) == datetime(2026, 6, 15, 12, 0, tzinfo=UTC)
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
def test_past_datetime_is_unchanged(self) -> None:
value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
assert _clamp_future_value_to_now(value) == value
@@ -269,7 +269,7 @@ class TestIncrementalParams:
assert snapshots[0]["params"] == expected_params
- @freeze_time("2026-06-15T12:00:00Z")
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_future_cursor_is_clamped(self, MockSession) -> None:
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.py b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.py
index bdb5cb788055..f87089f0a0fd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/runpod/tests/test_runpod.py
@@ -3,7 +3,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -89,8 +89,12 @@ class TestNormalizeBillingRecord:
assert record["time"] == "2025-08-01T00:00:00Z"
-@freeze_time("2022-05-15T12:00:00Z")
class TestBillingWindows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2022-05-15T12:00:00Z", tick=False):
+ yield
+
def test_full_refresh_walks_windows_from_launch_date(self) -> None:
responses = [
[
@@ -210,7 +214,6 @@ class TestSensitiveDataStripping:
assert "env" not in rows[0]["template"]
-@freeze_time("2022-05-15T12:00:00Z")
class TestSampleCapture:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
index ae0594e69272..b895f29cb39e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
@@ -4,7 +4,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from requests import HTTPError, Response
@@ -347,7 +347,7 @@ def _messages_page(count: int, last_event_time: str) -> list[dict[str, Any]]:
class TestActivityPagination:
- @freeze_time("2026-08-07T12:00:00Z")
+ @time_machine.travel("2026-08-07T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_walks_query_window_backwards_until_short_page(self, MockSession) -> None:
session = MockSession.return_value
@@ -421,7 +421,7 @@ class TestActivityPagination:
int(datetime(2026, 8, 1, 3, 4, 5, tzinfo=UTC).timestamp()),
],
)
- @freeze_time("2026-08-07T12:00:00Z")
+ @time_machine.travel("2026-08-07T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_incremental_window_starts_at_watermark(self, MockSession, cursor: Any) -> None:
# The cursor round-trips through storage in several shapes; all must produce the same
@@ -444,7 +444,7 @@ class TestActivityPagination:
== 'last_event_time BETWEEN TIMESTAMP "2026-08-01T03:04:05Z" AND TIMESTAMP "2026-08-07T12:00:00Z"'
)
- @freeze_time("2026-08-07T12:00:00Z")
+ @time_machine.travel("2026-08-07T12:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_full_page_that_cannot_narrow_the_window_stops(self, MockSession) -> None:
# More than `limit` messages sharing the window-end second would otherwise refetch the
@@ -586,7 +586,7 @@ class TestGetEndpointPermissions:
),
],
)
- @freeze_time("2026-08-07T12:00:00Z")
+ @time_machine.travel("2026-08-07T12:00:00Z", tick=False)
def test_probe_uses_the_endpoints_own_pagination_params(
self, endpoint: str, expected_params: dict[str, str]
) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py
index 1a63ed7c4e0c..c2a00d53aa09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py
@@ -2,7 +2,7 @@ from typing import Any
from urllib.parse import parse_qs, urlparse
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -115,7 +115,7 @@ class TestGetRows:
assert rows == []
assert manager.saved == []
- @freeze_time("2026-07-08T12:00:00Z")
+ @time_machine.travel("2026-07-08T12:00:00Z", tick=False)
def test_incremental_walks_creation_windows_under_90_days(self, monkeypatch: Any) -> None:
manager = _FakeResumableManager()
pages = {f"{SHIPPO_BASE_URL}/shipments/": {"next": None, "results": [{"object_id": "s"}]}}
@@ -147,7 +147,7 @@ class TestGetRows:
"2026-07-08T12:00:00Z",
]
- @freeze_time("2026-07-08T12:00:00Z")
+ @time_machine.travel("2026-07-08T12:00:00Z", tick=False)
def test_incremental_resumes_mid_window_then_advances(self, monkeypatch: Any) -> None:
page_2 = f"{SHIPPO_BASE_URL}/shipments/?page=2&object_created_gt=2026-06-01T00:00:00Z"
manager = _FakeResumableManager(ShippoResumeConfig(next_url=page_2, window_start="2026-06-01T00:00:00Z"))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py
index 297f7610b423..68d7f9d8d1e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from requests import Response
@@ -235,7 +235,7 @@ class TestGetRows:
assert "start_date" not in snapshots[0]["params"]
assert snapshots[0]["params"]["sort"] == "oldest"
- @freeze_time("2026-01-31 00:00:00")
+ @time_machine.travel("2026-01-31 00:00:00", tick=False)
@pytest.mark.parametrize("should_use_incremental_field", [True, False])
@mock.patch(CLIENT_SESSION_PATCH)
def test_updated_feed_defaults_to_bounded_lookback_without_watermark(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py
index 342c72a60178..06d6c2c11b6d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any, Optional, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -398,7 +398,7 @@ class TestSimilarwebTransport:
) -> None:
session = _session(_response(json_body=_series_body("visits", [])))
- with freeze_time("2024-06-15"):
+ with time_machine.travel("2024-06-15", tick=False):
_run(
VISITS,
session,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.py
index abc8e4add605..23fca97e7993 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartwaiver/tests/test_smartwaiver.py
@@ -2,7 +2,7 @@ import json
from datetime import UTC, date, datetime
from typing import Any
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -168,7 +168,7 @@ class TestWaivers:
("within_current_hour", "2026-07-08 15:30:00", _HOUR_BOUNDARY),
]
)
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_incremental_cursor_added_and_clamped(self, _name, cursor, expected, MockSession) -> None:
source, params, _manager = _source(
@@ -189,7 +189,7 @@ class TestWaivers:
class TestCheckins:
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_full_sync_uses_default_window(self, MockSession) -> None:
source, params, _manager = _source(
@@ -205,7 +205,7 @@ class TestCheckins:
assert params[0]["limit"] == PAGE_SIZE
assert params[0]["offset"] == 0
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_incremental_sync_starts_window_at_watermark(self, MockSession) -> None:
source, params, _manager = _source(
@@ -219,7 +219,7 @@ class TestCheckins:
assert params[0]["fromDts"] == "2026-06-01T08:00:00"
assert params[0]["toDts"] == _HOUR_BOUNDARY
- @freeze_time(_NOW)
+ @time_machine.travel(_NOW, tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_paginates_while_more_checkins_and_saves_state(self, MockSession) -> None:
source, params, manager = _source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py
index 97d612c06e72..406303e5f073 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -95,7 +95,7 @@ class TestWindows:
# A window must never extend past the requested end (the API rejects future/oversized windows).
assert all(w_end <= end for _, w_end in windows)
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_first_sync_starts_at_the_retention_floor(self) -> None:
# Snowplow only keeps about a week of runs; asking for more gets the window rejected.
window = _jobs_window_bounds(
@@ -107,7 +107,7 @@ class TestWindows:
assert window.end == datetime(2026, 7, 15, 12, tzinfo=UTC)
assert window.start == window.end - snowplow.JOB_RUNS_RETENTION
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_incremental_run_rewinds_watermark_by_lookback(self) -> None:
# A run listed while RUNNING changes state after we fetch it; advancing straight from the
# watermark would freeze it at RUNNING forever.
@@ -119,7 +119,7 @@ class TestWindows:
)
assert window.start == datetime(2026, 7, 14, tzinfo=UTC)
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_stale_watermark_is_clamped_to_the_retention_floor(self) -> None:
# A watermark older than the retention window would produce a from the API rejects.
window = _jobs_window_bounds(
@@ -130,7 +130,7 @@ class TestWindows:
)
assert window.start == window.end - snowplow.JOB_RUNS_RETENTION
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_future_watermark_is_clamped_to_now(self) -> None:
window = _jobs_window_bounds(
should_use_incremental_field=True,
@@ -140,7 +140,7 @@ class TestWindows:
)
assert window.start == window.end
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_resume_window_takes_precedence_over_the_watermark(self) -> None:
# On resume the saved window marks what was already yielded; restarting from the watermark
# would re-fetch (and re-merge) everything the crashed attempt already produced.
@@ -154,7 +154,7 @@ class TestWindows:
class TestJobRuns:
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_windows_are_requested_and_state_saved_after_each(self, monkeypatch: Any) -> None:
run = {"runId": "r1", "state": "SUCCEEDED", "startTime": "2026-07-14T00:10:00Z"}
@@ -180,13 +180,13 @@ class TestJobRuns:
# in-flight window instead of skipping it.
assert [s.window_from for s in manager.saved] == ["2026-07-15T12:00:00Z"]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_resume_restarts_from_the_saved_window(self, monkeypatch: Any) -> None:
manager = _FakeResumableManager(SnowplowResumeConfig(window_from="2026-07-15T00:00:00Z"))
_, client = _run_endpoint("job_runs", lambda path, params: [], manager, monkeypatch)
assert [p for _, p in client.calls] == [{"from": "2026-07-15T00:00:00Z", "to": "2026-07-15T12:00:00Z"}]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_full_window_logs_a_truncation_warning(self, monkeypatch: Any) -> None:
# The API silently caps a window at 10k rows; without the warning a truncated sync looks complete.
logger = MagicMock()
@@ -208,7 +208,7 @@ class TestJobRuns:
class TestJobRunSteps:
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_steps_carry_parent_run_fields(self, monkeypatch: Any) -> None:
# Step names are unique only within a run; the injected runId is what makes the composite
# primary key unique table-wide, and runStartTime is the advertised incremental field.
@@ -243,7 +243,7 @@ class TestJobRunSteps:
}
]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_run_that_404s_is_skipped(self, monkeypatch: Any) -> None:
# A run that aged out of retention between the window listing and the steps fetch must not
# fail the whole sync.
@@ -264,7 +264,7 @@ class TestJobRunSteps:
rows, _ = _run_endpoint("job_run_steps", handler, manager, monkeypatch)
assert [r["runId"] for r in rows] == ["r2"]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_run_without_run_id_is_skipped(self, monkeypatch: Any) -> None:
# runId is part of the (runId, name) primary key; a null-keyed row would collapse steps
# from every such run into one persisted row.
@@ -339,7 +339,7 @@ class TestFailedEventMetricsFanOut:
}
]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_fans_out_over_pipelines_with_incremental_window(self, monkeypatch: Any) -> None:
manager = _FakeResumableManager()
rows, client = _run_endpoint(
@@ -361,7 +361,7 @@ class TestFailedEventMetricsFanOut:
# mid-pipeline re-processes it (merge dedupes) rather than skipping it.
assert [s.completed_pipeline_ids for s in manager.saved] == [["p1"], ["p1", "p2"]]
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
def test_resume_skips_completed_pipelines(self, monkeypatch: Any) -> None:
manager = _FakeResumableManager(SnowplowResumeConfig(completed_pipeline_ids=["p1"]))
rows, client = _run_endpoint("failed_event_metrics", self._handler, manager, monkeypatch)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/swarmia/tests/test_swarmia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/swarmia/tests/test_swarmia.py
index ccbb156cb4d1..0c1d72c128b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/swarmia/tests/test_swarmia.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/swarmia/tests/test_swarmia.py
@@ -2,7 +2,7 @@ from collections.abc import Callable
from datetime import date
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -111,7 +111,6 @@ class TestColumnHandling:
]
-@freeze_time("2026-07-15T12:00:00Z") # a Wednesday
class TestBuildWindows:
@parameterized.expand(
[
@@ -188,8 +187,12 @@ class TestFetchCsv:
assert "startDate=2026-06-29" in session.get.call_args[0][0]
-@freeze_time("2026-07-15T12:00:00Z")
class TestGetRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-15T12:00:00Z", tick=False):
+ yield
+
@patch(_TRACKED_SESSION_PATH)
def test_incremental_sync_fetches_complete_windows_after_watermark(self, mock_make_session: MagicMock) -> None:
session = mock_make_session.return_value
@@ -322,7 +325,7 @@ class TestCredentialChecks:
assert check_credentials("token") is None
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
@patch(_TRACKED_SESSION_PATH)
def test_check_endpoint_access_flags_denied_reports(self, mock_make_session: MagicMock) -> None:
session = mock_make_session.return_value
@@ -368,7 +371,7 @@ class TestHttpSampleCaptureDisabled:
("check_endpoint_access", lambda: check_endpoint_access("token", ["pull_requests"])),
]
)
- @freeze_time("2026-07-15T12:00:00Z")
+ @time_machine.travel("2026-07-15T12:00:00Z", tick=False)
@patch(_TRACKED_SESSION_PATH)
def test_every_request_path_disables_capture_and_redacts_token(
self, _name: str, invoke: Callable[[], object], mock_make_session: MagicMock
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.py
index 443c2fde985e..0a17e7f6a862 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tailscale/tests/test_tailscale.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.tailscale import tailscale as tailscale_module
@@ -189,8 +189,12 @@ class TestGetRows:
]
-@freeze_time("2026-01-30T00:00:00Z")
class TestAuditLogRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-01-30T00:00:00Z", tick=False):
+ yield
+
def _run(self, responses: list[Any], manager: Optional[mock.MagicMock] = None, **kwargs: Any):
if manager is None:
manager = mock.MagicMock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py
index d56c7a5d8371..41c577061035 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py
@@ -2,7 +2,7 @@ from datetime import date
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -282,7 +282,7 @@ class TestTransistorTransport:
assert episode_calls[0]["order"] == "asc"
assert [row["show_id"] for batch in batches for row in batch] == ["22"]
- @freeze_time("2026-08-04")
+ @time_machine.travel("2026-08-04", tick=False)
@pytest.mark.parametrize(
"should_use_incremental_field, last_value, expected_start",
[
@@ -315,7 +315,7 @@ class TestTransistorTransport:
[{"show_id": "11", "date": "2026-07-18", "raw_date": "18-07-2026", "downloads": 7}],
]
- @freeze_time("2026-08-04")
+ @time_machine.travel("2026-08-04", tick=False)
def test_analytics_splits_long_backfills_into_windows_and_checkpoints_each(self):
analytics_params: list[dict[str, Any]] = []
@@ -336,7 +336,7 @@ class TestTransistorTransport:
(1, None),
]
- @freeze_time("2026-08-04")
+ @time_machine.travel("2026-08-04", tick=False)
def test_analytics_resumes_at_the_saved_window(self):
analytics_params: list[dict[str, Any]] = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py
index de7b8c1901d1..4154463174c2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -256,7 +256,7 @@ class TestQuarantinedTests:
class TestFailingTests:
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_fresh_run_defaults_to_lookback_window(self) -> None:
# The 30-day default lookback is walked in 7-day windows, so a fresh run issues
# several requests before reaching "now" — only the first row matters here.
@@ -287,7 +287,7 @@ class TestFailingTests:
# Row gets a `synced_through` cursor stamped on it for incremental watermarking.
assert pages[0][0]["synced_through"] == sent_bodies[0]["end_time"]
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_incremental_run_starts_from_last_value(self) -> None:
# 2024-06-01 -> 2024-06-15 is 14 days, walked in two 7-day windows.
last_value = "2024-06-01T00:00:00Z"
@@ -312,7 +312,7 @@ class TestFailingTests:
assert sent_bodies[0]["start_time"] == last_value
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_window_capped_at_seven_days(self) -> None:
last_value = "2024-01-01T00:00:00Z"
patcher, sent_bodies = _drive_session(
@@ -339,7 +339,7 @@ class TestFailingTests:
first_end = datetime.strptime(sent_bodies[0]["end_time"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
assert (first_end - first_start).days == FAILING_TESTS_WINDOW_DAYS
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_resume_seeds_window_and_page_token(self) -> None:
patcher, sent_bodies = _drive_session([_make_http_response({"tests": [{"id": "f-2"}], "page": _page("")})])
try:
@@ -365,7 +365,7 @@ class TestFailingTests:
assert sent_bodies[0]["start_time"] == "2024-06-10T00:00:00Z"
assert sent_bodies[0]["page_query"]["page_token"] == "cursor-mid"
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_terminates_once_window_reaches_now(self) -> None:
# Seed exactly at "now" so the walk loop must not fire a single request.
patcher, sent_bodies = _drive_session([])
@@ -427,7 +427,7 @@ class TestTrunkCursorPaginator:
class TestMergeQueuePullRequests:
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_fresh_run_paginates_and_stamps_one_synced_through(self) -> None:
patcher, sent_bodies = _drive_session(
[
@@ -482,7 +482,7 @@ class TestMergeQueuePullRequests:
assert sent_bodies[0]["since"] == "2024-06-01T00:00:00Z"
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_resume_seeds_cursor_and_pins_synced_through(self) -> None:
patcher, sent_bodies = _drive_session(
[_make_http_response({"pullRequests": [{"id": "pr-3"}], "nextCursor": ""})]
@@ -511,7 +511,7 @@ class TestMergeQueuePullRequests:
# The resumed half must not claim coverage the interrupted first half never had.
assert pages[0][0]["synced_through"] == "2024-06-14T00:00:00Z"
- @freeze_time("2024-06-15T00:00:00Z")
+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)
def test_saves_cursor_with_stamp_after_each_non_terminal_page(self) -> None:
patcher, _ = _drive_session(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py
index e4f3f1e7d43e..7330d4729edf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -518,8 +518,12 @@ class TestUbidotsSourceResponse:
assert called == [expected_fn]
-@freeze_time("2026-07-28T00:00:00Z")
class TestGetValuesRowsV2:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-28T00:00:00Z", tick=False):
+ yield
+
NOW_MS = int(datetime(2026, 7, 28, tzinfo=UTC).timestamp() * 1000)
@staticmethod
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.py
index f81a480ddde1..513c2aa65876 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/tests/test_wikipedia_pageviews.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any, Optional
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -134,7 +134,7 @@ class TestHelpers:
class TestPageviews:
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_single_window_rows_get_typed_date_and_state_saved_after_yield(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"items": [_aggregate_item("2026071800", views=42)]})
@@ -155,7 +155,7 @@ class TestPageviews:
saved = [call.args[0].next_start for call in manager.save_state.call_args_list]
assert saved == ["2026-07-22"]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_long_ranges_are_chunked_into_contiguous_windows(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"items": [_aggregate_item("2024070100")]})
@@ -171,7 +171,7 @@ class TestPageviews:
saved = [call.args[0].next_start for call in manager.save_state.call_args_list]
assert saved == ["2025-07-02", "2026-07-03", "2026-07-22"]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_start_date_before_data_start_is_clamped(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"items": []})
@@ -183,7 +183,7 @@ class TestPageviews:
first_start, _ = _requested_ranges(session)[0]
assert first_start == f"{DATA_START_DATE:%Y%m%d}00"
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_404_window_is_skipped_and_iteration_continues(self):
session = mock.MagicMock(spec=requests.Session)
session.get.side_effect = [
@@ -198,7 +198,7 @@ class TestPageviews:
assert len(batches) == 1
assert batches[0][0]["timestamp"] == "2025070200"
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_incremental_starts_at_watermark_day(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"items": []})
@@ -213,7 +213,7 @@ class TestPageviews:
# The watermark day itself is re-fetched (merge dedupes) to pick up late revisions.
assert _requested_ranges(session) == [("2026071500", "2026072100")]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_resume_state_takes_precedence_over_incremental_value(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"items": []})
@@ -229,7 +229,7 @@ class TestPageviews:
assert _requested_ranges(session) == [("2026071900", "2026072100")]
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_non_ok_status_raises(self):
response = _response(status=500, text="server error")
response.raise_for_status.side_effect = requests.HTTPError
@@ -241,7 +241,7 @@ class TestPageviews:
class TestArticlePageviews:
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_fans_out_per_article_with_encoded_titles(self):
session = mock.MagicMock(spec=requests.Session)
session.get.side_effect = [
@@ -283,7 +283,7 @@ class TestArticlePageviews:
with pytest.raises(ValueError, match=NO_ARTICLES_ERROR):
_run(ARTICLE_PAGEVIEWS_ENDPOINT, mock.MagicMock(spec=requests.Session), article_names=" , ")
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_article_titles_capped_at_max_at_runtime(self):
session = mock.MagicMock(spec=requests.Session)
session.get.return_value = _response(json_body={"items": []})
@@ -297,7 +297,7 @@ class TestArticlePageviews:
class TestTopArticles:
- @freeze_time("2026-07-21")
+ @time_machine.travel("2026-07-21", tick=False)
def test_flattens_daily_rankings_into_rows(self):
def day_response(url: str, timeout: int = 0) -> mock.MagicMock:
match = re.search(r"/top/en\.wikipedia\.org/all-access/(\d{4})/(\d{2})/(\d{2})$", url)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic.py
index 57940fe27e29..d76c8f6fce72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -146,8 +146,12 @@ class TestConfigEndpoints:
_collect("nonexistent", _FakeManager(), monkeypatch, _FakeApi())
-@freeze_time("2026-07-09T12:00:00Z")
class TestDailyEndpoints:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-07-09T12:00:00Z", tick=False):
+ yield
+
def test_walks_days_from_watermark_to_today_inclusive(self, monkeypatch):
# The watermark day is re-fetched: its previous sync may have run mid-day and captured
# partial data. Skipping it would permanently freeze that day's rows.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.py
index ccece13f5ee5..e23471530e6d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import MagicMock, Mock, patch
from parameterized import parameterized
@@ -161,7 +161,7 @@ class TestYocoPaginator:
class TestYocoResources:
- @freeze_time("2026-05-01T00:00:00Z")
+ @time_machine.travel("2026-05-01T00:00:00Z", tick=False)
def test_incremental_resource_windows_from_the_watermark(self) -> None:
resource = cast(
dict[str, Any],
@@ -179,7 +179,7 @@ class TestYocoResources:
assert request.params["updated_at__lte"] == "2026-05-01T00:00:00Z"
def test_window_never_exceeds_the_api_maximum(self) -> None:
- with freeze_time("2026-05-01T00:00:00Z"):
+ with time_machine.travel("2026-05-01T00:00:00Z", tick=False):
resource = cast(
dict[str, Any],
get_resource(
@@ -219,7 +219,7 @@ class TestYocoResources:
("endpoint_without_updated_at", "modifier_groups", None, "created_at__gte"),
]
)
- @freeze_time("2026-05-01T00:00:00Z")
+ @time_machine.travel("2026-05-01T00:00:00Z", tick=False)
def test_incremental_field_selection(
self, _name: str, endpoint: str, incremental_field: str | None, expected_param: str
) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py
index 9e7b2fabcbc9..12ba7c93a6ae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py
@@ -3,7 +3,7 @@ from datetime import UTC, date, datetime
from typing import Any, cast
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
import requests
@@ -270,8 +270,12 @@ class TestResolveStartDay:
assert resolve_start_day(start_date, should_use_incremental_field, last_value, date(2026, 7, 26)) == expected
-@freeze_time(FROZEN_NOW)
class TestGetRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(FROZEN_NOW, tick=False):
+ yield
+
def test_day_dimension_report_covers_a_multi_day_window_per_request(self) -> None:
manager = FakeResumeManager()
result = _result(["day", "views"], [["2026-07-20", 5], ["2026-07-21", 6]])
@@ -385,8 +389,12 @@ class TestGetRows:
assert sent[0]["ids"] == "channel==UC123"
-@freeze_time(FROZEN_NOW)
class TestValidateCredentials:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(FROZEN_NOW, tick=False):
+ yield
+
def _patch_client(self, query: Any) -> Any:
client = mock.MagicMock(spec=YouTubeAnalyticsClient)
client.query.side_effect = query
@@ -478,7 +486,7 @@ class TestYouTubeAnalyticsSourceResponse:
# Windows are walked oldest-first, so the incremental watermark advances safely.
assert response.sort_mode == "asc"
- @freeze_time(FROZEN_NOW)
+ @time_machine.travel(FROZEN_NOW, tick=False)
def test_items_is_lazy_until_iterated(self) -> None:
manager = FakeResumeManager()
response = youtube_analytics_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 09d2428f52e1..97c0d65c26a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -10,7 +10,7 @@ from typing import Any, Optional, cast
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest import mock
from unittest.mock import AsyncMock
@@ -1076,7 +1076,7 @@ async def test_postgres_binary_primary_key_synced_as_hex(team, postgres_config,
@pytest.mark.asyncio
async def test_delta_wrapper_files(team, stripe_balance_transaction, mock_stripe_client, minio_client):
datetime_now = datetime.now(tz=ZoneInfo("UTC"))
- with freeze_time(datetime_now):
+ with time_machine.travel(datetime_now, tick=False):
workflow_id, inputs = await _run(
team=team,
schema_name="BalanceTransaction",
@@ -1258,7 +1258,7 @@ async def test_sql_database_incremental_initial_value(team, postgres_config, pos
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_billing_limits(team, stripe_customer, mock_stripe_client):
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
source = await sync_to_async(ExternalDataSource.objects.create)(
source_id=uuid.uuid4(),
connection_id=uuid.uuid4(),
@@ -1305,7 +1305,7 @@ async def test_billing_limits(team, stripe_customer, mock_stripe_client):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_create_external_job_failure(team, stripe_customer, mock_stripe_client):
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
source = await sync_to_async(ExternalDataSource.objects.create)(
source_id=uuid.uuid4(),
connection_id=uuid.uuid4(),
@@ -1407,7 +1407,7 @@ async def test_create_external_job_failure_no_job_model(team, stripe_customer, m
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_non_retryable_error(team, zendesk_brands):
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
source = await sync_to_async(ExternalDataSource.objects.create)(
source_id=uuid.uuid4(),
connection_id=uuid.uuid4(),
@@ -1463,7 +1463,7 @@ async def test_non_retryable_error(team, zendesk_brands):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_non_retryable_error_with_special_characters(team, stripe_customer, mock_stripe_client):
- with freeze_time("2024-01-01T12:00:00Z"):
+ with time_machine.travel("2024-01-01T12:00:00Z", tick=False):
source = await sync_to_async(ExternalDataSource.objects.create)(
source_id=uuid.uuid4(),
connection_id=uuid.uuid4(),
@@ -3467,7 +3467,7 @@ async def test_billing_limits_too_many_rows_previously(team, postgres_config, po
mock.patch("ee.billing.billing_manager.http_session.get") as mock_billing_request,
mock.patch("posthog.cloud_utils.is_instance_licensed_cached", None),
):
- with freeze_time("2023-01-01"):
+ with time_machine.travel("2023-01-01", tick=False):
source = await sync_to_async(ExternalDataSource.objects.create)(team=team)
# A previous job that reached the billing limit
@@ -3715,7 +3715,7 @@ async def test_postgres_deleting_schemas_with_pre_synced_data(team, postgres_con
@pytest.mark.asyncio
async def test_timestamped_query_folder(team, stripe_balance_transaction, mock_stripe_client, minio_client):
datetime_1 = datetime.now()
- with freeze_time(datetime_1):
+ with time_machine.travel(datetime_1, tick=False):
workflow_id, inputs = await _run(
team=team,
schema_name=STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,
@@ -3733,7 +3733,7 @@ async def test_timestamped_query_folder(team, stripe_balance_transaction, mock_s
# Sync a second time 5 minutes later
datetime_2 = datetime_1 + timedelta(minutes=5)
- with freeze_time(datetime_2):
+ with time_machine.travel(datetime_2, tick=False):
await _execute_run(workflow_id, inputs, stripe_balance_transaction["data"])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -3751,7 +3751,7 @@ async def test_timestamped_query_folder(team, stripe_balance_transaction, mock_s
# Sync a third time 3 minutes later (still under 10 mins since the first sync)
datetime_3 = datetime_2 + timedelta(minutes=3)
- with freeze_time(datetime_3):
+ with time_machine.travel(datetime_3, tick=False):
await _execute_run(workflow_id, inputs, stripe_balance_transaction["data"])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -3774,7 +3774,7 @@ async def test_timestamped_query_folder(team, stripe_balance_transaction, mock_s
# Sync a fourth time 5 minutes later (now over 10 mins since the first sync)
datetime_4 = datetime_3 + timedelta(minutes=5)
- with freeze_time(datetime_4):
+ with time_machine.travel(datetime_4, tick=False):
await _execute_run(workflow_id, inputs, stripe_balance_transaction["data"])
await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
@@ -3803,7 +3803,7 @@ async def test_timestamped_query_folder(team, stripe_balance_transaction, mock_s
# Sync a fifth time 1 min later but with a reduced query file delete buffer
datetime_5 = datetime_4 + timedelta(minutes=1)
with (
- freeze_time(datetime_5),
+ time_machine.travel(datetime_5, tick=False),
mock.patch("products.warehouse_sources.backend.temporal.data_imports.util.S3_DELETE_TIME_BUFFER", 1),
):
await _execute_run(workflow_id, inputs, stripe_balance_transaction["data"])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
index 24b1ac9c0f58..60594fe1fe95 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
@@ -3,12 +3,12 @@ from datetime import datetime, timedelta
from typing import Any
import pytest
+import time_machine
from unittest import mock
from asgiref.sync import sync_to_async
from posthog.models.team.team import Team
-from posthog.tasks.test.test_usage_report import freeze_time
from products.warehouse_sources.backend.facade.models import (
DataWarehouseCredential,
@@ -627,7 +627,7 @@ def test_report_heartbeat_timeout_heartbeat_not_within_timeout(team):
team_id=team.pk, schema_id=uuid.uuid4(), source_id=uuid.uuid4(), run_id="run_id"
)
- with freeze_time("2024-01-01 12:00:00"):
+ with time_machine.travel("2024-01-01 12:00:00", tick=False):
past_time = datetime.now() - timedelta(seconds=30)
mock_info = mock.MagicMock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_snapchat_ads_utils.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_snapchat_ads_utils.py
index a60922579274..c3850b1e68de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_snapchat_ads_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_snapchat_ads_utils.py
@@ -2,7 +2,7 @@ from datetime import date, datetime, timedelta
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import Mock
from parameterized import parameterized
@@ -45,8 +45,12 @@ class TestSnapchatErrorHandler:
assert SnapchatErrorHandler.is_retryable(error) == expected
-@freeze_time(FROZEN_TIME)
class TestSnapchatDateRangeManager:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(FROZEN_TIME, tick=False):
+ yield
+
@parameterized.expand(
[
("no_incremental", False, None, 365),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py
index 8f2045d4df78..c330db364d6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_metrics_app_metrics2.py
@@ -1,7 +1,7 @@
import datetime as dt
from uuid import uuid4
-from freezegun import freeze_time
+import time_machine
from unittest import TestCase, mock
from parameterized import parameterized
@@ -220,7 +220,7 @@ class TestEmitDataImportAppMetrics(TestCase):
frozen_now = dt.datetime(2026, 4, 15, 9, 0, 0, tzinfo=dt.UTC)
with (
- freeze_time(frozen_now),
+ time_machine.travel(frozen_now, tick=False),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.metrics.get_producer"
) as mock_producer_cls,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py
index 4a843a9d49a0..dbf883bcc9a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py
@@ -5,7 +5,7 @@ from typing import Optional
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import BaseTest
from unittest import mock
@@ -227,13 +227,13 @@ class TestRowTracking(BaseTest):
with (
override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"),
self._setup_limits(limit),
- freeze_time("2024-01-01 12:00:00"),
+ time_machine.travel("2024-01-01 12:00:00", tick=False),
):
return await will_hit_billing_limit(team_id=self.team.pk, source=source, logger=self._logger())
@sync_to_async
def _create_source(self) -> ExternalDataSource:
- with freeze_time(datetime(2023, 12, 1)):
+ with time_machine.travel(datetime(2023, 12, 1), tick=False):
return ExternalDataSource.objects.create(team=self.team)
@pytest.mark.asyncio
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index 11516d27fb9c..bf0c5e020dd2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -2,7 +2,7 @@ import uuid
from datetime import UTC, datetime, timedelta
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import AsyncMock, MagicMock, patch
from temporalio.client import WorkflowExecutionStatus
@@ -481,7 +481,7 @@ class TestTakeOverStaleRunningJob:
mock_conn_cls.connect.side_effect = RuntimeError("connection refused")
assert self._run() is False
- @freeze_time("2026-01-01T12:00:00Z")
+ @time_machine.travel("2026-01-01T12:00:00Z", tick=False)
@patch(f"{MODULE}._release_and_acquire", return_value=True)
@patch(f"{MODULE}.update_external_job_status")
@patch(f"{MODULE}.BatchQueue")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py
index 5a81bf4a8655..4fd2381c170a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_fast_return_eligibility.py
@@ -8,7 +8,7 @@ fast-returns. A dropped condition is silent until a customer notices stale state
import uuid
import datetime as dt
-from freezegun import freeze_time
+import time_machine
from unittest.mock import patch
from parameterized import parameterized
@@ -89,7 +89,7 @@ class TestFastReturnEligibility:
def test_schema_state_that_blocks_eligibility(self, _name: str, config_overrides: dict):
assert _run(_schema(**config_overrides)) is False
- @freeze_time("2026-08-24T12:00:00Z")
+ @time_machine.travel("2026-08-24T12:00:00Z", tick=False)
def test_naive_full_run_stamp_is_not_eligible(self):
assert _run(_schema(last_full_run_at="2026-08-24T11:00:00")) is False
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index bb3e0b31526b..b5128cd41754 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -5,7 +5,7 @@ import typing as t
from datetime import date, timedelta
from typing import Any, cast
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, Mock, PropertyMock, patch
@@ -5762,9 +5762,9 @@ class TestExternalDataSource(APIBaseTest):
("2024-07-01T18:00:00.000Z", ExternalDataJob.Status.COMPLETED),
("2024-07-02T06:00:00.000Z", ExternalDataJob.Status.FAILED),
]:
- with freeze_time(created_at):
+ with time_machine.travel(created_at, tick=False):
ExternalDataJob.objects.create(team=self.team, pipeline=source, schema=schema, status=job_status)
- with freeze_time("2024-07-02T06:00:00.000Z"):
+ with time_machine.travel("2024-07-02T06:00:00.000Z", tick=False):
ExternalDataJob.objects.create(
team=self.team, pipeline=never_completed, status=ExternalDataJob.Status.RUNNING
)
@@ -5833,7 +5833,7 @@ class TestExternalDataSource(APIBaseTest):
def test_source_jobs_pagination(self):
source = self._create_external_data_source()
schema = self._create_external_data_schema(source.pk)
- with freeze_time("2024-07-01T12:00:00.000Z"):
+ with time_machine.travel("2024-07-01T12:00:00.000Z", tick=False):
job1 = ExternalDataJob.objects.create(
team=self.team,
pipeline=source,
@@ -5855,7 +5855,7 @@ class TestExternalDataSource(APIBaseTest):
assert data[0]["id"] == str(job1.pk)
# Query newer jobs
- with freeze_time("2024-07-01T18:00:00.000Z"):
+ with time_machine.travel("2024-07-01T18:00:00.000Z", tick=False):
job2 = ExternalDataJob.objects.create(
team=self.team,
pipeline=source,
@@ -5877,7 +5877,7 @@ class TestExternalDataSource(APIBaseTest):
assert data[0]["id"] == str(job2.pk)
# Query older jobs
- with freeze_time("2024-07-01T09:00:00.000Z"):
+ with time_machine.travel("2024-07-01T09:00:00.000Z", tick=False):
job3 = ExternalDataJob.objects.create(
team=self.team,
pipeline=source,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py b/products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py
index 92933cc1bc92..62f06f337725 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py
@@ -1,6 +1,6 @@
from typing import Optional, Union
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -29,7 +29,7 @@ class TestExternalClicksTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$autocapture"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.py b/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.py
index 069f7156bb59..5fa024804644 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_first_pageview_attribution_trends.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from django.test import override_settings
@@ -39,7 +39,7 @@ class TestFirstPageviewAttributionTrends(FirstPageviewAttributionTestMixin, Clic
tags=QueryLogTags(productKey="web_analytics") if tagged else None,
modifiers=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),
)
- with self._patch_first_pageview_flag(flag_on), freeze_time(self.QUERY_TIMESTAMP):
+ with self._patch_first_pageview_flag(flag_on), time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = TrendsQueryRunner(team=self.team, query=query).calculate()
return response.results[0]["count"]
@@ -88,7 +88,7 @@ class TestFirstPageviewAttributionTrends(FirstPageviewAttributionTestMixin, Clic
tags=QueryLogTags(productKey="web_analytics"),
modifiers=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),
)
- with self._patch_first_pageview_flag(flag_on), freeze_time(self.QUERY_TIMESTAMP):
+ with self._patch_first_pageview_flag(flag_on), time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
results = get_query_runner(query, team=self.team).calculate().results
assert results[0]["count"] == expected
diff --git a/products/web_analytics/backend/hogql_queries/test/test_notable_changes.py b/products/web_analytics/backend/hogql_queries/test/test_notable_changes.py
index 3b1bc6f5ba24..07fc3cd6f698 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_notable_changes.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_notable_changes.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, snapshot_clickhouse_queries
from posthog.schema import (
@@ -36,7 +36,7 @@ class TestWebNotableChangesQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def test_empty_results_without_preaggregated(self):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = self._create_query()
runner = WebNotableChangesQueryRunner(
team=self.team,
@@ -153,7 +153,7 @@ class TestWebNotableChangesQueryRunner(ClickhouseTestMixin, APIBaseTest):
},
)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = self._create_query(limit=50)
runner = WebNotableChangesQueryRunner(
team=self.team,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_page_reports_avg_time.py b/products/web_analytics/backend/hogql_queries/test/test_page_reports_avg_time.py
index 16ed5295e925..3c885277a359 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_page_reports_avg_time.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_page_reports_avg_time.py
@@ -1,7 +1,7 @@
from collections import defaultdict
from dataclasses import dataclass
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
import numpy as np
@@ -63,7 +63,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
def _create_pageviews(self, distinct_id: str, list_page_view_properties: list[PageViewProperties]):
person_time = list_page_view_properties[0].timestamp
- with freeze_time(person_time):
+ with time_machine.travel(person_time, tick=False):
person_result = _create_person(
team_id=self.team.pk,
distinct_ids=[distinct_id],
@@ -173,7 +173,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
stats = self._calculate_pageview_statistics([page_views])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/a", "all", "2025-12-15")
result_data = response.results[0]["data"]
@@ -201,7 +201,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
stats = self._calculate_pageview_statistics([p1_page_views, p2_page_views, p3_page_views])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/a", "all", "2025-12-15")
result_data = response.results[0]["data"]
@@ -229,7 +229,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
stats = self._calculate_pageview_statistics([p1_page_views, p2_page_views, p3_page_views])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/a", "all", "2025-12-15")
result_data = response.results[0]["data"]
@@ -264,7 +264,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
stats = self._calculate_pageview_statistics([p1_page_views, p2_page_views, p3_page_views, p4_page_views])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/a", "all", "2025-12-15")
result_data = response.results[0]["data"]
@@ -279,7 +279,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
self._create_pageviews("p1", page_views)
flush_persons_and_events()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/nonexistent", "all", "2025-12-15")
result_data = response.results[0]["data"]
@@ -307,7 +307,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
day1_stats = self._calculate_pageview_statistics([p1_day1, p2_day1])
day2_stats = self._calculate_pageview_statistics([p1_day2])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/a", "all", "2025-12-15")
result_data = response.results[0]["data"]
@@ -325,7 +325,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
stats = self._calculate_pageview_statistics([page_views])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/a", "all", "2025-12-15", interval=interval)
result_data = response.results[0]["data"]
@@ -357,7 +357,7 @@ class TestPageReportsTimeOnPage(ClickhouseTestMixin, APIBaseTest):
stats = self._calculate_pageview_statistics([p1_page_views, p2_page_views, p3_page_views, p4_page_views])
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
response = self._run_p90_time_query("/start", "all", "2025-12-15")
result_data = response.results[0]["data"]
diff --git a/products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py
index 7ca879e4a5fc..17cfc567b87b 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from posthog.schema import DateRange, WebAnalyticsPreComputeStrategy, WebPageURLSearchQuery
@@ -14,7 +14,7 @@ class TestPageUrlSearchQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -70,7 +70,7 @@ class TestPageUrlSearchQueryRunner(ClickhouseTestMixin, APIBaseTest):
stripQueryParams=False,
properties=None,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = WebPageURLSearchQuery(
dateRange=DateRange(date_from=date_from, date_to=date_to),
properties=properties or [],
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py b/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py
index 3a4271fe64b0..eb50f78b8e8a 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from posthog.schema import (
@@ -77,7 +77,7 @@ class TestWebAgentAnalyticsQueryRunner(ClickhouseTestMixin, APIBaseTest):
intentKey=intent_key,
limit=limit,
)
- with freeze_time("2026-08-20T18:00:00Z"):
+ with time_machine.travel("2026-08-20T18:00:00Z", tick=False):
return WebAgentAnalyticsQueryRunner(team=self.team, query=query).calculate()
@staticmethod
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
index 8101cd6cf65f..8d731cdbd614 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from parameterized import parameterized
@@ -37,7 +37,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -70,7 +70,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
cohort_id: int | None = None,
use_preaggregated: bool = False,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
properties = []
if cohort_id is not None:
properties.append(CohortPropertyFilter(key="id", value=cohort_id, type="cohort"))
@@ -92,7 +92,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
cohort_id: int | None = None,
use_preaggregated: bool = False,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
properties = []
if cohort_id is not None:
properties.append(CohortPropertyFilter(key="id", value=cohort_id, type="cohort"))
@@ -113,7 +113,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
date_to: str,
cohort_id: int | None = None,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
properties = []
if cohort_id is not None:
properties.append(CohortPropertyFilter(key="id", value=cohort_id, type="cohort"))
@@ -339,7 +339,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
cohort = self._create_cohort_with_person("p1")
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
properties = [CohortPropertyFilter(key="id", value=cohort.id, type="cohort")]
modifiers = HogQLQueryModifiers(useWebAnalyticsPreAggregatedTables=True)
query = WebOverviewQuery(
@@ -360,7 +360,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
cohort = self._create_cohort_with_person("p1")
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
properties = [CohortPropertyFilter(key="id", value=cohort.id, type="cohort")]
modifiers = HogQLQueryModifiers(useWebAnalyticsPreAggregatedTables=True)
query = WebStatsTableQuery(
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
index 1bf355462325..85f3276e47ce 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -22,7 +22,7 @@ from products.web_analytics.backend.hogql_queries.web_overview import WebOvervie
class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
_create_person(
team_id=self.team.pk,
distinct_ids=[id],
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_bots.py b/products/web_analytics/backend/hogql_queries/test/test_web_bots.py
index 151c6d3cebd6..8dd8e2d8f583 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_bots.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_bots.py
@@ -1,7 +1,7 @@
import re
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -113,14 +113,14 @@ class TestWebBotsTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_only_bot_traffic_grouped_by_breakdown(
self, breakdown_by: WebBotsBreakdown, expected_first_value: str
) -> None:
- with freeze_time("2026-01-10T11:00:00Z"):
+ with time_machine.travel("2026-01-10T11:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["bot"], properties={})
_create_person(team_id=self.team.pk, distinct_ids=["human"], properties={})
self._create_pageview("bot", GOOGLEBOT_UA, "/pricing")
self._create_pageview("bot", GOOGLEBOT_UA, "/pricing")
self._create_pageview("human", HUMAN_UA, "/pricing")
- with freeze_time("2026-01-15T00:00:00Z"):
+ with time_machine.travel("2026-01-15T00:00:00Z", tick=False):
results = self._run(breakdown_by)
self.assertEqual(len(results), 1)
@@ -129,11 +129,11 @@ class TestWebBotsTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0][requests_column], 2) # human pageview excluded
def test_date_range_excludes_outside_events(self) -> None:
- with freeze_time("2026-01-10T11:00:00Z"):
+ with time_machine.travel("2026-01-10T11:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["bot"], properties={})
self._create_pageview("bot", GOOGLEBOT_UA, "/pricing")
- with freeze_time("2026-03-15T00:00:00Z"):
+ with time_machine.travel("2026-03-15T00:00:00Z", tick=False):
query = WebBotsTableQuery(
breakdownBy=WebBotsBreakdown.CRAWLER,
dateRange=DateRange(date_from="2026-03-01", date_to="2026-03-31"),
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py
index 65f7aed09961..c85ac9cfe2ce 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from posthog.schema import DateRange, HogQLQueryModifiers, SessionTableVersion, WebOverviewQuery
@@ -15,7 +15,7 @@ from products.web_analytics.backend.hogql_queries.web_overview import WebOvervie
class TestWebBouncesPreAggregated(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
- with freeze_time("2024-01-01T09:00:00Z"):
+ with time_machine.travel("2024-01-01T09:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["anon1"])
_create_person(team_id=self.team.pk, distinct_ids=["user1"])
_create_person(team_id=self.team.pk, distinct_ids=["user2"])
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.py
index c412606de624..2b2a1d67b464 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.py
@@ -1,7 +1,7 @@
from collections.abc import Iterator
from contextlib import ExitStack, contextmanager
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -93,7 +93,7 @@ class TestWebCalendarHeatmapLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
cols = {(c.column, c.value) for c in structured.columnAggregations}
return cells, rows, cols, structured.allAggregations
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_unique_tab_matches_live_calendar_heatmap(self) -> None:
self._seed()
query = self._build_query(unique_tab=True)
@@ -109,7 +109,7 @@ class TestWebCalendarHeatmapLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._heatmap_as_dicts(pre_hm) == self._heatmap_as_dicts(live_hm)
assert precomputed.results[0]["count"] == live.results[0]["count"]
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_total_events_tab_falls_back(self) -> None:
# The total tab buckets by raw event timestamp; the session-start-keyed
# buckets can't reproduce that, so serving it would shift midnight- and
@@ -130,7 +130,7 @@ class TestWebCalendarHeatmapLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
)
def test_falls_back_when_buckets_cannot_reproduce_live_semantics(self, case: str) -> None:
with ExitStack() as stack:
- stack.enter_context(freeze_time("2024-01-15T12:00:00Z"))
+ stack.enter_context(time_machine.travel("2024-01-15T12:00:00Z", tick=False))
self._seed()
query = self._build_query()
if case == "distinct_id_aggregation":
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py
index 477e6275d101..68e072be1cd5 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime, timedelta
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from django.test import override_settings
@@ -87,7 +87,7 @@ class TestWebDimensionalPrecompute(ClickhouseTestMixin, APIBaseTest):
)
return int(rows[0][0]), int(rows[0][1]), int(rows[0][2])
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stats_ensure_creates_jobs_and_correct_totals(self):
self._seed_two_sessions()
result = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)
@@ -101,7 +101,7 @@ class TestWebDimensionalPrecompute(ClickhouseTestMixin, APIBaseTest):
assert sessions == 2
assert pageviews == 3
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stats_breaks_down_by_host(self):
self._seed_two_sessions()
result = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)
@@ -124,7 +124,7 @@ class TestWebDimensionalPrecompute(ClickhouseTestMixin, APIBaseTest):
assert by_host["example.com"] == (1, 1, 2)
assert by_host["other.com"] == (1, 1, 1)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stats_second_call_is_cache_hit(self):
self._seed_two_sessions()
first = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)
@@ -138,7 +138,7 @@ class TestWebDimensionalPrecompute(ClickhouseTestMixin, APIBaseTest):
assert jobs_after_second == jobs_after_first
assert set(second.job_ids) == set(first.job_ids)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_bounces_ensure_creates_jobs_and_correct_totals(self):
self._seed_two_sessions()
result = ensure_web_bounces_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)
@@ -167,7 +167,7 @@ class TestWebDimensionalPrecompute(ClickhouseTestMixin, APIBaseTest):
# Bounce semantics depend on the session table; just assert it's in range.
assert 0 <= bounces <= 2
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_separate_chunks_share_one_query_hash_and_read_reassembles_window(self):
# Two events in two different 7-day chunks of the same window.
_create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
@@ -265,7 +265,7 @@ class TestColdBackfillSplitsByTtlBandNotPerDay(unittest.TestCase):
window spans (a handful), and the bulk of history is one big INSERT — not 90.
"""
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_dimensional_schedule_90d_cold_range_is_three_bands(self):
end = datetime(2024, 6, 15, 12, tzinfo=UTC)
start = end - timedelta(days=90)
@@ -290,7 +290,7 @@ class TestColdBackfillSplitsByTtlBandNotPerDay(unittest.TestCase):
assert e1 == s2
assert sum((e - s).days for s, e, _ in bands) >= 90
- @freeze_time("2024-06-15T12:00:00Z")
+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)
def test_today_yesterday_7d_rest_schedule_is_four_bands(self):
# The exact schedule shape described in review: today / yesterday / last
# 7 days / the rest -> four INSERTs for a cold 90-day range.
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py
index f5f1f55108c8..7a7fa423a4f5 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py
@@ -14,7 +14,7 @@ tables exist to provide.
from datetime import UTC, datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person
from posthog.clickhouse.client import sync_execute
@@ -68,7 +68,7 @@ class TestWebDimensionalPrecomputeParity(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
sa, sb, sc = (str(uuid7(DATE_START)) for _ in range(3))
- with freeze_time("2024-01-01T09:00:00Z"):
+ with time_machine.travel("2024-01-01T09:00:00Z", tick=False):
# Create persons so events resolve to a stable person_id per distinct_id
# (without this, _create_event assigns a fresh random person_id per row).
for did in ("user_a", "user_b", "user_c"):
@@ -141,7 +141,7 @@ class TestWebDimensionalPrecomputeParity(WebAnalyticsPreAggregatedTestBase):
n = len(dims)
return {tuple(row[:n]): tuple(int(v) for v in row[n:]) for row in rows}
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stats_parity_with_v2(self):
# v2 path: populate web_pre_aggregated_stats directly.
sync_execute(
@@ -178,7 +178,7 @@ class TestWebDimensionalPrecomputeParity(WebAnalyticsPreAggregatedTestBase):
)
assert by_path == {("/",): (2,), ("/pricing",): (1,), ("/blog",): (1,)}, by_path
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_bounces_parity_with_v2(self):
sync_execute(
WEB_BOUNCES_INSERT_SQL(
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
index 676fa0f4fa75..acd7d8991568 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
@@ -1,6 +1,6 @@
from typing import Optional
-from freezegun.api import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -38,7 +38,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
EVENT_TIMESTAMP = "2024-12-01"
def _create_person(self):
- with freeze_time(self.EVENT_TIMESTAMP):
+ with time_machine.travel(self.EVENT_TIMESTAMP, tick=False):
distinct_id = self._uuid()
session_id = self._uuid()
p = _create_person(
@@ -59,7 +59,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
return p, session_id
def _visit_web_analytics(self, person: Person, session_id: Optional[str] = None):
- with freeze_time(self.EVENT_TIMESTAMP):
+ with time_machine.travel(self.EVENT_TIMESTAMP, tick=False):
_create_event(
team=self.team,
event="$pageview",
@@ -73,7 +73,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def _click_pay(self, person: Person, session_id: Optional[str] = None):
- with freeze_time(self.EVENT_TIMESTAMP):
+ with time_machine.travel(self.EVENT_TIMESTAMP, tick=False):
_create_event(
team=self.team,
event="$autocapture",
@@ -84,7 +84,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
def _create_actions(self):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
a0 = Action.objects.create(
team=self.team,
name="Clicked Pay",
@@ -135,7 +135,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
session_table_version: SessionTableVersion = SessionTableVersion.V2,
filter_test_accounts: Optional[bool] = False,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
modifiers = HogQLQueryModifiers(sessionTableVersion=session_table_version)
query = WebGoalsQuery(
dateRange=DateRange(date_from=date_from, date_to=date_to),
@@ -149,7 +149,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
return runner.calculate()
def _uuid(self):
- with freeze_time(self.EVENT_TIMESTAMP):
+ with time_machine.travel(self.EVENT_TIMESTAMP, tick=False):
return str(uuid7())
def test_no_crash_when_no_data_or_actions(self):
@@ -272,7 +272,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_aggregate_function_in_where_error(self):
"""Test cohort with multiple actions that produced the aggregate function in WHERE clause error:
Aggregate function any(if(NOT empty(events__override.distinct_id), events__override.person_id, events.person_id))AS person_id is found in WHERE in query."""
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
cohort = Cohort.objects.create(
team=self.team,
filters={
@@ -292,7 +292,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
# Create multiple actions to generate complex query
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
Action.objects.create(
team=self.team,
name="Test Action 1",
@@ -372,7 +372,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
# Create persons with distinct_id overrides to trigger the error
- with freeze_time(self.EVENT_TIMESTAMP):
+ with time_machine.travel(self.EVENT_TIMESTAMP, tick=False):
# Create persons with different distinct_ids but insert overrides that create conflicts
distinct_id_1 = self._uuid()
distinct_id_2 = self._uuid()
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py
index 367c833b1e40..aa10e120c73f 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py
@@ -1,5 +1,5 @@
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -179,7 +179,7 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# read-after-write visibility issue tracked on the paths tests is open.
# ----------------------------------------------------------------------
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_round_trip_creates_precompute_job(self):
self._create_action("Pageview")
self._seed_goal_events()
@@ -201,7 +201,7 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"lazy path returns empty rows despite READY job. Re-enable once the "
"read-after-write visibility issue tracked there is resolved."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_response_matches_live(self):
"""Compare the goals response between the live and lazy paths."""
action = self._create_action("Pageview")
@@ -229,7 +229,7 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# The live slice is hard-coded `[:5]` in `web_goals.py`'s `to_query`.
assert MAX_ACTIONS == 5
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stale_served_enqueues_background_revalidation(self):
# Without the `result.stale` hook this family would serve stale for the whole
# 6h grace and never refresh (the revalidate half of stale-while-revalidate).
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
index 6a6276958147..c47cb9b29a01 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin
from unittest import mock
@@ -784,7 +784,7 @@ class TestWebEnsurePrecomputed(BaseTest):
reset_query_tags()
self.team.timezone = tz
with (
- freeze_time("2026-08-20T12:00:00Z"),
+ time_machine.travel("2026-08-20T12:00:00Z", tick=False),
tags_context(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS.value),
):
web_ensure_precomputed(team=self.team, ttl_seconds={"0d": 4 * 3600, "default": 3600}, table=None)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index f0f71dec2814..87946a2d4f6b 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
@@ -3,7 +3,7 @@ from typing import Any, Optional
from zoneinfo import ZoneInfo
import pytest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -63,7 +63,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -120,7 +120,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
custom_event: Optional[str] = None,
bounce_rate_mode: Optional[BounceRatePageViewMode] = BounceRatePageViewMode.COUNT_PAGEVIEWS,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
modifiers = HogQLQueryModifiers(
sessionTableVersion=session_table_version, bounceRatePageViewMode=bounce_rate_mode
)
@@ -145,7 +145,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
self._seed_ssr_poisoned_session()
def visitors_for_paid_search(flag_on):
- with self._patch_first_pageview_flag(flag_on), freeze_time(self.QUERY_TIMESTAMP):
+ with self._patch_first_pageview_flag(flag_on), time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = WebOverviewQuery(
dateRange=DateRange(date_from="2024-06-01", date_to="2024-06-30"),
properties=[
@@ -779,7 +779,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
assert conversion_rate.previous is None
assert conversion_rate.changeFromPreviousPct is None
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_it_should_use_preaggregated_tables_with_fixed_dates_and_no_other_filters(self):
query = WebOverviewQuery(
dateRange=DateRange(date_from="2023-11-01", date_to="2023-11-30"),
@@ -791,7 +791,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
pre_agg_builder.can_use_preaggregated_tables(), "Should use pre-aggregated tables for historical data"
)
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_can_use_preaggregated_tables_with_current_date(self):
today = datetime.now(UTC).date().isoformat()
query = WebOverviewQuery(
@@ -805,7 +805,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
"Should use pre-aggregated tables when date range includes current date (using UNION ALL with hourly tables)",
)
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_cannot_use_preaggregated_tables_with_unsupported_properties(self):
query = WebOverviewQuery(
dateRange=DateRange(date_from="2023-11-01", date_to="2023-11-30"),
@@ -818,7 +818,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
"Should not use pre-aggregated tables with unsupported properties",
)
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_can_use_preaggregated_tables_with_conversion_goal(self):
query = WebOverviewQuery(
dateRange=DateRange(date_from="2023-11-01", date_to="2023-11-30"),
@@ -831,7 +831,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
pre_agg_builder.can_use_preaggregated_tables(), "Should use pre-aggregated tables with conversion goal"
)
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_can_use_preaggregated_tables_with_supported_properties(self):
query = WebOverviewQuery(
dateRange=DateRange(date_from="2023-11-01", date_to="2023-11-30"),
@@ -843,7 +843,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
pre_agg_builder.can_use_preaggregated_tables(), "Should use pre-aggregated tables with supported properties"
)
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_can_use_preaggregated_tables_with_channel_type_filter(self):
query = WebOverviewQuery(
dateRange=DateRange(date_from="2023-11-01", date_to="2023-11-30"),
@@ -853,7 +853,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
pre_agg_builder = runner.preaggregated_query_builder
assert pre_agg_builder.can_use_preaggregated_tables()
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
@snapshot_clickhouse_queries
def test_web_overview_with_channel_type_filter_execution(self):
query = WebOverviewQuery(
@@ -865,7 +865,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
assert runner.preaggregated_query_builder.can_use_preaggregated_tables()
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_preaggregated_queries_use_utc_filtering(self):
# Set team timezone to something other than UTC
self.team.timezone = "America/New_York" # UTC-5 (or UTC-4 during DST)
@@ -1041,7 +1041,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
("last_7_days_by_hour", "-7d", IntervalType.HOUR),
]
)
- @freeze_time("2024-05-16T14:20:00Z")
+ @time_machine.travel("2024-05-16T14:20:00Z", tick=False)
def test_compare_window_is_sized_to_the_elapsed_current_period(
self, _name: str, date_from: str, interval: IntervalType
) -> None:
@@ -1130,7 +1130,7 @@ class TestWebOverviewNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
("user_a", s2, ["2025-01-11T09:00:00Z"]),
("user_b", s3, ["2025-01-12T12:00:00Z", "2025-01-12T12:00:30Z"]),
]:
- with freeze_time(timestamps[0]):
+ with time_machine.travel(timestamps[0], tick=False):
_create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
for ts in timestamps:
_create_event(
@@ -1163,7 +1163,7 @@ class TestWebOverviewNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
self._create_pageviews()
kwargs = {"compareFilter": CompareFilter(compare=True)} if compare else {}
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
fast_runner = self._make_runner(**kwargs)
assert fast_runner.should_skip_session_join
@@ -1234,7 +1234,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
("user_a", s2, [("/docs", "2025-01-11T09:00:00Z")]),
("user_b", s3, [("/pricing", "2025-01-12T12:00:00Z"), ("/pricing", "2025-01-12T12:00:30Z")]),
]:
- with freeze_time(path_timestamps[0][1]):
+ with time_machine.travel(path_timestamps[0][1], tick=False):
_create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
for pathname, ts in path_timestamps:
_create_event(
@@ -1275,7 +1275,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
self._create_pageviews()
kwargs = {"compareFilter": CompareFilter(compare=True)} if compare else {}
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
fast_runner = self._make_runner(**kwargs)
assert fast_runner.should_use_session_id_set
@@ -1382,7 +1382,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
]
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
fast_runner = self._make_runner(filterTestAccounts=True)
assert fast_runner.should_use_session_id_set
@@ -1397,7 +1397,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
assert not runner.should_use_session_id_set
def test_session_id_set_pushes_id_filter_below_session_aggregation(self):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
runner = self._make_runner()
context = HogQLContext(
@@ -1432,7 +1432,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
calls.append((kwargs.get("query_type"), kwargs.get("modifiers")))
return execute_hogql_query(*args, **kwargs)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
with patch(
"products.web_analytics.backend.hogql_queries.web_overview.execute_hogql_query",
@@ -1455,7 +1455,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
calls.append(kwargs.get("query_type"))
return execute_hogql_query(*args, **kwargs)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
# The preflight executes from the shared base module; the main
# query from the runner module — both must be intercepted.
@@ -1490,7 +1490,7 @@ class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
calls.append(kwargs.get("query_type"))
return execute_hogql_query(*args, **kwargs)
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
with patch(
"products.web_analytics.backend.hogql_queries.web_analytics_query_runner.SESSION_ID_SET_MAX_MATCHING_SESSIONS",
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py
index 9dc318ad18c7..cdd947def1ba 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from posthog.schema import DashboardFilter, DateRange, EventPropertyFilter, WebOverviewQuery
@@ -42,7 +42,7 @@ class TestWebOverviewDashboardFilters(ClickhouseTestMixin, APIBaseTest):
def test_dashboard_filter_with_existing_properties_executes(self):
s1 = str(uuid7("2023-12-10"))
- with freeze_time("2023-12-10"):
+ with time_machine.travel("2023-12-10", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={})
_create_event(
team=self.team,
@@ -61,7 +61,7 @@ class TestWebOverviewDashboardFilters(ClickhouseTestMixin, APIBaseTest):
DashboardFilter(properties=[EventPropertyFilter(key="$browser", value="Chrome", operator="exact")])
)
- with freeze_time("2023-12-15"):
+ with time_machine.travel("2023-12-15", tick=False):
response = runner.calculate()
assert response.results is not None
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
index a0b88fbdc39b..277cefc2417c 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
@@ -2,7 +2,7 @@ import uuid
from datetime import UTC, datetime
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -102,7 +102,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def _run(self, query: WebOverviewQuery):
return WebOverviewQueryRunner(team=self.team, query=query).calculate()
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_unfiltered_round_trip_creates_precompute_job(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -116,7 +116,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"Suspected read-after-write visibility on Distributed table, but global "
"insert_distributed_sync=1 is already set in users-dev.xml. Root cause under investigation."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_result_matches_raw_result(self):
"""Run the same query with and without the lazy path enabled, assert results match."""
self._seed_two_sessions()
@@ -145,7 +145,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_views == raw_views, f"views mismatch: lazy={lazy_views}, raw={raw_views}"
assert lazy_sessions == raw_sessions, f"sessions mismatch: lazy={lazy_sessions}, raw={raw_sessions}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_host_filter_gets_distinct_cache_entry(self):
self._seed_two_sessions()
host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
@@ -165,7 +165,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"got overlap: {unfiltered_jobs & filtered_jobs}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_distinct_host_values_get_distinct_cache_entries(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -188,7 +188,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"different $host values must produce distinct cache keys, got overlap: {example_jobs & other_jobs}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_property_falls_through(self):
# Session and cohort filters fall through — precompute only serves event/person
# filters, since the live path applies session/cohort filters differently.
@@ -203,7 +203,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sampling_falls_through(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -211,7 +211,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_disabled_team_falls_through(self):
# Both gates closed: org feature flag off AND query opt-in not set.
self._seed_two_sessions()
@@ -219,7 +219,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
# `query.useWebAnalyticsPrecompute=True` BUT the
# `web-analytics-precompute-toggle` feature flag is off. Should
@@ -229,7 +229,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_org_flag_alone_falls_through_when_query_not_opted_in(self):
# Org feature flag is on BUT the query param is not set (the team hasn't
# enabled the "Allow precompute" toggle in the ScenePanel). Should fall
@@ -240,7 +240,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_cache_hit_on_second_call(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -270,7 +270,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"second run dropped some first-run READY jobs. first: {first_run_summary}, second: {second_run_summary}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_compare_to_period_reuses_cache(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -284,7 +284,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# it should reuse existing jobs and not multiply them.
assert no_compare_jobs.issubset(after_compare_jobs)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_compare_to_period_returns_real_previous_values(self):
"""Regression: ensure compare-period metrics come from real precomputed
previous-period data, not 0/NaN. The bug surfaced when the lazy path
@@ -348,7 +348,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"above @parameterized.expand, so the parameterized variants kept running and failing. "
"Root cause under investigation."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_result_matches_raw_for_whole_hour_timezones(self, _name: str, team_tz: str) -> None:
"""Whole-hour-offset teams must produce the same metrics through the lazy and raw paths."""
self.team.timezone = team_tz
@@ -369,7 +369,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
lazy_values = [(r.key, r.value) for r in lazy_response.results]
assert lazy_values == raw_values, f"lazy/raw mismatch for {team_tz}: raw={raw_values}, lazy={lazy_values}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_half_hour_offset_timezone_falls_through(self):
# IST is UTC+5:30 — hourly UTC buckets can't represent the team-local
# midnight, so the gate must refuse.
@@ -383,7 +383,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# --- Group B: gate strictness -------------------------------------------
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_uuid_session_mode_falls_through(self):
# `events.$session_id_uuid` would produce `uniqState(UUID)` which the
# `(uniq, String)` column rejects non-retryably. Gate must refuse.
@@ -395,7 +395,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_window_over_max_days_falls_through(self):
# 365 days >> MAX_PRECOMPUTE_DAYS — gate refuses to avoid spawning
# hundreds of daily INSERT jobs in one request.
@@ -411,7 +411,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"Flaky on CI since #59075 — same intermittent empty-result pattern as the other "
"round-trip tests in this file. Missed by #59614. Root cause under investigation."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_just_after_window_start_attributed_correctly(self):
# Forward-only pad regression: a session starting near the leading edge
# of a daily UTC bucket must still aggregate its full set of events.
@@ -441,7 +441,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_values == raw_values, f"forward-only pad parity broken: raw={raw_values}, lazy={lazy_values}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_compare_period_falls_back_when_previous_not_ready(self):
# If the previous-period precompute hasn't reached READY across all jobs,
# we must not read — the read would silently return 0/NaN for `prev_*`
@@ -474,7 +474,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"Flaky on CI since #59075 — same intermittent empty-result pattern as the other "
"round-trip tests in this file. Root cause under investigation."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_recomputation_picks_up_late_events_changing_bounce_and_duration(self):
# After a late event arrives, the next precompute run (cache invalidated
# via job deletion = simulated TTL expiry) must reflect the new
@@ -555,7 +555,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"recomputed lazy != raw for {metric}: lazy={second_metrics[metric]}, raw={raw_metrics[metric]}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_falls_back_when_current_period_not_ready(self):
# Symmetric to the previous test: if the current-period precompute
# hasn't reached READY, the read would scan empty buckets. Fall back.
@@ -577,7 +577,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# --- Group D: enrolled teams (arbitrary filters) ----------------------------------------
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_creates_job_for_multi_non_host_filter(self):
# Filters the old restriction rejected (multiple, non-`$host`, non-`exact`)
# precompute fine for any enrolled team.
@@ -590,7 +590,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(self._build_query(properties=props))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_distinct_filters_get_distinct_cache_entries(self):
self._seed_two_sessions()
chrome = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]
@@ -608,7 +608,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"distinct filter values must produce distinct cache keys, got overlap: {chrome_hashes & firefox_hashes}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_untouched_toggle_creates_job(self):
# Enrolled teams default to opt-out: an untouched toggle (None) still
# precomputes.
@@ -619,14 +619,14 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(query)
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_explicit_opt_out_falls_through(self):
self._seed_two_sessions()
with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):
self._run(self._build_query(opt_in_precompute=False))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stale_served_enqueues_background_revalidation(self):
# Without the `result.stale` hook this family would serve stale for the whole
# 6h grace and never refresh (the revalidate half of stale-while-revalidate).
@@ -735,7 +735,7 @@ class TestWebOverviewSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):
assert template is mod.JOIN_INSERT_QUERY_TEMPLATE
assert modifiers is None
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_filtered_insert_matches_join_insert(self):
"""The id-set insert must store the same finalized metrics as the join insert
for the same filtered key — the whole point of the shape swap. Compares the
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py
index 0ebf592288de..40867472f339 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py
@@ -1,7 +1,7 @@
import math
from datetime import datetime
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from posthog.schema import CompareFilter, DateRange, WebOverviewQuery
@@ -27,7 +27,7 @@ class TestWebOverviewStateTransform(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -67,7 +67,7 @@ class TestWebOverviewStateTransform(ClickhouseTestMixin, APIBaseTest):
compare: bool = False,
):
"""Run the web overview query and return both original and state-transformed results."""
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = WebOverviewQuery(
dateRange=DateRange(date_from=date_from, date_to=date_to),
properties=[],
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py
index 4ecf1154c412..9826d58d97e2 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py
@@ -1,5 +1,5 @@
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -241,7 +241,7 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# read-after-write visibility issue is investigated.
# ----------------------------------------------------------------------
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_round_trip_creates_precompute_job(self):
self._seed_frustration_events()
with self._enable_lazy():
@@ -255,7 +255,7 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"lazy path returns empty rows despite READY job. Re-enable once the "
"read-after-write visibility issue tracked there is resolved."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_response_matches_live(self):
"""Compare rage / dead / errors per path between the live and lazy paths."""
self._seed_frustration_events()
@@ -291,7 +291,7 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
}
return out
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stale_served_enqueues_background_revalidation(self):
# Without the `result.stale` hook this family would serve stale for the whole
# 6h grace and never refresh (the revalidate half of stale-while-revalidate).
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
index 3c71ec0083e3..ccb35a514c4e 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -195,7 +195,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def _job_count(self) -> int:
return PreaggregationJob.objects.filter(team_id=self.team.pk).count()
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_round_trip_creates_precompute_job(self):
self._seed()
with self._enable_lazy():
@@ -204,7 +204,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() > 0, "expected at least one precompute job to be created"
@parameterized.expand(PARITY_BREAKDOWNS)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_matches_raw(self, _name: str, breakdown_by: WebStatsBreakdown):
self._seed()
@@ -222,7 +222,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy == raw, f"lazy/raw mismatch for {breakdown_by}: raw={raw}, lazy={lazy}"
@parameterized.expand(PARITY_BREAKDOWNS)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_matches_raw_with_compare(self, _name: str, breakdown_by: WebStatsBreakdown):
self._seed()
# Previous period: one extra session for u1 in the 7 days before Jan 1.
@@ -256,7 +256,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("device_type", WebStatsBreakdown.DEVICE_TYPE, "$device_type"),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_keeps_null_breakdown_rows(self, _name: str, breakdown_by: WebStatsBreakdown, null_prop: str):
self._seed()
# One extra session whose breakdown property is absent -> a genuine NULL that
@@ -298,7 +298,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"{breakdown_by}: lazy keeps_null={lazy_keeps_null} but raw keeps_null={live_keeps_null}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_viewport_breakdown_lazy_runs(self):
# The raw VIEWPORT query compares viewport tuple elements against 0,
# which needs numeric properties the harness does not materialize — so
@@ -311,7 +311,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) > 0
assert all(isinstance(row[0], tuple) and len(row[0]) == 2 for row in response.results)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_host_filter_gets_distinct_cache_entry(self):
self._seed()
host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
@@ -327,7 +327,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert unfiltered and filtered
assert unfiltered.isdisjoint(filtered), "host filter must produce a distinct cache key"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_host_filter_lazy_matches_raw(self):
self._seed()
host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
@@ -338,7 +338,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy == raw, f"host-filtered lazy/raw mismatch: raw={raw}, lazy={lazy}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_distinct_breakdowns_get_distinct_cache_entries(self):
self._seed()
with self._enable_lazy():
@@ -358,7 +358,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("scroll_depth", {"include_scroll_depth": True}),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_extra_metric_falls_through(self, _name: str, kwargs: dict):
self._seed()
with self._enable_lazy():
@@ -373,7 +373,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("exit_click", WebStatsBreakdown.EXIT_CLICK),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_high_cardinality_breakdown_falls_through(self, _name: str, breakdown_by: WebStatsBreakdown):
# Page/path breakdowns are intentionally excluded — handled by the
# dedicated paths lazy precompute. They fall through to raw here.
@@ -383,7 +383,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_language_breakdown_precomputes_and_groups_by_prefix(self):
# LANGUAGE precomputes: the INSERT stores the full `$browser_language`
# ("en-US"/"en-GB"); the read groups by the "en" prefix and labels it with
@@ -398,7 +398,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._metrics(response) == [("en-US", (2.0, None), (4.0, None))]
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_language_breakdown_keeps_missing_value(self):
# The raw LANGUAGE query keeps rows with no `$browser_language`
# (outer_where_breakdown is None for LANGUAGE) so the tile total stays
@@ -430,7 +430,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._metrics(lazy_response) == raw
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_language_breakdown_three_part_tag_matches_raw(self):
# 3-component BCP-47 tags (e.g. `zh-Hans-CN`) must split the same way as the
# raw query, which uses `splitByChar('-', ..., 2)`. Assert parity against the
@@ -462,7 +462,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._metrics(lazy_response) == raw, f"raw={raw} lazy={self._metrics(lazy_response)}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_conversion_goal_falls_through(self):
self._seed()
with self._enable_lazy():
@@ -472,7 +472,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sampling_falls_through(self):
self._seed()
with self._enable_lazy():
@@ -480,7 +480,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_half_hour_offset_timezone_falls_through(self):
self.team.timezone = "Asia/Kolkata"
self.team.save()
@@ -490,7 +490,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
# Direct user-facing calculate (no warm pass): warming triggers bypass the
# org flag by design, so the helper's warm pre-pass would create jobs here.
@@ -499,7 +499,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_org_flag_alone_falls_through_when_query_not_opted_in(self):
self._seed()
with self._enable_lazy():
@@ -508,7 +508,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0
@parameterized.expand([("utc", "UTC"), ("pacific", "America/Los_Angeles"), ("tokyo", "Asia/Tokyo")])
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_matches_raw_for_whole_hour_timezones(self, _name: str, team_tz: str):
self.team.timezone = team_tz
self.team.save()
@@ -520,7 +520,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy == raw, f"lazy/raw mismatch for {team_tz}: raw={raw}, lazy={lazy}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_pagination_lazy_matches_raw(self):
self._seed()
query = self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)
@@ -536,7 +536,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_response.limit == raw_response.limit
assert lazy_response.offset == raw_response.offset
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_recomputation_picks_up_late_events(self):
self._seed()
with self._enable_lazy():
@@ -568,7 +568,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert any(row[0] == "Safari" for row in second), "recomputed result should include the late pageview"
assert first != second
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_crossing_midnight_lazy_matches_raw(self):
# A session whose pageviews straddle a UTC day boundary. Session-start
# bucketing attributes the whole session to its start hour; the forward
@@ -602,7 +602,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
safari = next(r for r in raw if r[0] == "Safari")
assert safari[2][0] == 2, f"expected 2 Safari views, got {safari}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_ui_fill_fraction_lazy_matches_raw(self):
# Column index 3 is `context.columns.ui_fill_fraction` — recomputed in
# Python on the lazy path, so assert parity with the raw SQL window fn.
@@ -617,7 +617,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
for raw_value, lazy_value in zip(raw_fill, lazy_fill):
assert abs(raw_value - lazy_value) < 1e-9, f"ui_fill_fraction mismatch: raw={raw_fill}, lazy={lazy_fill}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_views_desc_orderby_lazy_matches_raw(self):
# Forwarding the user's orderBy through to ClickHouse: sorting by views
# must beat the silent visitors fallback the original PR relied on.
@@ -640,7 +640,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("average_scroll", WebAnalyticsOrderByFields.AVERAGE_SCROLL_PERCENTAGE),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_unsupported_orderby_falls_through(self, _name: str, field: WebAnalyticsOrderByFields):
# Fields the precompute schema can't serve must skip lazy entirely, not
# silently rewrite the sort to visitors.
@@ -655,7 +655,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# we're guarding against is the lazy path silently serving with a rewritten sort.
assert response.preComputeStrategy != WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_pagination_page_two_lazy_matches_raw(self):
# The PR's original code sorted + sliced in Python from an arbitrary
# `LIMIT 100` cut. With SQL pagination, page 2 must be a contiguous
@@ -681,7 +681,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
if offset < len(raw_full):
assert self._metrics(lazy_resp)[0] == raw_full[offset], "lazy page row must match unpaginated position"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_high_cardinality_utm_source_orders_in_sql(self):
# Veria's concern: with N>>page_size distinct UTM values, the read used
# to materialize all rows + paginate in Python. With SQL pagination the
@@ -724,7 +724,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
visitors = [row[1][0] for row in lazy_metrics]
assert visitors == sorted(visitors, reverse=True), f"first page not ordered by visitors desc: {visitors}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stale_served_enqueues_background_revalidation(self):
# Without the `result.stale` hook this family would serve stale for the whole
# 6h grace and never refresh (the revalidate half of stale-while-revalidate).
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
index 279299cc8f1c..f4f9bdd07fb8 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
@@ -2,7 +2,7 @@ import uuid
import dataclasses
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -180,7 +180,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
reset_query_tags()
assert response.preComputeStale is expected
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_unfiltered_round_trip_creates_precompute_job(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -196,7 +196,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"Suspected read-after-write visibility on Distributed table, but global "
"insert_distributed_sync=1 is already set in users-dev.xml. Root cause under investigation."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_result_matches_raw_result(self):
"""Compare visitors / views / bounce_rate per path between the raw and lazy paths."""
self._seed_two_sessions()
@@ -239,7 +239,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"assertion KeyErrors on /a. Same root cause as test_lazy_result_matches_raw_result. "
"Re-enable when the read-after-write visibility issue is resolved."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_bounce_rate_attributed_to_entry_path_only(self):
"""Bounce rate for /a should reflect sessions that ENTERED on /a, not all sessions that touched it.
@@ -259,7 +259,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# with single-pageview session (bounce=1). avg = 0.5.
assert abs(metrics["/a"]["bounce_rate"] - 0.5) < 0.01, f"/a bounce should be 0.5, got {metrics['/a']}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_host_filter_gets_distinct_cache_entry(self):
self._seed_two_sessions()
host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
@@ -278,7 +278,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"got overlap: {unfiltered_jobs & filtered_jobs}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_distinct_include_host_values_get_distinct_cache_entries(self):
self._seed_two_sessions()
with self._enable_lazy():
@@ -293,7 +293,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"includeHost on/off must produce distinct cache keys, got overlap: {no_host_hashes & with_host_hashes}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_property_filter_falls_through(self):
with self._enable_lazy():
self._run(
@@ -305,25 +305,25 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
)
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sampling_falls_through(self):
with self._enable_lazy():
self._run(self._build_query(sampling=WebAnalyticsSampling(enabled=True)))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
# `query.useWebAnalyticsPrecompute=True` BUT the rollout flag is off — refuse.
self._run(self._build_query(opt_in_precompute=True))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_org_flag_alone_falls_through_when_query_not_opted_in(self):
with self._enable_lazy():
self._run(self._build_query(opt_in_precompute=False))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_initial_page_breakdown_uses_lazy_path(self):
# INITIAL_PAGE reuses the same precompute table: feeding
# `_entry_breakdown_value_expr` into both placeholders collapses the
@@ -336,7 +336,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(self._build_query(breakdown_by=WebStatsBreakdown.INITIAL_PAGE))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_page_and_initial_page_get_distinct_cache_entries(self):
# Defence-in-depth: a team toggling between Path / Entry path tabs must
# produce different precompute jobs. If the AST collapses (e.g., a
@@ -358,19 +358,19 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"got overlap: {page_hashes & initial_page_hashes}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_missing_include_bounce_rate_falls_through(self):
with self._enable_lazy():
self._run(self._build_query(include_bounce_rate=False))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_avg_time_on_page_falls_through(self):
with self._enable_lazy():
self._run(self._build_query(include_avg_time_on_page=True))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_scroll_depth_falls_through(self):
with self._enable_lazy():
self._run(self._build_query(include_scroll_depth=True))
@@ -383,7 +383,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
]
self.team.save()
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_path_cleaning_uses_lazy_path(self):
# Path cleaning is baked into the precompute at INSERT time, so a
# path-cleaning query is still lazy-eligible and creates a precompute job.
@@ -402,7 +402,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert "replaceRegexpAll" in repr(cleaned), f"{fn.__name__} must bake cleaning into the insert"
assert "replaceRegexpAll" not in repr(raw), f"{fn.__name__} must store raw paths when cleaning is off"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_path_cleaning_gets_distinct_cache_entry(self):
# Cleaning is part of the insert AST now, so doPathCleaning on/off map to
# distinct query_hashes / jobs (a rules change spawns a fresh job).
@@ -440,7 +440,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
else:
assert expected_metric in repr(expr)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sort_key_gets_distinct_cache_entry(self):
# The cap metric is in the insert AST, so different sort keys map to distinct
# capped jobs. This also exercises that the capped insert template parses/builds.
@@ -528,7 +528,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"the top-K rank must partition by the day bucket, got: {[w.partition_by for w in rank_windows]}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_uuid_session_mode_falls_through(self):
query = self._build_query()
query.modifiers = HogQLQueryModifiers(sessionsV2JoinMode=SessionsV2JoinMode.UUID)
@@ -536,7 +536,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(query)
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_window_over_max_days_falls_through(self):
with self._enable_lazy():
self._run(self._build_query(date_from="2023-01-01", date_to="2024-01-07"))
@@ -549,7 +549,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("tokyo", "Asia/Tokyo"),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_result_matches_raw_for_whole_hour_timezones(self, _name: str, team_tz: str) -> None:
# Same flakiness as test_lazy_result_matches_raw_result — lazy returns
# empty rows despite READY job on CI. Skipped until the read-after-write
@@ -577,7 +577,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
lazy_by_path = self._collect_metrics(lazy_response.results)
assert lazy_by_path == raw_by_path, f"lazy/raw mismatch for {team_tz}: raw={raw_by_path}, lazy={lazy_by_path}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_half_hour_offset_timezone_falls_through(self):
self.team.timezone = "Asia/Kolkata"
self.team.save()
@@ -586,7 +586,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(self._build_query())
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_falls_back_when_current_period_not_ready(self):
from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import (
execute_lazy_precomputed_read,
@@ -606,7 +606,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert result is None, f"expected fall-back to raw when current precompute not ready, got {result!r}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_compare_period_falls_back_when_previous_not_ready(self):
from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import (
execute_lazy_precomputed_read,
@@ -641,7 +641,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("conversion_rate", WebAnalyticsOrderByFields.CONVERSION_RATE),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_unsupported_orderby_falls_through(self, _name: str, field: WebAnalyticsOrderByFields) -> None:
# Fields the lazy response can't sort on must not silently rewrite to
# `visitors` — refuse and let the raw path serve the request.
@@ -666,7 +666,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"`@parameterized.expand` so the expanded variants inherit the skip — putting "
"it above the expand decorator lets the variants slip through (see #59614)."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_supported_orderby_is_eligible(
self,
_name: str,
@@ -682,7 +682,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"CI-only flake since #59075 (passes locally on the CI ClickHouse image) — "
"same lazy-read read-after-write issue as the parity tests."
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_compare_period_only_populated_returns_real_previous_bounce(self):
"""When current period has no events but previous does, the lazy path
must produce real previous-period bounce rates (not NaN/None) and
@@ -726,7 +726,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
}
return out
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_creates_job_for_multi_non_host_filter(self):
# Filters the old restriction rejected (multiple, non-`$host`, non-`exact`)
# precompute fine for any enrolled team.
@@ -739,7 +739,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(self._build_query(properties=props))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_distinct_filters_get_distinct_cache_entries(self):
self._seed_two_sessions()
chrome = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]
@@ -757,7 +757,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"distinct filter values must produce distinct cache keys, got overlap: {chrome_hashes & firefox_hashes}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_untouched_toggle_creates_job(self):
# Enrolled teams default to opt-out: an untouched toggle (None) still
# precomputes.
@@ -768,7 +768,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(query)
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_enrolled_team_explicit_opt_out_falls_through(self):
self._seed_two_sessions()
with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):
@@ -785,7 +785,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("stale_revalidation", "webAnalyticsStaleRevalidation"),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_ensure_wait_budget_by_trigger(self, _name: str, trigger: str | None) -> None:
from datetime import UTC, datetime
@@ -826,7 +826,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("remainder_passed_to_compare", 2.0, 8.0),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_user_ensure_budget_is_shared_across_compare_periods(
self, _name: str, first_ensure_seconds: float, expected_compare_budget: float | None
) -> None:
@@ -866,7 +866,7 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert ensure_mock.call_args_list[1].kwargs["wait_budget_seconds"] == expected_compare_budget
@parameterized.expand([("no_compare", False), ("compare", True)])
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_read_scan_is_pruned_to_requested_windows(self, _name: str, compare: bool) -> None:
from datetime import UTC, datetime
@@ -1021,7 +1021,7 @@ class TestWebStatsPathsSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):
assert "session_id_v7 IN" not in insert_query
assert modifiers is None
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_filtered_insert_matches_join_insert(self):
"""The pruned-join insert must store the same finalized per-path metrics as the
plain join insert for the same filtered key. The fixture carries the divergence
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py
index 6eb3f3ecad27..c64caad4fee4 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queries
from unittest.mock import MagicMock
@@ -33,7 +33,7 @@ from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_ba
@snapshot_clickhouse_queries
class TestWebStatsPreAggregated(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
- with freeze_time("2024-01-01T09:00:00Z"):
+ with time_machine.travel("2024-01-01T09:00:00Z", tick=False):
sessions = [str(uuid7("2024-01-01")) for _ in range(20)]
for i in range(20):
@@ -506,7 +506,7 @@ class TestWebStatsPreAggregated(WebAnalyticsPreAggregatedTestBase):
)
def test_include_host_concatenates_host_and_path(self, breakdown):
self._truncate_preaggregated_tables()
- with freeze_time("2024-01-02T09:00:00Z"):
+ with time_machine.travel("2024-01-02T09:00:00Z", tick=False):
sessions = [str(uuid7("2024-01-02")) for _ in range(3)]
for i in range(3):
@@ -631,7 +631,7 @@ class TestWebStatsPreAggregated(WebAnalyticsPreAggregatedTestBase):
)
def test_include_host_false_returns_path_only(self, breakdown):
self._truncate_preaggregated_tables()
- with freeze_time("2024-01-02T09:00:00Z"):
+ with time_machine.travel("2024-01-02T09:00:00Z", tick=False):
sessions = [str(uuid7("2024-01-02")) for _ in range(2)]
for i in range(2):
@@ -689,7 +689,7 @@ class TestWebStatsPreAggregated(WebAnalyticsPreAggregatedTestBase):
def test_include_host_page_breakdown_groups_same_paths_separately(self):
self._truncate_preaggregated_tables()
- with freeze_time("2024-01-02T09:00:00Z"):
+ with time_machine.travel("2024-01-02T09:00:00Z", tick=False):
sessions = [str(uuid7("2024-01-02")) for _ in range(3)]
for i in range(3):
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py
index b089849dc9ca..26c86bb5b986 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from posthog.schema import (
@@ -24,7 +24,7 @@ from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_ba
class TestWebStatsPreAggregatedChannelTypes(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
- with freeze_time("2024-01-01T09:00:00Z"):
+ with time_machine.travel("2024-01-01T09:00:00Z", tick=False):
sessions = [str(uuid7("2024-01-01")) for _ in range(21)]
for i in range(21):
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index 52ada48b6e33..4e8fb5f84c26 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -3,7 +3,7 @@ from collections import defaultdict
from typing import Any, Optional
import unittest
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -127,7 +127,7 @@ class TestWebStatsTableQueryRunner(
def _create_events(self, data, event="$pageview"):
person_result = []
for id, timestamps in data:
- with freeze_time(timestamps[0][0]):
+ with time_machine.travel(timestamps[0][0], tick=False):
person_result.append(
_create_person(
team_id=self.team.pk,
@@ -169,7 +169,7 @@ class TestWebStatsTableQueryRunner(
def _create_pageviews(self, distinct_id: str, list_page_view_properties: list[PageViewProperties]):
person_time = list_page_view_properties[0].timestamp
- with freeze_time(person_time):
+ with time_machine.travel(person_time, tick=False):
person_result = _create_person(
team_id=self.team.pk,
distinct_ids=[distinct_id],
@@ -241,7 +241,7 @@ class TestWebStatsTableQueryRunner(
bounce_rate_mode: Optional[BounceRatePageViewMode] = BounceRatePageViewMode.COUNT_PAGEVIEWS,
orderBy=None,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
modifiers = HogQLQueryModifiers(
sessionTableVersion=session_table_version, bounceRatePageViewMode=bounce_rate_mode
)
@@ -2156,7 +2156,7 @@ class TestWebStatsTableQueryRunner(
assert [row[0] for row in response.results] == ["/foo", "/bar"]
- @freeze_time("2023-12-15T12:00:00Z")
+ @time_machine.travel("2023-12-15T12:00:00Z", tick=False)
def test_can_use_preaggregated_tables_with_channel_type_filter(self):
query = WebStatsTableQuery(
dateRange=DateRange(date_from="2023-11-01", date_to="2023-11-30"),
@@ -2834,7 +2834,7 @@ class TestWebStatsTableNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
("user_a", s2, [("/pricing", "2025-01-11T09:00:00Z")]),
("user_b", s3, [("/", "2025-01-12T12:00:00Z"), ("/", "2025-01-12T12:00:30Z")]),
]:
- with freeze_time(path_timestamps[0][1]):
+ with time_machine.travel(path_timestamps[0][1], tick=False):
_create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
for pathname, ts in path_timestamps:
_create_event(
@@ -2873,7 +2873,7 @@ class TestWebStatsTableNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
def test_no_join_paths_results_match_join_path(self, include_avg_time: bool):
self._create_pageviews()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
fast_runner = self._make_runner(includeAvgTimeOnPage=include_avg_time)
assert fast_runner.query_strategy().startswith("stats_table_no_join_path_bounce")
@@ -2960,9 +2960,9 @@ class TestWebStatsTableSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
# the same distinct_id mints a second person, and events then carry
# whichever person id existed at creation time, manufacturing the known
# per-event vs per-session visitor-count drift inside a single session.
- with freeze_time("2025-01-10T09:00:00Z"):
+ with time_machine.travel("2025-01-10T09:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_a"])
- with freeze_time("2025-01-12T09:00:00Z"):
+ with time_machine.travel("2025-01-12T09:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_b"])
for distinct_id, session_id, browser, path_timestamps in [
("user_a", s1, "Chrome", [("/", "2025-01-10T10:00:00Z"), ("/pricing", "2025-01-10T10:05:00Z")]),
@@ -3035,7 +3035,7 @@ class TestWebStatsTableSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
self._create_pageviews()
properties = [EventPropertyFilter(key=key, operator=PropertyOperator.EXACT, value=value)]
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
fast_runner = self._make_runner(includeAvgTimeOnPage=include_avg_time, properties=properties)
assert fast_runner.query_strategy().startswith("stats_table_session_id_set")
@@ -3103,7 +3103,7 @@ class TestWebStatsTableSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
def test_session_id_set_paths_pushes_id_filter_below_session_aggregation(
self, _name: str, key: str, value: str, expected_global_in: int
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
runner = self._make_runner(
properties=[EventPropertyFilter(key=key, operator=PropertyOperator.EXACT, value=value)]
@@ -3121,7 +3121,7 @@ class TestWebStatsTableSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
def test_session_id_set_paths_executes_with_pushdown_modifier_and_tag(self):
self._create_pageviews()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
runner = self._make_runner()
original_execute = runner.paginator.execute_hogql_query
@@ -3141,7 +3141,7 @@ class TestWebStatsTableSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
def test_session_id_set_paths_falls_back_to_join_when_filter_is_unselective(self):
self._create_pageviews()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
with patch(
"products.web_analytics.backend.hogql_queries.web_analytics_query_runner.SESSION_ID_SET_MAX_MATCHING_SESSIONS",
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
index e43c4e9d26f4..7404e62cbeb7 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import _create_event, _create_person, flush_persons_and_events
from posthog.schema import (
@@ -23,7 +23,7 @@ from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_ba
class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self, user_prefix="user"):
- with freeze_time("2024-01-01T09:00:00Z"):
+ with time_machine.travel("2024-01-01T09:00:00Z", tick=False):
_create_person(team_id=self.team.pk, distinct_ids=[f"{user_prefix}1"])
_create_person(team_id=self.team.pk, distinct_ids=[f"{user_prefix}2"])
@@ -82,7 +82,7 @@ class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBas
)
sync_execute(f"INSERT INTO web_pre_aggregated_stats {sql}")
- with freeze_time("2024-01-02T00:00:00Z"):
+ with time_machine.travel("2024-01-02T00:00:00Z", tick=False):
modifiers = HogQLQueryModifiers(
sessionTableVersion=SessionTableVersion.V2,
useWebAnalyticsPreAggregatedTables=True,
@@ -172,7 +172,7 @@ class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBas
)
sync_execute(f"INSERT INTO web_pre_aggregated_stats {sql}")
- with freeze_time("2024-01-02T00:00:00Z"):
+ with time_machine.travel("2024-01-02T00:00:00Z", tick=False):
modifiers = HogQLQueryModifiers(
sessionTableVersion=SessionTableVersion.V2,
useWebAnalyticsPreAggregatedTables=True,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py
index 6bec5309296d..fa83831a84b7 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py
@@ -2,7 +2,7 @@ from dataclasses import replace
from datetime import datetime
from zoneinfo import ZoneInfo
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -111,7 +111,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
super().setUp()
PreaggregationJob.objects.filter(team_id=self.team.pk).delete()
# Precompute rows are "born expired" relative to the real ClickHouse
- # clock under freeze_time; stop TTL merges so they survive until read.
+ # clock under the frozen clock; stop TTL merges so they survive until read.
sync_execute("SYSTEM STOP TTL MERGES sharded_web_overview_preaggregated")
def _enable_lazy(self):
@@ -199,7 +199,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("bounce_rate", "avg", "$is_bounce"),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_precompute_matches_live_trends(self, _name: str, math: str, math_property: str | None) -> None:
self._seed()
query = self._build_query(math=math, math_property=math_property)
@@ -220,7 +220,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert pre_series["label"] == live_series["label"]
assert pre_series["action"]["custom_name"] == "My metric"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_compare_period_matches_live_trends(self) -> None:
self._seed()
query = self._build_query(compare=True)
@@ -242,7 +242,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert pre_series["action"]["days"] == live_series["action"]["days"]
assert precomputed.resolved_compare_date_range is not None
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_reuses_overview_precompute_jobs(self) -> None:
# The whole point of the inner-WebOverviewQuery mapping: trends reads
# must find the buckets the overview tile already built, not mint a
@@ -260,7 +260,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == jobs_after_overview
assert sum(precomputed.results[0]["data"]) > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_flag_off_falls_back_to_live_path(self) -> None:
self._seed()
trends_flag_off = patch(
@@ -338,7 +338,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def test_servable_shape_maps_to_metric(self) -> None:
assert trends_precompute_metric(self._build_query()) is WebTrendsMetric.UNIQUE_USERS
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_filter_falls_back(self) -> None:
# Session filters pass the shape gate but the shared eligibility check
# rejects them (the precompute INSERT can't apply them faithfully).
@@ -382,7 +382,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("month", IntervalType.MONTH, "2024-01-01", "2024-01-31"),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_interval_parity_with_live_trends(
self, _name: str, interval: IntervalType, date_from: str, date_to: str
) -> None:
@@ -398,7 +398,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert precomputed.results[0]["days"] == live.results[0]["days"]
assert precomputed.results[0]["labels"] == live.results[0]["labels"]
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_filtered_round_trip_matches_live(self) -> None:
# Filters must flow into the precompute INSERT and back out — if the
# series-level merge in effective_properties or the inner query's
@@ -423,7 +423,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
series_filtered = WebTrendsQueryRunner(team=self.team, query=series_query).calculate()
assert series_filtered.results[0]["data"] == precomputed.results[0]["data"]
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_distinct_id_aggregation_falls_back(self) -> None:
# Vanilla trends counts distinct_ids for these teams while the buckets
# store person-id uniq states — genuinely different numbers.
@@ -436,7 +436,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
WebTrendsQueryRunner(team=self.team, query=self._build_query()).calculate()
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stale_buckets_are_served_and_revalidated_via_overview_family(self) -> None:
# Stale-within-grace buckets must be served (falling back would put
# dashboards on the slow path at every TTL lapse) and the background
@@ -466,7 +466,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert mock_stale.called
assert mock_stale.call_args.kwargs["family"] == "web_overview"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_today_spanning_range_stitches_live_tail(self) -> None:
# A range whose last bucket is "today": settled days come from precompute,
# today comes from the live tail. If the tail merge keyed buckets wrong,
@@ -487,7 +487,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# Settled days were still precomputed — the path did not fully fall back.
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_today_only_range_falls_back_to_live(self) -> None:
# The whole range is the in-progress day, so nothing is settled enough to
# precompute: the path bails to live and mints no precompute jobs.
@@ -503,7 +503,7 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert precomputed.results[0]["data"] == live.results[0]["data"]
assert sum(precomputed.results[0]["data"]) == 1
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_week_interval_zero_fills_full_range(self) -> None:
self._seed()
query = self._build_query(interval=IntervalType.WEEK)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py
index 921183c380e1..8e589f0064bb 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -50,7 +50,7 @@ class TestWebVitalsPathBreakdownQueryRunner(ClickhouseTestMixin, APIBaseTest):
percentile: PropertyMathType = PropertyMathType.P75,
properties=None,
):
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = WebVitalsPathBreakdownQuery(
dateRange=DateRange(date_from=date_from, date_to=date_to),
metric=metric,
@@ -301,7 +301,7 @@ class TestWebVitalsPathBreakdownQueryRunner(ClickhouseTestMixin, APIBaseTest):
]
self.team.save()
- with freeze_time(self.QUERY_TIMESTAMP):
+ with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
query = WebVitalsPathBreakdownQuery(
dateRange=DateRange(date_from="2025-01-08", date_to="2025-01-15"),
metric=WebVitalsMetric.INP,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py
index 81017f4df7ca..fe327fca9088 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -142,7 +142,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def _job_count(self) -> int:
return PreaggregationJob.objects.filter(team_id=self.team.pk).count()
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_round_trip_creates_precompute_job(self):
self._seed()
with self._enable_lazy():
@@ -151,7 +151,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() > 0, "expected at least one precompute job to be created"
@parameterized.expand(PARITY_MATRIX)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_matches_raw_per_metric_percentile(
self, _name: str, metric: WebVitalsMetric, percentile: WebVitalsPercentile
):
@@ -173,7 +173,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
f"value mismatch for {path} {metric}/{percentile}: raw={raw_value}, lazy={lazy_value}"
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_classifies_bands_correctly(self):
self._seed()
with self._enable_lazy():
@@ -182,7 +182,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._band_paths(response, WebVitalsMetricBand.NEEDS_IMPROVEMENTS) == ["/mid"]
assert self._band_paths(response, WebVitalsMetricBand.POOR) == ["/slow"]
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_conversion_goal_falls_through(self):
self._seed()
with self._enable_lazy():
@@ -192,7 +192,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert response.preComputeStrategy != WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sampling_falls_through(self):
self._seed()
with self._enable_lazy():
@@ -207,7 +207,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
("end_misaligned", "2024-01-02T00:00:00", "2024-01-02T12:00:00"),
]
)
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_explicit_sub_day_range_falls_through(self, _name: str, date_from: str, date_to: str):
# Only `explicitDate=True` lets the query date range surface non-midnight
# times; without it, the parser silently truncates to start/end of day.
@@ -222,7 +222,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert response.preComputeStrategy != WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_half_hour_offset_timezone_matches_raw(self):
# Vitals buckets by team-tz day, so half-hour-offset timezones (IST +5:30
# here) align cleanly and don't fall through to raw.
@@ -238,7 +238,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert raw == lazy, f"lazy/raw mismatch in IST: raw={raw}, lazy={lazy}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
# Direct user-facing calculate (no warm pass): warming triggers bypass the
# org flag by design, so the helper's warm pre-pass would create jobs here.
@@ -249,7 +249,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert response.preComputeStrategy != WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_org_flag_alone_falls_through_when_query_not_opted_in(self):
self._seed()
with self._enable_lazy():
@@ -257,7 +257,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert response.preComputeStrategy != WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._job_count() == 0
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_host_filter_gets_distinct_cache_entry(self):
self._seed()
host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
@@ -274,7 +274,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert unfiltered.isdisjoint(filtered), "host filter must produce a distinct cache key"
@parameterized.expand([("utc", "UTC"), ("pacific", "America/Los_Angeles"), ("tokyo", "Asia/Tokyo")])
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_matches_raw_for_whole_hour_timezones(self, _name: str, team_tz: str):
self.team.timezone = team_tz
self.team.save()
@@ -286,7 +286,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert raw == lazy, f"lazy/raw mismatch for {team_tz}: raw={raw}, lazy={lazy}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_returns_at_most_20_per_band(self):
_create_person(team_id=self.team.pk, distinct_ids=["bulk_user"], properties={})
# 25 distinct paths all classifying as "poor" (LCP 6000+).
@@ -310,7 +310,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
poor_items = response.results[0].poor
assert len(poor_items) == 20, f"expected exactly 20 paths in poor band, got {len(poor_items)}"
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_stale_served_enqueues_background_revalidation(self):
# Without the `result.stale` hook this family would serve stale for the whole
# 6h grace and never refresh (the revalidate half of stale-while-revalidate).
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py
index 6ae47e21b0fe..92651c4687c9 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py
@@ -2,7 +2,7 @@ from collections.abc import Iterator
from contextlib import ExitStack, contextmanager
from typing import Any, Optional
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import patch
@@ -203,7 +203,7 @@ class TestWebVitalsTimeseriesLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
finally:
reset_query_tags()
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_precomputed_matches_live_trends(self) -> None:
self._seed()
query = _vitals_query()
@@ -227,7 +227,7 @@ class TestWebVitalsTimeseriesLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert pre_series["data"] == live_series["data"], live_series["action"]["custom_name"]
assert pre_series["action"]["custom_name"] == live_series["action"]["custom_name"]
- @freeze_time("2024-01-15T12:00:00Z")
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_dispatch_routes_only_when_flag_enabled(self) -> None:
query = _vitals_query().model_dump(mode="json")
diff --git a/products/web_analytics/backend/test/test_api.py b/products/web_analytics/backend/test/test_api.py
index 54bb397fd9e1..8263bc477588 100644
--- a/products/web_analytics/backend/test/test_api.py
+++ b/products/web_analytics/backend/test/test_api.py
@@ -1,7 +1,7 @@
from datetime import timedelta
from urllib.parse import urlparse
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import Mock, patch
@@ -50,7 +50,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
return self.ENDPOINT.format(team_id=team_id or self.team.id)
def test_returns_digest_shape(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
_create_pageview(self.team, distinct_id="user_1", url="https://example.com/", timestamp="2025-01-25")
flush_persons_and_events()
@@ -77,7 +77,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
assert "/web" in data["dashboard_url"]
def test_empty_team_returns_zero_metrics(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
response = self.client.get(self._url())
assert response.status_code == status.HTTP_200_OK
@@ -97,7 +97,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
assert response.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)
def test_days_param_respected(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_recent"])
_create_person(team_id=self.team.pk, distinct_ids=["user_old"])
_create_pageview(
@@ -133,13 +133,13 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
]
)
def test_days_param_validation(self, _name, days_value, expected_status):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
response = self.client.get(self._url(), data={"days": days_value})
assert response.status_code == expected_status
def test_compare_false_omits_change(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_current"])
_create_person(team_id=self.team.pk, distinct_ids=["user_prior"])
_create_pageview(
@@ -165,7 +165,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
assert data[metric]["change"] is None, metric
def test_compare_true_populates_change_when_prior_period_has_data(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["cur_1"])
_create_person(team_id=self.team.pk, distinct_ids=["cur_2"])
_create_person(team_id=self.team.pk, distinct_ids=["cur_3"])
@@ -196,7 +196,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
assert visitors["change"]["percent"] == 200
def test_top_pages_limited_to_five(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
for idx in range(7):
distinct_id = f"page_user_{idx}"
_create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
@@ -219,7 +219,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
assert isinstance(entry["visitors"], int)
def test_top_sources_limited_to_five(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
for idx in range(7):
distinct_id = f"src_user_{idx}"
_create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
@@ -244,7 +244,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
assert isinstance(entry["visitors"], int)
def test_goals_empty_when_team_has_no_actions(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
response = self.client.get(self._url())
assert response.status_code == status.HTTP_200_OK
@@ -268,7 +268,7 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):
api_key = self.create_personal_api_key_with_scopes(scopes)
self.client.logout()
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
response = self.client.get(self._url(), HTTP_AUTHORIZATION=f"Bearer {api_key}")
assert response.status_code == expected_status
@@ -289,7 +289,7 @@ class TestWebAnalyticsRecapAPI(ClickhouseTestMixin, APIBaseTest):
return self.ENDPOINT.format(team_id=team_id or self.team.id)
def test_recap_extends_digest_with_persona_and_highlights(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
_create_pageview(self.team, distinct_id="user_1", url="https://example.com/", timestamp="2025-01-25")
flush_persons_and_events()
@@ -317,7 +317,7 @@ class TestWebAnalyticsRecapAPI(ClickhouseTestMixin, APIBaseTest):
assert data["project_name"] == self.team.name
def test_empty_team_gets_just_getting_started_persona(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
response = self.client.get(self._url())
assert response.status_code == status.HTTP_200_OK
@@ -351,7 +351,7 @@ class TestWebAnalyticsRecapAPI(ClickhouseTestMixin, APIBaseTest):
api_key = self.create_personal_api_key_with_scopes(scopes)
self.client.logout()
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
response = self.client.get(self._url(), HTTP_AUTHORIZATION=f"Bearer {api_key}")
assert response.status_code == expected_status
diff --git a/products/web_analytics/backend/test/test_heatmaps_api.py b/products/web_analytics/backend/test/test_heatmaps_api.py
index 6dd824cad78f..c2ac4b60fa05 100644
--- a/products/web_analytics/backend/test/test_heatmaps_api.py
+++ b/products/web_analytics/backend/test/test_heatmaps_api.py
@@ -3,7 +3,7 @@ from contextlib import contextmanager
from json import dumps
from urllib.parse import quote
-import freezegun
+import time_machine
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -149,7 +149,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
properties=properties,
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_empty_response(self) -> None:
response = self.client.get("/api/heatmap/?date_from=2024-05-03")
@@ -168,7 +168,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
},
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_all_data_response(self) -> None:
self._create_heatmap_event("session_1", "click")
@@ -176,7 +176,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
self._assert_heatmap_single_result_count({"date_from": "2023-03-08"}, 2)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_returns_below_the_fold_summary(self) -> None:
# Non-fixed clicks against a 640px-tall viewport: one above the fold, two below it.
self._create_heatmap_event("s1", "click", viewport_height=640, y=320, pointer_target_fixed=False)
@@ -194,7 +194,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
"median_viewport_height": 640,
}
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_cannot_query_across_teams(self) -> None:
self._create_heatmap_event("session_1", "click")
self._create_heatmap_event("session_2", "click")
@@ -206,7 +206,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
# second team's click is not counted
self._assert_heatmap_single_result_count({"date_from": "2023-03-08"}, 2)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_filter_by_date_from(self) -> None:
self._create_heatmap_event("session_1", "click", "2023-03-07T07:00:00")
@@ -215,7 +215,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
self._assert_heatmap_single_result_count({"date_from": "2023-03-08"}, 1)
@snapshot_clickhouse_queries
- @freezegun.freeze_time("2023-03-15T09:00:00")
+ @time_machine.travel("2023-03-15T09:00:00", tick=False)
def test_can_get_filter_by_relative_date(self) -> None:
self._create_heatmap_event("session_1", "click", "2023-03-07T07:00:00")
self._create_heatmap_event("session_2", "click", "2023-03-08T08:00:00")
@@ -223,7 +223,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
self._assert_heatmap_single_result_count({"date_from": "-7d", "date_to": "-1d"}, 1)
self._assert_heatmap_no_result_count({"date_from": "dStart", "date_to": "dEnd"})
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_filter_by_click(self) -> None:
self._create_heatmap_event("session_1", "click", "2023-03-08T07:00:00")
@@ -254,7 +254,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
("offset_past_end_returns_empty", 2, 5, [], False),
]
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_limit_and_offset_page_hottest_first(
self, _name: str, limit: int | None, offset: int | None, expected_counts: list[int], expected_has_more: bool
) -> None:
@@ -270,7 +270,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
assert [r["count"] for r in response.data["results"]] == expected_counts
assert response.data["has_more"] is expected_has_more
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_scrolldepth_ignores_limit_and_has_no_has_more(self) -> None:
for i, y in enumerate([100, 200, 300, 400]):
self._create_heatmap_event(f"session_{i}", "scrolldepth", "2023-03-08T08:00:00", y=y, viewport_height=1000)
@@ -279,7 +279,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
assert len(response.data["results"]) > 1
assert "has_more" not in response.data
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_by_exact_url(self) -> None:
self._create_heatmap_event("session_1", "rageclick", "2023-03-08T08:00:00", current_url="http://example.com")
@@ -306,7 +306,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
("query_with_slash_data_with_slash", "http://example.com/", "http://example.com/"),
]
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_url_exact_normalizes_trailing_slash(self, _name: str, query_url: str, data_url: str) -> None:
self._create_heatmap_event("session_1", "click", "2023-03-08T08:00:00", current_url=data_url)
@@ -314,7 +314,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
{"date_from": "2023-03-08", "url_exact": query_url, "type": "click"}, 1
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_by_url_pattern_where_end_is_anchored(self) -> None:
# home page with no trailing slash
@@ -344,7 +344,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
],
name_func=lambda f, n, p: f"{f.__name__}_{p.args[0]}",
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_by_url_pattern(self, pattern: str, expected_matches: int) -> None:
# the home page
@@ -388,7 +388,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
expected_matches,
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_scrolldepth_counts(self) -> None:
# to calculate expected scroll depth bucket from y and viewport height
@@ -446,7 +446,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
],
}
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_scrolldepth_counts_by_visitor(self) -> None:
# scroll depth bucket 1000
@@ -526,7 +526,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
],
]
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_by_viewport(self, _name: str, query_params: dict, expected_results: list) -> None:
# all these xs = round(10/16) = 1
@@ -547,7 +547,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
response = self._get_heatmap(query_params)
assert sorted(response.data["results"], key=lambda k: k["pointer_relative_x"]) == expected_results
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_filter_by_test_accounts(self) -> None:
self.team.test_account_filters = [
@@ -622,7 +622,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
("relative_today_start_end", {"date_from": "dStart", "date_to": "dEnd"}),
]
)
- @freezegun.freeze_time("2023-03-08T13:00:00")
+ @time_machine.travel("2023-03-08T13:00:00", tick=False)
def test_filter_test_accounts_returns_data_for_single_day_range(self, _name: str, params: dict[str, str]) -> None:
# A single-day window (date_from and date_to on the same day) must still return data when filtering
# test accounts. The events subquery backing the test-account filter used to collapse to an impossible
@@ -655,7 +655,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
},
]
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_can_get_count_by_aggregation(self) -> None:
# 3 items but 2 visitors
@@ -708,21 +708,21 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
("default", {"date_from": "2023-03-08"}),
]
)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_hide_zero_coordinates_filters_out_zero_zero_events(self, _name: str, params: dict) -> None:
self._create_heatmap_event("session_1", "click", x=0, y=0)
self._create_heatmap_event("session_2", "click", x=10, y=20)
self._assert_heatmap_single_result_count(params, 1)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_hide_zero_coordinates_false_includes_zero_zero(self) -> None:
self._create_heatmap_event("session_1", "click", x=0, y=0)
self._create_heatmap_event("session_2", "click", x=10, y=20)
self._assert_heatmap_result_count({"date_from": "2023-03-08", "hide_zero_coordinates": "false"}, 2)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_hide_zero_coordinates_not_applied_to_scrolldepth(self) -> None:
self._create_heatmap_event("session_1", "scrolldepth", x=0, y=0)
@@ -749,7 +749,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
self._create_heatmap_event("session_2", "click", "2023-03-08T09:00:00", viewport_width=100, x=50, y=10)
self._create_heatmap_event("session_3", "click", "2023-03-08T09:00:00", viewport_width=100, x=100, y=10)
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_narrows_to_sessions_containing_every_selected_event(self) -> None:
self._create_three_sessions_at_distinct_positions()
@@ -770,7 +770,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
two_events = self._events_param([{"id": "purchase"}, {"id": "signed_up"}])
assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": two_events}) == [0.0]
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_applies_the_property_filters_carried_by_an_event(self) -> None:
self._create_three_sessions_at_distinct_positions()
@@ -792,7 +792,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
with self._event_filter_flag(True):
assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": events}) == [0.0]
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_keeps_a_session_whose_event_landed_before_the_window(self) -> None:
# The interaction is inside the window and the event that selects it is not, because the session
@@ -804,7 +804,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
with self._event_filter_flag(True):
assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": events}) == [0.0]
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
def test_event_filter_is_ignored_when_the_flag_is_off(self) -> None:
self._create_three_sessions_at_distinct_positions()
self.create_event(session_id="session_1", timestamp="2023-03-08T09:00:00", event_name="purchase", properties={})
@@ -813,7 +813,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
with self._event_filter_flag(False):
assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": events}) == [0.0, 0.5, 1.0]
- @freezegun.freeze_time("2025-03-31")
+ @time_machine.travel("2025-03-31", tick=False)
@snapshot_clickhouse_queries
def test_event_filter_also_narrows_the_interaction_drill_down(self) -> None:
# The drill-down has to answer for the same sessions as the heatmap it was opened from, or a hotspot
diff --git a/products/web_analytics/backend/test/test_weekly_digest.py b/products/web_analytics/backend/test/test_weekly_digest.py
index 3ac0b7b8f6f6..614e388a7d47 100644
--- a/products/web_analytics/backend/test/test_weekly_digest.py
+++ b/products/web_analytics/backend/test/test_weekly_digest.py
@@ -1,6 +1,6 @@
from datetime import timedelta
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from django.utils import timezone
@@ -109,7 +109,7 @@ class TestAutoSelectProjectForUser(ClickhouseTestMixin, APIBaseTest):
class TestGetOverviewForTeam(ClickhouseTestMixin, APIBaseTest):
def test_returns_overview_with_events(self):
session_id = str(uuid7("2025-01-25"))
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
for _ in range(3):
_create_pageview(self.team, distinct_id="user_1", session_id=session_id, timestamp="2025-01-25")
@@ -126,7 +126,7 @@ class TestGetOverviewForTeam(ClickhouseTestMixin, APIBaseTest):
assert "avg_session_duration" in result
def test_returns_zero_values_for_team_with_no_events(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
result = get_overview_for_team(self.team)
assert result == {
@@ -140,7 +140,7 @@ class TestGetOverviewForTeam(ClickhouseTestMixin, APIBaseTest):
class TestGetTopPages(ClickhouseTestMixin, APIBaseTest):
def test_returns_pages_ordered_by_visitors(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
_create_person(team_id=self.team.pk, distinct_ids=["user_2"])
_create_person(team_id=self.team.pk, distinct_ids=["user_3"])
@@ -184,7 +184,7 @@ class TestGetTopPages(ClickhouseTestMixin, APIBaseTest):
assert result[0]["change"] is None
def test_includes_week_over_week_change(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["prev_user"])
_create_pageview(
self.team,
@@ -215,7 +215,7 @@ class TestGetTopPages(ClickhouseTestMixin, APIBaseTest):
assert change["text"].startswith("Up")
def test_respects_limit(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
session = str(uuid7("2025-01-25"))
for i in range(5):
@@ -233,14 +233,14 @@ class TestGetTopPages(ClickhouseTestMixin, APIBaseTest):
assert len(result) <= 2
def test_returns_empty_for_no_events(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
result = get_top_pages(self.team)
assert result == []
class TestGetTopSources(ClickhouseTestMixin, APIBaseTest):
def test_returns_sources_with_visitors(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
session = str(uuid7("2025-01-25"))
_create_pageview(
@@ -262,7 +262,7 @@ class TestGetTopSources(ClickhouseTestMixin, APIBaseTest):
assert result[0]["change"] is None
def test_includes_week_over_week_change(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["prev_user"])
_create_pageview(
self.team,
@@ -295,7 +295,7 @@ class TestGetTopSources(ClickhouseTestMixin, APIBaseTest):
assert change["text"].startswith("Up")
def test_filters_out_empty_sources(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
session = str(uuid7("2025-01-25"))
_create_pageview(
@@ -312,19 +312,19 @@ class TestGetTopSources(ClickhouseTestMixin, APIBaseTest):
assert all(r["name"] != "" for r in result)
def test_returns_empty_for_no_events(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
result = get_top_sources(self.team)
assert result == []
class TestGetGoalsForTeam(ClickhouseTestMixin, APIBaseTest):
def test_returns_empty_when_no_actions(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
result = get_goals_for_team(self.team)
assert result == []
def test_returns_goals_with_conversions(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
Action.objects.create(
team=self.team,
name="Signed Up",
@@ -352,7 +352,7 @@ class TestGetGoalsForTeam(ClickhouseTestMixin, APIBaseTest):
class TestBuildTeamDigest(ClickhouseTestMixin, APIBaseTest):
def test_returns_all_expected_keys(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
_create_person(team_id=self.team.pk, distinct_ids=["user_1"])
session = str(uuid7("2025-01-25"))
_create_pageview(
@@ -371,7 +371,7 @@ class TestBuildTeamDigest(ClickhouseTestMixin, APIBaseTest):
assert f"/project/{self.team.pk}/web" in result["dashboard_url"]
def test_works_with_no_events(self):
- with freeze_time(QUERY_TIMESTAMP):
+ with time_machine.travel(QUERY_TIMESTAMP, tick=False):
result = build_team_digest(self.team)
assert result["team"] == self.team
diff --git a/products/web_analytics/dags/tests/test_web_analytics_watchdog.py b/products/web_analytics/dags/tests/test_web_analytics_watchdog.py
index c7ec79c71dbc..76d06c2925d5 100644
--- a/products/web_analytics/dags/tests/test_web_analytics_watchdog.py
+++ b/products/web_analytics/dags/tests/test_web_analytics_watchdog.py
@@ -2,7 +2,7 @@ import datetime
from typing import Any
import pytest
-from freezegun import freeze_time
+import time_machine
from unittest.mock import Mock, patch
import dagster
@@ -127,7 +127,7 @@ class TestBuildRemediationConfigs:
class TestWebAnalyticsWatchdogAsset:
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_all_partitions_passing(self, mock_check):
mock_check.return_value = {
@@ -152,7 +152,7 @@ class TestWebAnalyticsWatchdogAsset:
assert result.metadata["accuracy_rate"].value == 100.0
assert result.metadata["dry_run"].value is True
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_some_partitions_failing(self, mock_check):
def side_effect(context, team_id, partition_date, tolerance_pct):
@@ -195,7 +195,7 @@ class TestWebAnalyticsWatchdogAsset:
assert len(remediation) == 1
assert remediation[0]["partition_key"] == "2024-01-18"
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_partition_check_error_handling(self, mock_check):
mock_check.side_effect = Exception("ClickHouse connection failed")
@@ -213,7 +213,7 @@ class TestWebAnalyticsWatchdogAsset:
assert len(failure.metadata["errors"].value) == 2
assert failure.metadata["partial_results"].value == []
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_partial_errors_still_fail_run(self, mock_check):
"""When some partitions succeed but others error, the run should still fail."""
@@ -247,7 +247,7 @@ class TestWebAnalyticsWatchdogAsset:
assert failure.metadata["error_count"].value == 2
assert len(failure.metadata["partial_results"].value) == 1
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_lookback_days_determines_date_range(self, mock_check):
mock_check.return_value = {
@@ -269,7 +269,7 @@ class TestWebAnalyticsWatchdogAsset:
checked_dates = [call.args[2] for call in mock_check.call_args_list]
assert checked_dates == ["2024-01-15", "2024-01-16", "2024-01-17", "2024-01-18", "2024-01-19"]
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_dry_run_logs_but_does_not_trigger(self, mock_check):
mock_check.return_value = {
@@ -300,7 +300,7 @@ class TestWebAnalyticsWatchdogAsset:
(0, 10, "POOR"),
],
)
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
@patch("products.web_analytics.dags.web_analytics_watchdog.check_partition_accuracy")
def test_overall_status_thresholds(self, mock_check, passing_count, total_count, expected_status):
call_count = [0]
@@ -329,7 +329,7 @@ class TestWebAnalyticsWatchdogAsset:
class TestWatchdogSchedule:
- @freeze_time("2024-01-20 12:00:00")
+ @time_machine.travel("2024-01-20 12:00:00", tick=False)
def test_schedule_returns_run_request(self):
context = dagster.build_schedule_context(scheduled_execution_time=datetime.datetime(2024, 1, 20, 6, 0))
result = web_analytics_watchdog_schedule(context)
diff --git a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py b/products/workflows/backend/api/test/test_hog_flow_draft_publish.py
index 016322e2d2dc..e2b4b1e38460 100644
--- a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py
+++ b/products/workflows/backend/api/test/test_hog_flow_draft_publish.py
@@ -1,4 +1,4 @@
-from freezegun import freeze_time
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -500,7 +500,7 @@ class TestHogFlowDraftPublish(APIBaseTest):
def test_publish_with_expired_token_is_rejected(self):
flow_id = self._create_active_flow()
- with freeze_time("2026-01-01T00:00:00Z"):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):
self._stage_draft(flow_id)
confirm_token = self._publish_preview(flow_id).json()["confirm_token"]
diff --git a/pyproject.toml b/pyproject.toml
index 1fa4f7f9a905..4bb4fd2861e4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -234,7 +234,7 @@ dev = [
"hypothesis~=6.151.9",
"pyinstrument~=5.1",
"pytest-rerunfailures~=16.1",
- "freezegun==1.5.5",
+ "time-machine==3.5.0",
"grpcio-tools~=1.71.0",
"protoletariat~=3.3.10",
"ipython~=9.3.0",
@@ -440,8 +440,8 @@ section-order = [
[tool.ruff.lint.isort.sections]
"django" = ["django"] # Group all Django imports into a separate section.
"testing" = [ # Group all testing imports into a separate section.
- "freezegun",
"pytest",
+ "time_machine",
"unittest",
"posthog.test.base",
]
diff --git a/uv.lock b/uv.lock
index c6d12bd1c823..9258c9a4d3c9 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2461,18 +2461,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/13/80/c2ef902d079fd9680ca8e98c2f709e39e45159fbd11c7a7b9a576faac63a/free_email_domains-1.0.1-py3-none-any.whl", hash = "sha256:3d2f7be52008297c7db65c989cf358553e9100a37a0d28cb090d1787a02e81b2", size = 26835, upload-time = "2025-01-27T16:45:46.562Z" },
]
-[[package]]
-name = "freezegun"
-version = "1.5.5"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "python-dateutil" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/95/dd/23e2f4e357f8fd3bdff613c1fe4466d21bfb00a6177f238079b17f7b1c84/freezegun-1.5.5.tar.gz", hash = "sha256:ac7742a6cc6c25a2c35e9292dfd554b897b517d2dec26891a2e8debf205cb94a", size = 35914, upload-time = "2025-08-09T10:39:08.338Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/5e/2e/b41d8a1a917d6581fc27a35d05561037b048e47df50f27f8ac9c7e27a710/freezegun-1.5.5-py3-none-any.whl", hash = "sha256:cd557f4a75cf074e84bc374249b9dd491eaeacd61376b9eb3c423282211619d2", size = 19266, upload-time = "2025-08-09T10:39:06.636Z" },
-]
-
[[package]]
name = "frozenlist"
version = "1.6.2"
@@ -5757,7 +5745,6 @@ dev = [
{ name = "faker" },
{ name = "fakeredis", extra = ["lua"] },
{ name = "flameprof" },
- { name = "freezegun" },
{ name = "grpcio-tools" },
{ name = "hogli" },
{ name = "hypothesis" },
@@ -5797,6 +5784,7 @@ dev = [
{ name = "syrupy" },
{ name = "tach" },
{ name = "testcontainers", extra = ["mysql"] },
+ { name = "time-machine" },
{ name = "ty" },
{ name = "types-aioboto3", extra = ["s3"] },
{ name = "types-aiobotocore" },
@@ -6039,7 +6027,6 @@ dev = [
{ name = "faker", specifier = "==17.5.0" },
{ name = "fakeredis", extras = ["lua"], specifier = "==2.23.3" },
{ name = "flameprof", specifier = "~=0.4" },
- { name = "freezegun", specifier = "==1.5.5" },
{ name = "grpcio-tools", specifier = "~=1.71.0" },
{ name = "hogli", editable = "tools/hogli" },
{ name = "hypothesis", specifier = "~=6.151.9" },
@@ -6079,6 +6066,7 @@ dev = [
{ name = "syrupy", specifier = "~=4.9.1" },
{ name = "tach", specifier = "~=0.34" },
{ name = "testcontainers", extras = ["mysql"], specifier = "~=4.14" },
+ { name = "time-machine", specifier = "==3.5.0" },
{ name = "ty", specifier = "==0.0.74" },
{ name = "types-aioboto3", extras = ["s3"], specifier = "~=14.3.0" },
{ name = "types-aiobotocore", specifier = "~=2.22.0" },
@@ -8286,6 +8274,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/de/a8/8f499c179ec900783ffe133e9aab10044481679bb9aad78436d239eee716/tiktoken-0.9.0-cp313-cp313-win_amd64.whl", hash = "sha256:5ea0edb6f83dc56d794723286215918c1cde03712cbbafa0348b33448faf5b95", size = 894669, upload-time = "2025-02-14T06:02:47.341Z" },
]
+[[package]]
+name = "time-machine"
+version = "3.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e3/1a/d9c82e780ac6c41102d50b30c3fb3c25a3b8dd46f807147462d1f4429171/time_machine-3.5.0.tar.gz", hash = "sha256:bc193985b43f15394cfded976efaf9068c3078a2135f42f81c874ba684720eae", size = 25692, upload-time = "2026-08-25T00:18:32.594Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8a/dc/61669d9a3c95291de10486d36b24ca8af50dce17e8d624f9887208f484d1/time_machine-3.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f01f0e0fa67ea501c4ea3bf5983234612fb5036ac32ddab092b09ead37715c7c", size = 25707, upload-time = "2026-08-25T00:17:49.791Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/a4/3f5a4286768dff89e2de8c9ebcb8765962f2ce00196865954f48132435ea/time_machine-3.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:479abe218c4bc03e1acd1914f095a2351ca658db17e69e56b194f5fe2337b216", size = 25878, upload-time = "2026-08-25T00:17:50.881Z" },
+ { url = "https://files.pythonhosted.org/packages/b3/ee/1cf35afb752519cd38a1aaf74617cde56c8417a6d235d26c9a650c74138f/time_machine-3.5.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a625e2fd1e3b0dcc1479f559866a068a8c48c3ebe7a2c2093daef8e924ff1a7e", size = 57713, upload-time = "2026-08-25T00:17:52.036Z" },
+ { url = "https://files.pythonhosted.org/packages/67/57/d9e3a30cad31fbbe17b81971984ae83121cf968e7583e36b8cf92f31e534/time_machine-3.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c5624a6c3256182aaf1d15defcff782d6b0a12c8b2554191981bb59fe00954a", size = 58443, upload-time = "2026-08-25T00:17:53.074Z" },
+ { url = "https://files.pythonhosted.org/packages/63/37/82035b221f3bd657f8ca1eb3e28a5a7865338d35331ccc06a0569b87c39a/time_machine-3.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:27a2a399d500f03fafe185b4313d372098901bb66b839abf9fb1b981ffb85f44", size = 57122, upload-time = "2026-08-25T00:17:54.116Z" },
+ { url = "https://files.pythonhosted.org/packages/93/ae/196922dd5af6b0b4ef650c02343f1276e4be5d98b2f83dfada5f79047cab/time_machine-3.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e5e0c69a871a6a03daf491421590671652fd299803c218a37af9551c15dc3e68", size = 56842, upload-time = "2026-08-25T00:17:55.219Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/d2/e6e055de97a1b4137bce620a44bd696c95d85f7621959e80e4a6a68c8265/time_machine-3.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:e31e50fc71059e9669da03fcf84a7431c1b731203e27625e4852e35a72bfd16e", size = 27753, upload-time = "2026-08-25T00:17:56.275Z" },
+ { url = "https://files.pythonhosted.org/packages/66/74/1fd21def4e95506209b1a10d756d3ca038828347730d4eaef2609d3813dc/time_machine-3.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:ca4a49ef0c28bb8a31e6cb9ff4b6a392e515b8642b07f561369d5023e820c583", size = 26987, upload-time = "2026-08-25T00:17:57.225Z" },
+]
+
[[package]]
name = "tld"
version = "0.13.2"