Skip to content

Commit

Permalink
chore(python): replace pytz.utc with ZoneInfo('UTC') (#17310)
Browse files Browse the repository at this point in the history
  • Loading branch information
thmsobrmlr authored Sep 12, 2023
1 parent b2016e4 commit 215de61
Show file tree
Hide file tree
Showing 29 changed files with 184 additions and 172 deletions.
4 changes: 2 additions & 2 deletions ee/api/test/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import datetime
from typing import Dict, Optional, cast

import pytz
from zoneinfo import ZoneInfo

from ee.api.test.fixtures.available_product_features import AVAILABLE_PRODUCT_FEATURES
from ee.models.license import License, LicenseManager
Expand Down Expand Up @@ -30,7 +30,7 @@ def setUpTestData(cls):
cls.license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key=cls.CONFIG_LICENSE_KEY,
plan=cls.CONFIG_LICENSE_PLAN,
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7, tzinfo=pytz.UTC),
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7, tzinfo=ZoneInfo("UTC")),
)
if hasattr(cls, "organization") and cls.organization: # type: ignore
cls.organization.available_product_features = AVAILABLE_PRODUCT_FEATURES # type: ignore
Expand Down
8 changes: 4 additions & 4 deletions ee/api/test/test_billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from uuid import uuid4

import jwt
import pytz
from zoneinfo import ZoneInfo
from dateutil.relativedelta import relativedelta
from django.utils.timezone import now
from freezegun import freeze_time
Expand Down Expand Up @@ -377,13 +377,13 @@ def test_license_is_updated_on_billing_load(self, mock_request):
self.client.get("/api/billing-v2")
self.license.refresh_from_db()

self.license.valid_until = datetime(2022, 1, 2, 0, 0, 0, tzinfo=pytz.UTC)
self.license.valid_until = datetime(2022, 1, 2, 0, 0, 0, tzinfo=ZoneInfo("UTC"))
self.license.save()
assert self.license.plan == "scale"
TEST_clear_instance_license_cache()
license = get_cached_instance_license()
assert license.plan == "scale"
assert license.valid_until == datetime(2022, 1, 2, 0, 0, 0, tzinfo=pytz.UTC)
assert license.valid_until == datetime(2022, 1, 2, 0, 0, 0, tzinfo=ZoneInfo("UTC"))

mock_request.return_value.json.return_value = {
"license": {
Expand All @@ -396,7 +396,7 @@ def test_license_is_updated_on_billing_load(self, mock_request):
license = get_cached_instance_license()
assert license.plan == "enterprise"
# Should be extended by 30 days
assert license.valid_until == datetime(2022, 1, 31, 12, 0, 0, tzinfo=pytz.UTC)
assert license.valid_until == datetime(2022, 1, 31, 12, 0, 0, tzinfo=ZoneInfo("UTC"))

@patch("ee.api.billing.requests.get")
def test_organization_available_features_updated_if_different(self, mock_request):
Expand Down
4 changes: 2 additions & 2 deletions ee/api/test/test_license.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from unittest.mock import Mock, patch

import pytest
import pytz
from zoneinfo import ZoneInfo
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.utils.timezone import now
Expand All @@ -27,7 +27,7 @@ def test_can_list_and_retrieve_licenses(self):
self.assertEqual(response_data["results"][0]["key"], "12345::67890")
self.assertEqual(
response_data["results"][0]["valid_until"],
timezone.datetime(2038, 1, 19, 3, 14, 7, tzinfo=pytz.UTC).isoformat().replace("+00:00", "Z"),
timezone.datetime(2038, 1, 19, 3, 14, 7, tzinfo=ZoneInfo("UTC")).isoformat().replace("+00:00", "Z"),
)

retrieve_response = self.client.get(f"/api/license/{response_data['results'][0]['id']}")
Expand Down
8 changes: 4 additions & 4 deletions ee/clickhouse/queries/test/test_util.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta

import pytz
from zoneinfo import ZoneInfo
from freezegun.api import freeze_time

from posthog.client import sync_execute
Expand All @@ -18,19 +18,19 @@ def test_get_earliest_timestamp(db, team):
_create_event(team=team, event="sign up", distinct_id="1", timestamp="2020-01-04T14:10:00Z")
_create_event(team=team, event="sign up", distinct_id="1", timestamp="2020-01-06T14:10:00Z")

assert get_earliest_timestamp(team.id) == datetime(2020, 1, 4, 14, 10, tzinfo=pytz.UTC)
assert get_earliest_timestamp(team.id) == datetime(2020, 1, 4, 14, 10, tzinfo=ZoneInfo("UTC"))

frozen_time.tick(timedelta(seconds=1))
_create_event(team=team, event="sign up", distinct_id="1", timestamp="1984-01-06T14:10:00Z")
_create_event(team=team, event="sign up", distinct_id="1", timestamp="2014-01-01T01:00:00Z")
_create_event(team=team, event="sign up", distinct_id="1", timestamp="2015-01-01T01:00:00Z")

assert get_earliest_timestamp(team.id) == datetime(2015, 1, 1, 1, tzinfo=pytz.UTC)
assert get_earliest_timestamp(team.id) == datetime(2015, 1, 1, 1, tzinfo=ZoneInfo("UTC"))


@freeze_time("2021-01-21")
def test_get_earliest_timestamp_with_no_events(db, team):
assert get_earliest_timestamp(team.id) == datetime(2021, 1, 14, tzinfo=pytz.UTC)
assert get_earliest_timestamp(team.id) == datetime(2021, 1, 14, tzinfo=ZoneInfo("UTC"))


def test_parse_breakdown_cohort_query(db, team):
Expand Down
4 changes: 2 additions & 2 deletions ee/tasks/test/subscriptions/subscriptions_test_factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import Any

import pytz
from zoneinfo import ZoneInfo

from posthog.models.subscription import Subscription

Expand All @@ -12,7 +12,7 @@ def create_subscription(**kwargs: Any) -> Subscription:
target_value="[email protected],[email protected]",
frequency="daily",
interval=1,
start_date=datetime(2022, 1, 1, 9, 0).replace(tzinfo=pytz.UTC),
start_date=datetime(2022, 1, 1, 9, 0).replace(tzinfo=ZoneInfo("UTC")),
)

payload.update(kwargs)
Expand Down
6 changes: 3 additions & 3 deletions ee/tasks/test/subscriptions/test_subscriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import List
from unittest.mock import MagicMock, call, patch

import pytz
from zoneinfo import ZoneInfo
from freezegun import freeze_time

from ee.tasks.subscriptions import (
Expand Down Expand Up @@ -58,9 +58,9 @@ def test_subscription_delivery_scheduling(
create_subscription(team=self.team, dashboard=self.dashboard, created_by=self.user, deleted=True),
]
# Modify a subscription to have its target time at least an hour ahead
subscriptions[2].start_date = datetime(2022, 1, 1, 10, 0).replace(tzinfo=pytz.UTC)
subscriptions[2].start_date = datetime(2022, 1, 1, 10, 0).replace(tzinfo=ZoneInfo("UTC"))
subscriptions[2].save()
assert subscriptions[2].next_delivery_date == datetime(2022, 2, 2, 10, 0).replace(tzinfo=pytz.UTC)
assert subscriptions[2].next_delivery_date == datetime(2022, 2, 2, 10, 0).replace(tzinfo=ZoneInfo("UTC"))

schedule_all_subscriptions()

Expand Down
4 changes: 2 additions & 2 deletions posthog/api/test/test_annotation.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime
from unittest.mock import patch

import pytz
from zoneinfo import ZoneInfo
from django.utils.timezone import now
from rest_framework import status

Expand Down Expand Up @@ -111,7 +111,7 @@ def test_creating_annotation(self, mock_capture):
"team": team2.pk, # make sure this is set automatically
},
)
date_marker: datetime = datetime(2020, 1, 1, 0, 0, 0).replace(tzinfo=pytz.UTC)
date_marker: datetime = datetime(2020, 1, 1, 0, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
instance = Annotation.objects.get(pk=response.json()["id"])
self.assertEqual(instance.content, "Marketing campaign")
Expand Down
7 changes: 3 additions & 4 deletions posthog/api/test/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from unittest.mock import patch
from urllib.parse import unquote, urlencode

import pytz
from zoneinfo import ZoneInfo
from dateutil import parser
from dateutil.relativedelta import relativedelta
from django.utils import timezone
Expand Down Expand Up @@ -168,7 +168,6 @@ def test_custom_event_values(self):
@also_test_with_materialized_columns(["random_prop"])
@snapshot_clickhouse_queries
def test_event_property_values(self):

with freeze_time("2020-01-10"):
_create_event(
distinct_id="bla",
Expand Down Expand Up @@ -346,8 +345,8 @@ def test_pagination_bounded_date_range(self):
with freeze_time("2021-10-10T12:03:03.829294Z"):
_create_person(team=self.team, distinct_ids=["1"])
now = timezone.now() - relativedelta(months=11)
after = (now).astimezone(pytz.utc).isoformat()
before = (now + relativedelta(days=23)).astimezone(pytz.utc).isoformat()
after = (now).astimezone(ZoneInfo("UTC")).isoformat()
before = (now + relativedelta(days=23)).astimezone(ZoneInfo("UTC")).isoformat()
params = {"distinct_id": "1", "after": after, "before": before, "limit": 10}
params_string = urlencode(params)
for idx in range(0, 25):
Expand Down
6 changes: 3 additions & 3 deletions posthog/api/test/test_insight.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from unittest.case import skip
from unittest.mock import patch

import pytz
from zoneinfo import ZoneInfo
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
Expand Down Expand Up @@ -1860,7 +1860,7 @@ def test_create_insight_viewed(self) -> None:
self.assertEqual(created_insight_viewed.user, self.user)
self.assertEqual(
created_insight_viewed.last_viewed_at,
datetime(2022, 3, 22, 0, 0, tzinfo=pytz.UTC),
datetime(2022, 3, 22, 0, 0, tzinfo=ZoneInfo("UTC")),
)

def test_update_insight_viewed(self) -> None:
Expand All @@ -1882,7 +1882,7 @@ def test_update_insight_viewed(self) -> None:
updated_insight_viewed = InsightViewed.objects.all()[0]
self.assertEqual(
updated_insight_viewed.last_viewed_at,
datetime(2022, 3, 23, 0, 0, tzinfo=pytz.UTC),
datetime(2022, 3, 23, 0, 0, tzinfo=ZoneInfo("UTC")),
)

def test_cant_view_insight_viewed_for_insight_in_another_team(self) -> None:
Expand Down
12 changes: 6 additions & 6 deletions posthog/api/test/test_organization_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import dns.resolver
import dns.rrset
import pytest
import pytz
from zoneinfo import ZoneInfo
from django.utils import timezone
from freezegun import freeze_time
from rest_framework import status
Expand Down Expand Up @@ -133,7 +133,7 @@ def test_creating_domain_on_self_hosted_is_automatically_verified(self):

instance = OrganizationDomain.objects.get(id=response_data["id"])
self.assertEqual(instance.domain, "the.posthog.com")
self.assertEqual(instance.verified_at, datetime.datetime(2021, 8, 8, 20, 20, 8, tzinfo=pytz.UTC))
self.assertEqual(instance.verified_at, datetime.datetime(2021, 8, 8, 20, 20, 8, tzinfo=ZoneInfo("UTC")))
self.assertEqual(instance.last_verification_retry, None)
self.assertEqual(instance.sso_enforcement, "")

Expand Down Expand Up @@ -200,7 +200,7 @@ def test_can_request_verification_for_unverified_domains(self, mock_dns_query):
self.assertEqual(response_data["verified_at"], self.domain.verified_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
self.assertEqual(response_data["is_verified"], True)

self.assertEqual(self.domain.verified_at, datetime.datetime(2021, 8, 8, 20, 20, 8, tzinfo=pytz.UTC))
self.assertEqual(self.domain.verified_at, datetime.datetime(2021, 8, 8, 20, 20, 8, tzinfo=ZoneInfo("UTC")))
self.assertEqual(self.domain.is_verified, True)

@patch("posthog.models.organization_domain.dns.resolver.resolve")
Expand All @@ -220,7 +220,7 @@ def test_domain_is_not_verified_with_missing_challenge(self, mock_dns_query):
self.assertEqual(response_data["verified_at"], None)
self.assertEqual(self.domain.verified_at, None)
self.assertEqual(
self.domain.last_verification_retry, datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=pytz.UTC)
self.domain.last_verification_retry, datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=ZoneInfo("UTC"))
)

@patch("posthog.models.organization_domain.dns.resolver.resolve")
Expand All @@ -240,7 +240,7 @@ def test_domain_is_not_verified_with_missing_domain(self, mock_dns_query):
self.assertEqual(response_data["verified_at"], None)
self.assertEqual(self.domain.verified_at, None)
self.assertEqual(
self.domain.last_verification_retry, datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=pytz.UTC)
self.domain.last_verification_retry, datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=ZoneInfo("UTC"))
)

@patch("posthog.models.organization_domain.dns.resolver.resolve")
Expand All @@ -262,7 +262,7 @@ def test_domain_is_not_verified_with_incorrect_challenge(self, mock_dns_query):
self.assertEqual(response_data["verified_at"], None)
self.assertEqual(self.domain.verified_at, None)
self.assertEqual(
self.domain.last_verification_retry, datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=pytz.UTC)
self.domain.last_verification_retry, datetime.datetime(2021, 10, 10, 10, 10, 10, tzinfo=ZoneInfo("UTC"))
)

def test_cannot_request_verification_for_verified_domains(self):
Expand Down
8 changes: 4 additions & 4 deletions posthog/api/test/test_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from unittest import mock
from unittest.mock import ANY, patch

import pytz
from zoneinfo import ZoneInfo
from django.core.files.uploadedfile import SimpleUploadedFile
from freezegun import freeze_time
from rest_framework import status
Expand Down Expand Up @@ -269,7 +269,7 @@ def test_update_plugin_auth(self, mock_sync_from_plugin_archive, mock_get, mock_

plugin = Plugin.objects.get(id=response.json()["id"])

fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=pytz.UTC)
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()):
Expand Down Expand Up @@ -715,7 +715,7 @@ def test_install_plugin_on_multiple_orgs(self, mock_get, mock_reload):
name="FooBar2", plugins_access_level=Organization.PluginsAccessLevel.INSTALL
)

fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=pytz.UTC)
fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
with freeze_time(fake_date.isoformat()):
response = self.client.post(
f"/api/organizations/{my_org.id}/plugins/", {"url": "https://github.com/PostHog/helloworldplugin"}
Expand Down Expand Up @@ -1281,7 +1281,7 @@ def test_check_for_updates_plugins_reload_not_called(self, _, mock_reload):

plugin_id = response.json()["id"]
plugin = Plugin.objects.get(id=plugin_id)
fake_date = datetime(2022, 1, 1, 0, 0).replace(tzinfo=pytz.UTC)
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()):
Expand Down
6 changes: 3 additions & 3 deletions posthog/api/test/test_signup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from unittest.mock import ANY, patch

import pytest
import pytz
from zoneinfo import ZoneInfo
from django.core import mail
from django.urls.base import reverse
from django.utils import timezone
Expand Down Expand Up @@ -733,7 +733,7 @@ def test_api_invite_sign_up_prevalidate_expired_invite(self):
invite: OrganizationInvite = OrganizationInvite.objects.create(
target_email="[email protected]", organization=self.organization
)
invite.created_at = datetime.datetime(2020, 12, 1, tzinfo=pytz.UTC)
invite.created_at = datetime.datetime(2020, 12, 1, tzinfo=ZoneInfo("UTC"))
invite.save()

response = self.client.get(f"/api/signup/{invite.id}/")
Expand Down Expand Up @@ -1132,7 +1132,7 @@ def test_cant_claim_expired_invite(self):
invite: OrganizationInvite = OrganizationInvite.objects.create(
target_email="[email protected]", organization=self.organization
)
invite.created_at = datetime.datetime(2020, 3, 3, tzinfo=pytz.UTC)
invite.created_at = datetime.datetime(2020, 3, 3, tzinfo=ZoneInfo("UTC"))
invite.save()

response = self.client.post(f"/api/signup/{invite.id}/", {"first_name": "Charlie", "password": "test_password"})
Expand Down
4 changes: 2 additions & 2 deletions posthog/clickhouse/system_status.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import timedelta
from os.path import abspath, dirname, join
from typing import Dict, Generator, List, Tuple
import pytz
from zoneinfo import ZoneInfo

from dateutil.relativedelta import relativedelta
from django.utils import timezone
Expand Down Expand Up @@ -103,7 +103,7 @@ def system_status() -> Generator[SystemStatusRow, None, None]:
last_event_ingested_timestamp = sync_execute("SELECT max(_timestamp) FROM events")[0][0]

# Therefore we can confidently apply the UTC timezone
last_event_ingested_timestamp_utc = last_event_ingested_timestamp.replace(tzinfo=pytz.UTC)
last_event_ingested_timestamp_utc = last_event_ingested_timestamp.replace(tzinfo=ZoneInfo("UTC"))

yield {
"key": "last_event_ingested_timestamp",
Expand Down
8 changes: 4 additions & 4 deletions posthog/clickhouse/test/test_person_overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from uuid import UUID, uuid4

import pytest
import pytz
from zoneinfo import ZoneInfo
from kafka import KafkaProducer

from posthog.clickhouse.client import sync_execute
Expand Down Expand Up @@ -35,9 +35,9 @@ def test_can_insert_person_overrides():
old_person_id = uuid4()
override_person_id = uuid4()
oldest_event_string = "2020-01-01 00:00:00"
oldest_event = datetime.fromisoformat(oldest_event_string).replace(tzinfo=pytz.UTC)
oldest_event = datetime.fromisoformat(oldest_event_string).replace(tzinfo=ZoneInfo("UTC"))
merged_at_string = "2020-01-02 00:00:00"
merged_at = datetime.fromisoformat(merged_at_string).replace(tzinfo=pytz.UTC)
merged_at = datetime.fromisoformat(merged_at_string).replace(tzinfo=ZoneInfo("UTC"))
message = {
"team_id": 1,
"old_person_id": str(old_person_id),
Expand Down Expand Up @@ -82,7 +82,7 @@ def test_can_insert_person_overrides():
[result] = results
created_at, *the_rest = result
assert the_rest == [1, old_person_id, override_person_id, oldest_event, merged_at, 2]
assert created_at > datetime.now(tz=pytz.UTC) - timedelta(seconds=10)
assert created_at > datetime.now(tz=ZoneInfo("UTC")) - timedelta(seconds=10)
finally:
producer.close()

Expand Down
6 changes: 4 additions & 2 deletions posthog/demo/test/test_matrix_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from enum import auto
from typing import Optional

import pytz
from zoneinfo import ZoneInfo

from posthog.client import sync_execute
from posthog.demo.matrix.manager import MatrixManager
Expand Down Expand Up @@ -54,7 +54,9 @@ class TestMatrixManager(ClickhouseDestroyTablesMixin):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.matrix = DummyMatrix(n_clusters=3, now=dt.datetime(2020, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC), days_future=0)
cls.matrix = DummyMatrix(
n_clusters=3, now=dt.datetime(2020, 1, 1, 0, 0, 0, 0, tzinfo=ZoneInfo("UTC")), days_future=0
)
cls.matrix.simulate()

def test_reset_master(self):
Expand Down
Loading

0 comments on commit 215de61

Please sign in to comment.