Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Enable datetimez lint rules in Ruff

Patryk Zawadzki5f84bd926c50
diff --git a/poetry.lock b/poetry.lock
index da67df099e..353b139265 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -3610,17 +3610,6 @@ files = [
{file = "pytimeparse-1.1.8.tar.gz", hash = "sha256:e86136477be924d7e670646a98561957e8ca7308d44841e21f5ddea757556a0a"},
]
-[[package]]
-name = "pytz"
-version = "2024.2"
-description = "World timezone definitions, modern and historical"
-optional = false
-python-versions = "*"
-files = [
- {file = "pytz-2024.2-py2.py3-none-any.whl", hash = "sha256:31c7c1817eb7fae7ca4b8c7ee50c72f93aa2dd863de768e1ef4245d426aa0725"},
- {file = "pytz-2024.2.tar.gz", hash = "sha256:2aa355083c50a0f93fa581709deac0c9ad65cca8a9e9beac660adcbd493c798a"},
-]
-
[[package]]
name = "pywatchman"
version = "2.0.0"
@@ -4520,13 +4509,13 @@ files = [
[[package]]
name = "types-pytz"
-version = "2024.2.0.20240913"
+version = "2024.2.0.20241003"
description = "Typing stubs for pytz"
optional = false
python-versions = ">=3.8"
files = [
- {file = "types-pytz-2024.2.0.20240913.tar.gz", hash = "sha256:4433b5df4a6fc587bbed41716d86a5ba5d832b4378e506f40d34bc9c81df2c24"},
- {file = "types_pytz-2024.2.0.20240913-py3-none-any.whl", hash = "sha256:a1eebf57ebc6e127a99d2fa2ba0a88d2b173784ef9b3defcc2004ab6855a44df"},
+ {file = "types-pytz-2024.2.0.20241003.tar.gz", hash = "sha256:575dc38f385a922a212bac00a7d6d2e16e141132a3c955078f4a4fd13ed6cb44"},
+ {file = "types_pytz-2024.2.0.20241003-py3-none-any.whl", hash = "sha256:3e22df1336c0c6ad1d29163c8fda82736909eb977281cb823c57f8bae07118b7"},
]
[[package]]
@@ -5176,4 +5165,4 @@ multidict = ">=4.0"
[metadata]
lock-version = "2.0"
python-versions = "~3.12"
-content-hash = "668afbdea6738a365c3aae6cbb9e34098c707cfa6832ffee0a3f473497dc3d23"
+content-hash = "fde023b061726d8726a5c15bcd877cc2d86e1afcbc31073edfc8f9d0689a71c1"
diff --git a/pyproject.toml b/pyproject.toml
index ccf03bcc29..51b77c14a2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -71,7 +71,6 @@ documentation = "https://docs.saleor.io/"
python-http-client = "^3.3.7"
python-json-logger = ">=0.1.11,<2.1.0"
pytimeparse = "^1.1.8"
- pytz = "^2024.1"
razorpay = "^1.2"
redis = "^5.0.1"
requests = "^2.32"
@@ -136,7 +135,6 @@ documentation = "https://docs.saleor.io/"
types-mock = "^5.0.0.5"
types-setuptools = "^74.1.0.20240907"
types-python-dateutil = "^2.8.19"
- types-pytz = "^2024.1.0"
types-redis = "^4.6.0"
types-requests = "^2.31.0"
types-six = "^1.16.17"
@@ -193,6 +191,7 @@ target-version = "py39"
"B",
"C4",
"D",
+ "DTZ",
"E",
"F",
"I",
diff --git a/saleor/account/tests/test_throttling.py b/saleor/account/tests/test_throttling.py
index 04a0d55eba..70b4329365 100644
--- a/saleor/account/tests/test_throttling.py
+++ b/saleor/account/tests/test_throttling.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import timedelta
from unittest.mock import patch
import before_after
@@ -73,7 +73,7 @@ def test_authenticate_successful_first_attempt(
assert mocked_cache.get(ip_key) is None
assert mocked_cache.get(ip_user_key) is None
- next_attempt = now + timedelta(seconds=MIN_DELAY)
+ next_attempt = now + datetime.timedelta(seconds=MIN_DELAY)
mocked_cache.add.assert_called_once_with(block_key, next_attempt, timeout=MIN_DELAY)
mocked_cache.set.assert_not_called()
mocked_cache.incr.assert_not_called()
@@ -113,7 +113,7 @@ def test_authenticate_successful_subsequent_attempt(
assert mocked_cache.get(ip_key) is None
assert mocked_cache.get(ip_user_key) is None
- next_attempt = now + timedelta(seconds=MIN_DELAY)
+ next_attempt = now + datetime.timedelta(seconds=MIN_DELAY)
mocked_cache.add.assert_called_once_with(block_key, next_attempt, timeout=MIN_DELAY)
mocked_cache.set.assert_not_called()
mocked_cache.incr.assert_not_called()
@@ -150,7 +150,7 @@ def test_authenticate_incorrect_password_non_existing_email_first_attempt(
ip_attempts_count = mocked_cache.get(ip_key)
ip_user_attempts_count = mocked_cache.get(ip_user_key)
- assert next_attempt == now + timedelta(seconds=MIN_DELAY)
+ assert next_attempt == now + datetime.timedelta(seconds=MIN_DELAY)
assert ip_attempts_count == 1
assert ip_user_attempts_count is None
mock_incr_arg_set = {arg.args[0] for arg in mocked_cache.incr.call_args_list}
@@ -191,7 +191,7 @@ def test_authenticate_incorrect_password_non_existing_email_subsequent_attempt(
updated_ip_attempts_count = mocked_cache.get(ip_key)
ip_user_attempts_count = mocked_cache.get(ip_user_key)
- assert next_attempt == now + timedelta(seconds=expected_delay)
+ assert next_attempt == now + datetime.timedelta(seconds=expected_delay)
assert updated_ip_attempts_count == ip_attempts_count + 1
assert ip_user_attempts_count is None
mock_incr_arg_set = {arg.args[0] for arg in mocked_cache.incr.call_args_list}
@@ -227,7 +227,7 @@ def test_authenticate_incorrect_password_existing_email_first_attempt(
ip_attempts_count = mocked_cache.get(ip_key)
ip_user_attempts_count = mocked_cache.get(ip_user_key)
- assert next_attempt == now + timedelta(seconds=MIN_DELAY)
+ assert next_attempt == now + datetime.timedelta(seconds=MIN_DELAY)
assert ip_attempts_count == 1
assert ip_user_attempts_count == 1
@@ -268,7 +268,7 @@ def test_authenticate_incorrect_password_existing_email_subsequent_attempt(
updated_ip_attempts_count = mocked_cache.get(ip_key)
updated_ip_user_attempts_count = mocked_cache.get(ip_user_key)
- assert next_attempt == now + timedelta(seconds=expected_delay)
+ assert next_attempt == now + datetime.timedelta(seconds=expected_delay)
assert updated_ip_attempts_count == ip_attempts_count + 1
assert updated_ip_user_attempts_count == ip_user_attempts_count + 1
@@ -310,7 +310,7 @@ def test_authenticate_login_attempt_delayed(
dummy_cache[ip_key] = {"value": ip_attempts_count, "ttl": 100}
dummy_cache[ip_user_key] = {"value": ip_user_attempts_count, "ttl": 100}
delay = get_delay_time(ip_attempts_count, ip_user_attempts_count)
- next_attempt = now + timedelta(seconds=delay)
+ next_attempt = now + datetime.timedelta(seconds=delay)
dummy_cache[block_key] = {"value": next_attempt, "ttl": delay}
# when & then
@@ -343,7 +343,7 @@ def test_authenticate_race_condition(
ip_key = get_cache_key_failed_ip(ip)
ip_user_key = get_cache_key_failed_ip_with_user(ip, customer_user.id)
- next_attempt = now + timedelta(seconds=MIN_DELAY)
+ next_attempt = now + datetime.timedelta(seconds=MIN_DELAY)
# when
def login_attempt(*args, **kwargs):
@@ -402,7 +402,7 @@ def test_authenticate_incorrect_credentials_max_attempts(
updated_ip_attempts_count = mocked_cache.get(ip_key)
updated_ip_user_attempts_count = mocked_cache.get(ip_user_key)
- assert next_attempt == now + timedelta(seconds=expected_delay)
+ assert next_attempt == now + datetime.timedelta(seconds=expected_delay)
assert updated_ip_attempts_count == ip_attempts_count + 1
assert updated_ip_user_attempts_count == ip_user_attempts_count + 1
assert "Unsuccessful logging attempts reached max value." in caplog.text
diff --git a/saleor/account/throttling.py b/saleor/account/throttling.py
index 65142a55b9..65103883e2 100644
--- a/saleor/account/throttling.py
+++ b/saleor/account/throttling.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import timedelta
from math import ceil
from typing import Optional
@@ -33,7 +33,7 @@ def authenticate_with_throttling(request, email, password) -> Optional[models.Us
# block the IP address before the next attempt to prevent concurrent requests
if add_block(block_key, MIN_DELAY) is False:
- next_attempt_time = cache.get(block_key) or timezone.now() + timedelta(
+ next_attempt_time = cache.get(block_key) or timezone.now() + datetime.timedelta(
seconds=MIN_DELAY
)
raise ValidationError(
@@ -121,12 +121,12 @@ def get_delay_time(ip_attempts_count: int, ip_user_attempts_count: int) -> int:
def override_block(block_key: str, time_delta: int):
- next_attempt_time = timezone.now() + timedelta(seconds=time_delta)
+ next_attempt_time = timezone.now() + datetime.timedelta(seconds=time_delta)
cache.set(block_key, next_attempt_time, timeout=time_delta)
def add_block(block_key: str, time_delta: int) -> bool:
- next_attempt_time = timezone.now() + timedelta(seconds=time_delta)
+ next_attempt_time = timezone.now() + datetime.timedelta(seconds=time_delta)
return cache.add(block_key, next_attempt_time, timeout=time_delta)
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index 4585deba4b..899c2a55f5 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from django.conf import settings
from django.db import models
@@ -41,7 +41,7 @@ class Channel(ModelWithMetadata):
expire_orders_after = models.IntegerField(default=None, null=True, blank=True)
delete_expired_orders_after = models.DurationField(
- default=timedelta(days=60),
+ default=datetime.timedelta(days=60),
)
include_draft_order_in_voucher_usage = models.BooleanField(default=False)
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 7242a836fa..8bc4193553 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -1,5 +1,5 @@
+import datetime
from collections.abc import Iterable
-from datetime import timedelta
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
@@ -91,7 +91,7 @@ def _trigger_checkout_sync_webhooks(
# valid prices. Triggered only when we have active sync tax webhook.
if webhook_event_map.get(
WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- ) and checkout_info.checkout.price_expiration < timezone.now() + timedelta(
+ ) and checkout_info.checkout.price_expiration < timezone.now() + datetime.timedelta(
seconds=10
):
fetch_checkout_data(
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index 8f38deb7f2..02597033af 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -1,5 +1,5 @@
+import datetime
from collections.abc import Iterable
-from datetime import date
from typing import TYPE_CHECKING, Optional, Union
import graphene
@@ -110,7 +110,7 @@ def validate_checkout_email(checkout: models.Checkout):
def _validate_gift_cards(checkout: Checkout):
"""Check if all gift cards assigned to checkout are available."""
- today = date.today()
+ today = datetime.datetime.now(tz=datetime.UTC).date()
all_gift_cards = GiftCard.objects.filter(checkouts=checkout.token).count()
active_gift_cards = (
GiftCard.objects.active(date=today).filter(checkouts=checkout.token).count()
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 81031e9c95..33db9bcc01 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1,6 +1,6 @@
+import datetime
import logging
from collections.abc import Iterable
-from datetime import timedelta
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional, Union, cast
from uuid import UUID
@@ -1760,7 +1760,7 @@ def _reserve_stocks_without_availability_check(
Reservation(
quantity_reserved=line.line.quantity,
reserved_until=timezone.now()
- + timedelta(seconds=settings.RESERVE_DURATION),
+ + datetime.timedelta(seconds=settings.RESERVE_DURATION),
stock=variants_stocks_map[line.variant.id],
checkout_line=line.line,
)
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index e034d7a064..8c620ecb77 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -1,6 +1,6 @@
"""Checkout-related ORM models."""
-from datetime import date
+import datetime
from decimal import Decimal
from operator import attrgetter
from typing import TYPE_CHECKING, Optional
@@ -234,7 +234,7 @@ class Checkout(models.Model):
"""Return the total balance of the gift cards assigned to the checkout."""
balance = (
self.gift_cards.using(database_connection_name)
- .active(date=date.today())
+ .active(date=datetime.datetime.now(tz=datetime.UTC).date())
.aggregate(models.Sum("current_balance_amount"))[
"current_balance_amount__sum"
]
diff --git a/saleor/checkout/problems.py b/saleor/checkout/problems.py
index de10a5fdfa..323cbe7cc1 100644
--- a/saleor/checkout/problems.py
+++ b/saleor/checkout/problems.py
@@ -4,8 +4,6 @@ from collections.abc import Iterable
from dataclasses import dataclass
from typing import Optional, Union
-import pytz
-
from ..graphql.channel import ChannelContext
from ..product.models import ProductChannelListing, ProductVariant
from ..warehouse.models import Stock
@@ -121,7 +119,7 @@ def get_not_available_lines(
],
):
lines_not_available = []
- now = datetime.datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
for line in lines:
if line_is_not_available(line, now, product_channel_listings_map):
lines_not_available.append(line)
diff --git a/saleor/checkout/tests/conftest.py b/saleor/checkout/tests/conftest.py
index 7c6444a710..d743bbaea0 100644
--- a/saleor/checkout/tests/conftest.py
+++ b/saleor/checkout/tests/conftest.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
import pytest
@@ -48,7 +48,7 @@ def priced_checkout_factory():
checkout.subtotal_gross_amount *= tax
checkout.total_gross_amount *= tax
# Cache prices until invalidated by force
- checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(days=1)
checkout.save()
return checkout
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
index 781bc58a34..cffa2e6587 100644
--- a/saleor/checkout/tests/test_actions.py
+++ b/saleor/checkout/tests/test_actions.py
@@ -4,7 +4,6 @@ from unittest.mock import call, patch
import before_after
import pytest
-import pytz
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
@@ -335,7 +334,7 @@ def test_transaction_amounts_automatic_checkout_complete_called_once(
@pytest.mark.parametrize(
"previous_modified_at",
- [None, datetime.datetime(2018, 5, 31, 12, 0, 0, tzinfo=pytz.UTC)],
+ [None, datetime.datetime(2018, 5, 31, 12, 0, 0, tzinfo=datetime.UTC)],
)
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
@freeze_time("2023-05-31 12:00:01")
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 55011b6f7a..b60784319e 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -152,7 +152,7 @@ def test_get_prices_of_discounted_specific_product_only_product(
add_variant_to_checkout(checkout_info, product2.variants.get(), 1)
voucher.products.add(product)
# assume that cache is correct
- checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(days=1)
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
@@ -186,7 +186,7 @@ def test_get_prices_of_discounted_specific_product_only_collection(
product.collections.add(collection)
voucher.collections.add(collection)
# assume that cache is correct
- checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(days=1)
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
@@ -223,7 +223,7 @@ def test_get_prices_of_discounted_specific_product_only_category(
add_variant_to_checkout(checkout_info, product2.variants.get(), 1)
voucher.categories.add(category)
# assume that cache is correct
- checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(days=1)
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 17aa4f983a..3b78bf6b85 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -4,7 +4,6 @@ from unittest.mock import Mock, patch
import graphene
import pytest
-import pytz
from django.utils import timezone
from django_countries.fields import Country
from freezegun import freeze_time
@@ -361,23 +360,23 @@ def test_clear_delivery_method(checkout, shipping_method):
def test_last_change_update(checkout):
- with freeze_time(datetime.datetime.now()) as frozen_datetime:
- assert checkout.last_change != frozen_datetime()
+ with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
+ assert checkout.last_change != datetime.datetime.now(tz=datetime.UTC)
checkout.note = "Sample note"
checkout.save()
- assert checkout.last_change == pytz.utc.localize(frozen_datetime())
+ assert checkout.last_change == datetime.datetime.now(tz=datetime.UTC)
def test_last_change_update_foreign_key(checkout, shipping_method):
- with freeze_time(datetime.datetime.now()) as frozen_datetime:
- assert checkout.last_change != frozen_datetime()
+ with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
+ assert checkout.last_change != datetime.datetime.now(tz=datetime.UTC)
checkout.shipping_method = shipping_method
checkout.save(update_fields=["shipping_method", "last_change"])
- assert checkout.last_change == pytz.utc.localize(frozen_datetime())
+ assert checkout.last_change == datetime.datetime.now(tz=datetime.UTC)
@pytest.mark.parametrize(
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 03b94f30c0..758927190e 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
from unittest import mock
@@ -2463,7 +2463,7 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
checkout.shipping_method = shipping_method
checkout.tracking_code = ""
checkout.redirect_url = "https://www.example.com"
- checkout.price_expiration = timezone.now() + timedelta(hours=2)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(hours=2)
checkout.save()
lines, _ = fetch_checkout_lines(checkout)
@@ -2471,7 +2471,7 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
def update_price_expiration(*args, **kwargs):
# Invalidate checkout prices just after processing payment
- checkout.price_expiration = timezone.now() - timedelta(hours=2)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(hours=2)
checkout.save(update_fields=["price_expiration"])
# when
diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.py
index 39105ec9e0..95ff718d38 100644
--- a/saleor/checkout/tests/test_tasks.py
+++ b/saleor/checkout/tests/test_tasks.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import timedelta
from decimal import Decimal
from unittest import mock
from uuid import UUID
@@ -26,8 +26,8 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
expired_anonymous_checkout = checkouts_list[0]
expired_anonymous_checkout.email = None
expired_anonymous_checkout.user = None
- expired_anonymous_checkout.created_at = now - timedelta(days=40)
- expired_anonymous_checkout.last_change = now - timedelta(days=35)
+ expired_anonymous_checkout.created_at = now - datetime.timedelta(days=40)
+ expired_anonymous_checkout.last_change = now - datetime.timedelta(days=35)
expired_anonymous_checkout.lines.create(
checkout=expired_anonymous_checkout, variant=variant, quantity=1
)
@@ -35,8 +35,8 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
not_expired_checkout_1 = checkouts_list[1]
not_expired_checkout_1.email = None
not_expired_checkout_1.user = None
- not_expired_checkout_1.created_at = now - timedelta(days=35)
- not_expired_checkout_1.last_change = now - timedelta(days=29)
+ not_expired_checkout_1.created_at = now - datetime.timedelta(days=35)
+ not_expired_checkout_1.last_change = now - datetime.timedelta(days=29)
not_expired_checkout_1.lines.create(
checkout=not_expired_checkout_1, variant=variant, quantity=1
)
@@ -44,8 +44,8 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
not_expired_checkout_2 = checkouts_list[2]
not_expired_checkout_2.email = None
not_expired_checkout_2.user = customer_user
- not_expired_checkout_2.created_at = now - timedelta(days=45)
- not_expired_checkout_2.last_change = now - timedelta(days=40)
+ not_expired_checkout_2.created_at = now - datetime.timedelta(days=45)
+ not_expired_checkout_2.last_change = now - datetime.timedelta(days=40)
not_expired_checkout_2.lines.create(
checkout=not_expired_checkout_2, variant=variant, quantity=1
)
@@ -53,14 +53,14 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
not_expired_checkout_3 = checkouts_list[3]
not_expired_checkout_3.email = "[email protected]"
not_expired_checkout_3.user = None
- not_expired_checkout_3.created_at = now - timedelta(days=45)
- not_expired_checkout_3.last_change = now - timedelta(days=40)
+ not_expired_checkout_3.created_at = now - datetime.timedelta(days=45)
+ not_expired_checkout_3.last_change = now - datetime.timedelta(days=40)
not_expired_checkout_3.lines.create(
checkout=not_expired_checkout_3, variant=variant, quantity=1
)
empty_checkout = checkouts_list[4]
- empty_checkout.last_change = now - timedelta(hours=8)
+ empty_checkout.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout.lines.count() == 0
Checkout.objects.bulk_update(
@@ -90,8 +90,8 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
expired_user_checkout_1 = checkouts_list[0]
expired_user_checkout_1.email = None
expired_user_checkout_1.user = customer_user
- expired_user_checkout_1.created_at = now - timedelta(days=100)
- expired_user_checkout_1.last_change = now - timedelta(days=98)
+ expired_user_checkout_1.created_at = now - datetime.timedelta(days=100)
+ expired_user_checkout_1.last_change = now - datetime.timedelta(days=98)
expired_user_checkout_1.lines.create(
checkout=expired_user_checkout_1, variant=variant, quantity=1
)
@@ -99,8 +99,8 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
expired_user_checkout_2 = checkouts_list[1]
expired_user_checkout_2.email = "[email protected]"
expired_user_checkout_2.user = None
- expired_user_checkout_2.created_at = now - timedelta(days=100)
- expired_user_checkout_2.last_change = now - timedelta(days=91)
+ expired_user_checkout_2.created_at = now - datetime.timedelta(days=100)
+ expired_user_checkout_2.last_change = now - datetime.timedelta(days=91)
expired_user_checkout_2.lines.create(
checkout=expired_user_checkout_2, variant=variant, quantity=1
)
@@ -108,8 +108,8 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
not_expired_checkout_1 = checkouts_list[2]
not_expired_checkout_1.email = None
not_expired_checkout_1.user = None
- not_expired_checkout_1.created_at = now - timedelta(days=35)
- not_expired_checkout_1.last_change = now - timedelta(days=29)
+ not_expired_checkout_1.created_at = now - datetime.timedelta(days=35)
+ not_expired_checkout_1.last_change = now - datetime.timedelta(days=29)
not_expired_checkout_1.lines.create(
checkout=not_expired_checkout_1, variant=variant, quantity=1
)
@@ -117,8 +117,8 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
not_expired_checkout_2 = checkouts_list[3]
not_expired_checkout_2.email = "[email protected]"
not_expired_checkout_2.user = None
- not_expired_checkout_2.created_at = now - timedelta(days=100)
- not_expired_checkout_2.last_change = now - timedelta(days=60)
+ not_expired_checkout_2.created_at = now - datetime.timedelta(days=100)
+ not_expired_checkout_2.last_change = now - datetime.timedelta(days=60)
not_expired_checkout_2.lines.create(
checkout=not_expired_checkout_2, variant=variant, quantity=1
)
@@ -126,8 +126,8 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
not_expired_checkout_3 = checkouts_list[4]
not_expired_checkout_3.email = None
not_expired_checkout_3.user = customer_user
- not_expired_checkout_3.created_at = now - timedelta(days=100)
- not_expired_checkout_3.last_change = now - timedelta(days=89)
+ not_expired_checkout_3.created_at = now - datetime.timedelta(days=100)
+ not_expired_checkout_3.last_change = now - datetime.timedelta(days=89)
not_expired_checkout_3.lines.create(
checkout=not_expired_checkout_3, variant=variant, quantity=1
)
@@ -159,21 +159,21 @@ def test_delete_empty_checkouts(checkouts_list, customer_user, variant):
checkout_count = Checkout.objects.count()
empty_checkout_1 = checkouts_list[0]
- empty_checkout_1.last_change = now - timedelta(hours=8)
+ empty_checkout_1.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout_1.lines.count() == 0
empty_checkout_2 = checkouts_list[1]
empty_checkout_2.email = "[email protected]"
empty_checkout_2.user = customer_user
- empty_checkout_2.last_change = now - timedelta(hours=8)
+ empty_checkout_2.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout_2.lines.count() == 0
empty_checkout_3 = checkouts_list[2]
- empty_checkout_3.last_change = now - timedelta(hours=2)
+ empty_checkout_3.last_change = now - datetime.timedelta(hours=2)
assert empty_checkout_3.lines.count() == 0
not_empty_checkout = checkouts_list[3]
- not_empty_checkout.last_change = now - timedelta(days=2)
+ not_empty_checkout.last_change = now - datetime.timedelta(days=2)
not_empty_checkout.lines.create(
checkout=not_empty_checkout, variant=variant, quantity=1
)
@@ -200,22 +200,22 @@ def test_delete_expired_checkouts(checkouts_list, customer_user, variant):
expired_anonymous_checkout = checkouts_list[0]
expired_anonymous_checkout.email = None
- expired_anonymous_checkout.created_at = now - timedelta(days=40)
- expired_anonymous_checkout.last_change = now - timedelta(days=35)
+ expired_anonymous_checkout.created_at = now - datetime.timedelta(days=40)
+ expired_anonymous_checkout.last_change = now - datetime.timedelta(days=35)
expired_anonymous_checkout.lines.create(
checkout=expired_anonymous_checkout, variant=variant, quantity=1
)
expired_user_checkout = checkouts_list[2]
expired_user_checkout.user = customer_user
- expired_user_checkout.created_at = now - timedelta(days=100)
- expired_user_checkout.last_change = now - timedelta(days=95)
+ expired_user_checkout.created_at = now - datetime.timedelta(days=100)
+ expired_user_checkout.last_change = now - datetime.timedelta(days=95)
expired_user_checkout.lines.create(
checkout=expired_user_checkout, variant=variant, quantity=1
)
empty_checkout = checkouts_list[4]
- empty_checkout.last_change = now - timedelta(hours=8)
+ empty_checkout.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout.lines.count() == 0
Checkout.objects.bulk_update(
@@ -279,8 +279,8 @@ def test_delete_expired_checkouts_doesnt_delete_when_transaction_amount_exists(
expired_anonymous_checkout = checkouts_list[0]
expired_anonymous_checkout.email = None
- expired_anonymous_checkout.created_at = now - timedelta(days=40)
- expired_anonymous_checkout.last_change = now - timedelta(days=35)
+ expired_anonymous_checkout.created_at = now - datetime.timedelta(days=40)
+ expired_anonymous_checkout.last_change = now - datetime.timedelta(days=35)
expired_anonymous_checkout.lines.create(
checkout=expired_anonymous_checkout, variant=variant, quantity=1
)
@@ -296,7 +296,7 @@ def test_delete_expired_checkouts_doesnt_delete_when_transaction_amount_exists(
)
empty_checkout = checkouts_list[1]
- empty_checkout.last_change = now - timedelta(hours=8)
+ empty_checkout.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout.lines.count() == 0
empty_checkout.payment_transactions.create(
authorized_value=Decimal(authorized),
@@ -312,8 +312,8 @@ def test_delete_expired_checkouts_doesnt_delete_when_transaction_amount_exists(
expired_user_checkout = checkouts_list[2]
expired_user_checkout.email = None
expired_user_checkout.user = customer_user
- expired_user_checkout.created_at = now - timedelta(days=100)
- expired_user_checkout.last_change = now - timedelta(days=98)
+ expired_user_checkout.created_at = now - datetime.timedelta(days=100)
+ expired_user_checkout.last_change = now - datetime.timedelta(days=98)
expired_user_checkout.lines.create(variant=variant, quantity=1)
expired_user_checkout.payment_transactions.create(
authorized_value=Decimal(authorized),
@@ -378,7 +378,7 @@ def test_delete_checkouts_until_done(mocked_task: mock.MagicMock, channel_USD):
for checkout_id in range(7)
]
)
- Checkout.objects.update(last_change=timezone.now() - timedelta(hours=7))
+ Checkout.objects.update(last_change=timezone.now() - datetime.timedelta(hours=7))
task_params = {
"batch_size": 2,
@@ -432,7 +432,7 @@ def test_aborts_deleting_checkouts_when_invocation_count_exhausted(
for checkout_id in range(3)
]
)
- Checkout.objects.update(last_change=timezone.now() - timedelta(hours=7))
+ Checkout.objects.update(last_change=timezone.now() - datetime.timedelta(hours=7))
mocked_task.assert_not_called()
task_params = {
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
index 8284d16659..98a63ced93 100644
--- a/saleor/core/jwt.py
+++ b/saleor/core/jwt.py
@@ -1,5 +1,5 @@
+import datetime
from collections.abc import Iterable
-from datetime import datetime, timedelta
from typing import Any, Optional
import graphene
@@ -29,9 +29,9 @@ JWT_OWNER_FIELD = "owner"
def jwt_base_payload(
- exp_delta: Optional[timedelta], token_owner: str
+ exp_delta: Optional[datetime.timedelta], token_owner: str
) -> dict[str, Any]:
- utc_now = datetime.utcnow()
+ utc_now = datetime.datetime.now(tz=datetime.UTC)
payload = {
"iat": utc_now,
@@ -46,7 +46,7 @@ def jwt_base_payload(
def jwt_user_payload(
user: User,
token_type: str,
- exp_delta: Optional[timedelta],
+ exp_delta: Optional[datetime.timedelta],
additional_payload: Optional[dict[str, Any]] = None,
token_owner: str = JWT_SALEOR_OWNER_NAME,
) -> dict[str, Any]:
@@ -86,7 +86,7 @@ def jwt_decode(
return jwt_manager.decode(token, verify_expiration, verify_aud=verify_aud)
-def create_token(payload: dict[str, Any], exp_delta: timedelta) -> str:
+def create_token(payload: dict[str, Any], exp_delta: datetime.timedelta) -> str:
payload.update(jwt_base_payload(exp_delta, token_owner=JWT_SALEOR_OWNER_NAME))
return jwt_encode(payload)
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index ba385f6f13..76dc300076 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import datetime
from typing import TYPE_CHECKING, Union
from django.conf import settings
@@ -28,7 +28,9 @@ def jwt_refresh_token_middleware(get_response):
jwt_refresh_token
)
if refresh_token_payload and refresh_token_payload.get("exp"):
- expires = datetime.utcfromtimestamp(refresh_token_payload["exp"])
+ expires = datetime.datetime.fromtimestamp(
+ refresh_token_payload["exp"], tz=datetime.UTC
+ )
response.set_cookie(
JWT_REFRESH_TOKEN_COOKIE_NAME,
jwt_refresh_token,
diff --git a/saleor/core/models.py b/saleor/core/models.py
index 83717af1b9..a9b0315a98 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -2,7 +2,6 @@ import datetime
from collections.abc import Iterable
from typing import Any, TypeVar
-import pytz
from django.contrib.postgres.indexes import GinIndex
from django.core.files.base import ContentFile
from django.db import models, transaction
@@ -51,7 +50,7 @@ T = TypeVar("T", bound="PublishableModel")
class PublishedQuerySet(models.QuerySet[T]):
def published(self):
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
return self.filter(
Q(published_at__lte=today) | Q(published_at__isnull=True),
is_published=True,
@@ -74,7 +73,7 @@ class PublishableModel(models.Model):
def is_visible(self):
return self.is_published and (
self.published_at is None
- or self.published_at <= datetime.datetime.now(pytz.UTC)
+ or self.published_at <= datetime.datetime.now(tz=datetime.UTC)
)
diff --git a/saleor/core/schedules.py b/saleor/core/schedules.py
index d1e4083b8f..159ef7dc6f 100644
--- a/saleor/core/schedules.py
+++ b/saleor/core/schedules.py
@@ -1,8 +1,7 @@
+import datetime
from collections import namedtuple
-from datetime import datetime, timedelta
from typing import cast
-import pytz
from celery.utils.time import maybe_timedelta, remaining
from django.db.models import F, Q
@@ -28,10 +27,10 @@ class promotion_webhook_schedule(CustomSchedule):
"""
def __init__(self, initial_timedelta=60, nowfun=None, app=None):
- self.initial_timedelta: timedelta = cast(
- timedelta, maybe_timedelta(initial_timedelta)
+ self.initial_timedelta: datetime.timedelta = cast(
+ datetime.timedelta, maybe_timedelta(initial_timedelta)
)
- self.next_run: timedelta = self.initial_timedelta
+ self.next_run: datetime.timedelta = self.initial_timedelta
super().__init__(
schedule=self,
nowfun=nowfun,
@@ -66,7 +65,7 @@ class promotion_webhook_schedule(CustomSchedule):
get_starting_promotions,
)
- now = datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
# remaining time must be calculated as the next call is overridden with 0
# when is_due was True (/celery/beat.py Scheduler.populate_heap)
@@ -78,7 +77,7 @@ class promotion_webhook_schedule(CustomSchedule):
# if task needs to be handled in batches, schedule next run with const value
if len(staring_promotions | ending_promotions) > PROMOTION_TOGGLE_BATCH_SIZE:
- self.next_run = timedelta(seconds=self.NEXT_BATCH_RUN_TIME)
+ self.next_run = datetime.timedelta(seconds=self.NEXT_BATCH_RUN_TIME)
is_due = remaining == 0
return schedstate(is_due, self.NEXT_BATCH_RUN_TIME)
@@ -107,7 +106,7 @@ class promotion_webhook_schedule(CustomSchedule):
nearest_end_date = upcoming_end_dates.first()
# calculate the earliest incoming date of starting or ending sale
- next_upcoming_date: datetime
+ next_upcoming_date: datetime.datetime
if nearest_start_date and nearest_end_date and nearest_end_date.end_date:
next_upcoming_date = min(
nearest_start_date.start_date, nearest_end_date.end_date
diff --git a/saleor/core/tests/test_schedules.py b/saleor/core/tests/test_schedules.py
index 10af62faee..9b24a313d8 100644
--- a/saleor/core/tests/test_schedules.py
+++ b/saleor/core/tests/test_schedules.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from django.utils import timezone
from freezegun import freeze_time
@@ -23,7 +23,7 @@ def test_promotion_webhook_schedule_remaining_estimate_initial_state():
def test_promotion_webhook_schedule_remaining_estimate():
# given
schedule = promotion_webhook_schedule()
- time_delta = timedelta(seconds=30)
+ time_delta = datetime.timedelta(seconds=30)
# when
remaining = schedule.remaining_estimate(last_run_at=timezone.now() - time_delta)
@@ -40,18 +40,18 @@ def test_is_due_not_promotion_to_notify_about_not_upcoming_promotion(promotion_l
promotion_1 = promotion_list[0]
promotion_2 = promotion_list[1]
- promotion_1.start_date = now - timedelta(days=1)
- promotion_1.last_notification_scheduled_at = now - timedelta(minutes=2)
+ promotion_1.start_date = now - datetime.timedelta(days=1)
+ promotion_1.last_notification_scheduled_at = now - datetime.timedelta(minutes=2)
- promotion_2.start_date = now - timedelta(days=2)
- promotion_2.last_notification_scheduled_at = now - timedelta(minutes=2)
+ promotion_2.start_date = now - datetime.timedelta(days=2)
+ promotion_2.last_notification_scheduled_at = now - datetime.timedelta(minutes=2)
Promotion.objects.bulk_update(
[promotion_1, promotion_2], ["start_date", "last_notification_scheduled_at"]
)
# when
- is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))
# then
assert is_due is False
@@ -66,11 +66,11 @@ def test_is_due_promotion_started_to_notify_and_not_upcoming_promotion(promotion
promotion_1 = promotion_list[0]
promotion_2 = promotion_list[1]
- promotion_1.start_date = now - timedelta(minutes=5)
- promotion_1.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_1.start_date = now - datetime.timedelta(minutes=5)
+ promotion_1.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
- promotion_2.start_date = now - timedelta(days=2)
- promotion_2.last_notification_scheduled_at = now - timedelta(minutes=2)
+ promotion_2.start_date = now - datetime.timedelta(days=2)
+ promotion_2.last_notification_scheduled_at = now - datetime.timedelta(minutes=2)
Promotion.objects.bulk_update(
[promotion_1, promotion_2],
@@ -78,7 +78,7 @@ def test_is_due_promotion_started_to_notify_and_not_upcoming_promotion(promotion
)
# when
- is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))
# then
assert is_due is True
@@ -93,12 +93,12 @@ def test_is_due_promotion_ended_to_notify_and_not_upcoming_promotion(promotion_l
promotion_1 = promotion_list[0]
promotion_2 = promotion_list[1]
- promotion_1.start_date = now - timedelta(days=2)
- promotion_1.last_notification_scheduled_at = now - timedelta(minutes=2)
+ promotion_1.start_date = now - datetime.timedelta(days=2)
+ promotion_1.last_notification_scheduled_at = now - datetime.timedelta(minutes=2)
- promotion_2.start_date = now - timedelta(days=1)
- promotion_2.end_date = now - timedelta(minutes=5)
- promotion_2.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_2.start_date = now - datetime.timedelta(days=1)
+ promotion_2.end_date = now - datetime.timedelta(minutes=5)
+ promotion_2.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
Promotion.objects.bulk_update(
[promotion_1, promotion_2],
@@ -110,7 +110,7 @@ def test_is_due_promotion_ended_to_notify_and_not_upcoming_promotion(promotion_l
)
# when
- is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))
# then
assert is_due is True
@@ -126,13 +126,13 @@ def test_is_due_promotion_started_to_notify_and_upcoming_promotion(promotion_lis
promotion_1 = promotion_list[0]
promotion_2 = promotion_list[1]
- promotion_1.start_date = now - timedelta(minutes=5)
- promotion_1.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_1.start_date = now - datetime.timedelta(minutes=5)
+ promotion_1.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
- time_delta = timedelta(seconds=44)
- promotion_2.start_date = now - timedelta(minutes=7)
+ time_delta = datetime.timedelta(seconds=44)
+ promotion_2.start_date = now - datetime.timedelta(minutes=7)
promotion_2.end_date = timezone.now() + time_delta
- promotion_2.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_2.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
Promotion.objects.bulk_update(
[promotion_1, promotion_2],
@@ -144,7 +144,7 @@ def test_is_due_promotion_started_to_notify_and_upcoming_promotion(promotion_lis
)
# when
- is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))
# then
assert is_due is True
@@ -162,13 +162,13 @@ def test_is_due_no_promotion_to_notify_about_and_upcoming_promotion_exists(
promotion_1 = promotion_list[0]
promotion_2 = promotion_list[1]
- promotion_1.start_date = now - timedelta(minutes=8)
- promotion_1.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_1.start_date = now - datetime.timedelta(minutes=8)
+ promotion_1.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
- time_delta = timedelta(seconds=22)
- promotion_2.start_date = now - timedelta(minutes=7)
+ time_delta = datetime.timedelta(seconds=22)
+ promotion_2.start_date = now - datetime.timedelta(minutes=7)
promotion_2.end_date = timezone.now() + time_delta
- promotion_2.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_2.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
Promotion.objects.bulk_update(
[promotion_1, promotion_2],
@@ -176,7 +176,7 @@ def test_is_due_no_promotion_to_notify_about_and_upcoming_promotion_exists(
)
# when
- is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))
# then
assert is_due is False
@@ -194,13 +194,13 @@ def test_is_due_no_promo_to_notify_about_upcoming_promo_exists_initial_time_retu
promotion_1 = promotion_list[0]
promotion_2 = promotion_list[1]
- promotion_1.start_date = now - timedelta(minutes=8)
- promotion_1.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_1.start_date = now - datetime.timedelta(minutes=8)
+ promotion_1.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
- time_delta = timedelta(minutes=3)
- promotion_2.start_date = now - timedelta(minutes=7)
+ time_delta = datetime.timedelta(minutes=3)
+ promotion_2.start_date = now - datetime.timedelta(minutes=7)
promotion_2.end_date = timezone.now() + time_delta
- promotion_2.last_notification_scheduled_at = now - timedelta(minutes=6)
+ promotion_2.last_notification_scheduled_at = now - datetime.timedelta(minutes=6)
Promotion.objects.bulk_update(
[promotion_1, promotion_2],
@@ -208,7 +208,7 @@ def test_is_due_no_promo_to_notify_about_upcoming_promo_exists_initial_time_retu
)
# when
- is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+ is_due, next_run = schedule.is_due(timezone.now() - datetime.timedelta(minutes=1))
# then
assert is_due is False
diff --git a/saleor/core/tests/test_tasks.py b/saleor/core/tests/test_tasks.py
index 9857d81ff5..e3123b6ae7 100644
--- a/saleor/core/tests/test_tasks.py
+++ b/saleor/core/tests/test_tasks.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from django.core.files.storage import default_storage
from django.utils import timezone
@@ -39,8 +39,8 @@ def test_delete_from_storage_task_file_that_not_exists(media_root):
def test_delete_event_payloads_task(webhook, settings):
delete_period = settings.EVENT_PAYLOAD_DELETE_PERIOD
start_time = timezone.now()
- before_delete_period = start_time - delete_period - timedelta(seconds=1)
- after_delete_period = start_time - delete_period + timedelta(seconds=1)
+ before_delete_period = start_time - delete_period - datetime.timedelta(seconds=1)
+ after_delete_period = start_time - delete_period + datetime.timedelta(seconds=1)
payload_files = {}
for creation_time in [before_delete_period, after_delete_period]:
with freeze_time(creation_time):
@@ -51,7 +51,7 @@ def test_delete_event_payloads_task(webhook, settings):
payload=payload,
webhook=webhook,
)
- with freeze_time(creation_time + timedelta(seconds=2)):
+ with freeze_time(creation_time + datetime.timedelta(seconds=2)):
EventDeliveryAttempt.objects.create(delivery=delivery)
with freeze_time(start_time):
diff --git a/saleor/core/utils/date_time.py b/saleor/core/utils/date_time.py
index ad45adb347..df1e983632 100644
--- a/saleor/core/utils/date_time.py
+++ b/saleor/core/utils/date_time.py
@@ -1,10 +1,10 @@
-from datetime import datetime
-
-import pytz
+import datetime
def convert_to_utc_date_time(date):
"""Convert date into utc date time."""
if date is None:
return
- return datetime.combine(date, datetime.min.time(), tzinfo=pytz.UTC)
+ return datetime.datetime.combine(
+ date, datetime.datetime.min.time(), tzinfo=datetime.UTC
+ )
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 7436c27c6b..e75fb4cc64 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -527,7 +527,7 @@ def create_fake_user(user_password, save=True, generate_id=False):
"default_shipping_address": address,
"is_active": True,
"note": fake.paragraph(),
- "date_joined": fake.date_time(tzinfo=timezone.get_current_timezone()),
+ "date_joined": fake.date_time(tzinfo=datetime.UTC),
}
if generate_id:
diff --git a/saleor/core/utils/validators.py b/saleor/core/utils/validators.py
index 599eb754bf..d0ad766a7b 100644
--- a/saleor/core/utils/validators.py
+++ b/saleor/core/utils/validators.py
@@ -1,4 +1,4 @@
-from datetime import date
+import datetime
from typing import Any
import micawber
@@ -37,4 +37,4 @@ def get_oembed_data(url: str, field_name: str) -> tuple[dict[str, Any], str]:
def is_date_in_future(given_date):
"""Return true when the date is in the future."""
- return given_date > date.today()
+ return given_date > datetime.datetime.now(tz=datetime.UTC).date()
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index ab347ece6d..1c9b917c83 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+import datetime
from unittest.mock import patch
from .....attribute.models import (
@@ -1072,7 +1072,7 @@ def test_add_reference_info_to_data_update_attribute_data(product, page):
def test_add_date_time_attribute_info_to_data(product, date_time_attribute):
# given
pk = product.pk
- date_time = datetime(2021, 7, 15, 2, 3)
+ date_time = datetime.datetime(2021, 7, 15, 2, 3, tzinfo=datetime.UTC)
attribute_data = AttributeData(
slug=date_time_attribute.slug,
value_slug=None,
@@ -1103,7 +1103,7 @@ def test_add_date_time_attribute_info_to_data(product, date_time_attribute):
def test_add_date_attribute_info_to_data(product, date_attribute):
# given
pk = product.pk
- date = datetime(2021, 8, 10, 5, 3)
+ date = datetime.datetime(2021, 8, 10, 5, 3, tzinfo=datetime.UTC)
attribute_data = AttributeData(
slug=date_attribute.slug,
value_slug=None,
diff --git a/saleor/csv/tests/test_tasks.py b/saleor/csv/tests/test_tasks.py
index a9a45d8f37..339e59778a 100644
--- a/saleor/csv/tests/test_tasks.py
+++ b/saleor/csv/tests/test_tasks.py
@@ -1,7 +1,6 @@
import datetime
from unittest.mock import ANY, MagicMock, Mock, patch
-import pytz
from django.core.files import File
from django.test import override_settings
from django.utils import timezone
@@ -108,13 +107,13 @@ def test_on_task_failure(send_export_failed_info_mock, user_export_file):
assert user_export_file.created_at
previous_updated_at = user_export_file.updated_at
- with freeze_time(datetime.datetime.now()) as frozen_datetime:
+ with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
# when
ExportTask().on_failure(exc, task_id, args, kwargs, info)
# then
user_export_file.refresh_from_db()
- assert user_export_file.updated_at == pytz.utc.localize(frozen_datetime())
+ assert user_export_file.updated_at == datetime.datetime.now(tz=datetime.UTC)
assert user_export_file.updated_at != previous_updated_at
assert user_export_file.status == JobStatus.FAILED
@@ -148,13 +147,13 @@ def test_on_task_failure_for_app(send_export_failed_info_mock, app_export_file):
assert app_export_file.created_at
previous_updated_at = app_export_file.updated_at
- with freeze_time(datetime.datetime.now()) as frozen_datetime:
+ with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
# when
ExportTask().on_failure(exc, task_id, args, kwargs, info)
# then
app_export_file.refresh_from_db()
- assert app_export_file.updated_at == pytz.utc.localize(frozen_datetime())
+ assert app_export_file.updated_at == datetime.datetime.now(tz=datetime.UTC)
assert app_export_file.updated_at != previous_updated_at
assert app_export_file.status == JobStatus.FAILED
@@ -184,13 +183,13 @@ def test_on_task_success(user_export_file):
assert user_export_file.created_at
previous_updated_at = user_export_file.updated_at
- with freeze_time(datetime.datetime.now()) as frozen_datetime:
+ with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
# when
ExportTask().on_success(None, task_id, args, kwargs)
# then
user_export_file.refresh_from_db()
- assert user_export_file.updated_at == pytz.utc.localize(frozen_datetime())
+ assert user_export_file.updated_at == datetime.datetime.now(tz=datetime.UTC)
assert user_export_file.updated_at != previous_updated_at
assert user_export_file.status == JobStatus.SUCCESS
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.py
index ca303d552d..f01e0f3482 100644
--- a/saleor/csv/utils/export.py
+++ b/saleor/csv/utils/export.py
@@ -1,5 +1,5 @@
+import datetime
import uuid
-from datetime import date, datetime
from tempfile import NamedTemporaryFile
from typing import IO, TYPE_CHECKING, Any, Optional, Union
@@ -157,15 +157,15 @@ def parse_input(data: Any) -> dict[str, Union[str, dict]]:
for attr in data.get("attributes") or []:
if "date_time" in attr:
if gte := attr["date_time"].get("gte"):
- attr["date_time"]["gte"] = datetime.fromisoformat(gte)
+ attr["date_time"]["gte"] = datetime.datetime.fromisoformat(gte)
if lte := attr["date_time"].get("lte"):
- attr["date_time"]["lte"] = datetime.fromisoformat(lte)
+ attr["date_time"]["lte"] = datetime.datetime.fromisoformat(lte)
if "date" in attr:
if gte := attr["date"].get("gte"):
- attr["date"]["gte"] = date.fromisoformat(gte)
+ attr["date"]["gte"] = datetime.date.fromisoformat(gte)
if lte := attr["date"].get("lte"):
- attr["date"]["lte"] = date.fromisoformat(lte)
+ attr["date"]["lte"] = datetime.date.fromisoformat(lte)
serialized_attributes.append(attr)
diff --git a/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py b/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py
index 71ab639a01..08a6454f83 100644
--- a/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py
+++ b/saleor/discount/migrations/0041_fulfill_orderdiscount_token_created_at_old_id.py
@@ -1,7 +1,6 @@
# Generated by Django 3.2.13 on 2022-05-02 11:06
import datetime
-import pytz
from django.contrib.postgres.functions import RandomUUID
from django.contrib.postgres.operations import CryptoExtension
from django.db import migrations
@@ -19,7 +18,7 @@ def set_order_discount_token_and_created_at(apps, _schema_editor):
Subquery(
Order.objects.filter(discounts=OuterRef("id")).values("created_at")[:1]
),
- datetime.datetime.now(pytz.UTC),
+ datetime.datetime.now(tz=datetime.UTC),
),
)
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index db25c5dabe..ac17ea2d78 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -1,10 +1,9 @@
-from datetime import datetime
+import datetime
from decimal import ROUND_HALF_UP, Decimal
from functools import partial
from typing import TYPE_CHECKING, Optional
from uuid import uuid4
-import pytz
from django.conf import settings
from django.contrib.postgres.indexes import BTreeIndex, GinIndex
from django.db import connection, models
@@ -349,7 +348,7 @@ class Promotion(ModelWithMetadata):
def is_active(self, date=None):
if date is None:
- date = datetime.now(pytz.utc)
+ date = datetime.datetime.now(tz=datetime.UTC)
return (not self.end_date or self.end_date >= date) and self.start_date <= date
def assign_old_sale_id(self):
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index 1a6fcdeef1..28c743d4f8 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -1,9 +1,8 @@
+import datetime
from collections import defaultdict
-from datetime import datetime
from typing import TYPE_CHECKING
import graphene
-import pytz
from celery.utils.log import get_task_logger
from django.conf import settings
from django.db.models import Exists, F, OuterRef, Q, QuerySet
@@ -112,7 +111,9 @@ def handle_promotion_toggle():
# DEPRECATED: will be removed in Saleor 4.0.
promotion_ids_str = ", ".join([str(promo.id) for promo in promotions])
- promotions.update(last_notification_scheduled_at=datetime.now(pytz.UTC))
+ promotions.update(
+ last_notification_scheduled_at=datetime.datetime.now(tz=datetime.UTC)
+ )
if starting_promotion_ids:
task_logger.info(
"The promotion_started webhook sent for Promotions with ids: %s",
@@ -137,7 +138,7 @@ def get_starting_promotions(batch=False):
and the notification date is null or the last notification was sent
before the start date.
"""
- now = datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
promotions = Promotion.objects.filter(
(
Q(last_notification_scheduled_at__isnull=True)
@@ -157,7 +158,7 @@ def get_ending_promotions(batch=False):
and the notification date is null or the last notification was sent
before the end date.
"""
- now = datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
promotions = Promotion.objects.filter(
(
Q(last_notification_scheduled_at__isnull=True)
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index d8e2c1366a..43f29ba913 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
import graphene
@@ -174,7 +174,7 @@ def test_voucher_queryset_active(voucher, channel_USD):
vouchers = Voucher.objects.all()
assert vouchers.count() == 1
active_vouchers = Voucher.objects.active_in_channel(
- date=timezone.now() - timedelta(days=1), channel_slug=channel_USD.slug
+ date=timezone.now() - datetime.timedelta(days=1), channel_slug=channel_USD.slug
)
assert active_vouchers.count() == 0
diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.py
index 457093def4..a0102c422e 100644
--- a/saleor/discount/tests/test_tasks.py
+++ b/saleor/discount/tests/test_tasks.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
from unittest.mock import ANY, patch
@@ -100,52 +100,52 @@ def test_handle_promotion_toggle(
# promotions with start date before current date
# without notification sent day - should be sent for started
- promotions[0].start_date = now - timedelta(days=1)
+ promotions[0].start_date = now - datetime.timedelta(days=1)
promotions[0].last_notification_scheduled_at = None
# with notification sent day after the start date - shouldn't be sent
- promotions[1].start_date = now - timedelta(days=1)
- promotions[1].last_notification_scheduled_at = now - timedelta(minutes=2)
+ promotions[1].start_date = now - datetime.timedelta(days=1)
+ promotions[1].last_notification_scheduled_at = now - datetime.timedelta(minutes=2)
# with notification sent day before the start date - should be sent for started
- promotions[2].start_date = now - timedelta(minutes=2)
- promotions[2].last_notification_scheduled_at = now - timedelta(minutes=5)
+ promotions[2].start_date = now - datetime.timedelta(minutes=2)
+ promotions[2].last_notification_scheduled_at = now - datetime.timedelta(minutes=5)
# without notification sent day
# promotions with start date after current date - shouldn't be sent
- promotions[3].start_date = now + timedelta(days=1)
+ promotions[3].start_date = now + datetime.timedelta(days=1)
promotions[3].last_notification_scheduled_at = None
# with notification sent day before the start date
- promotions[4].start_date = now + timedelta(days=1)
- promotions[4].last_notification_scheduled_at = now - timedelta(minutes=5)
+ promotions[4].start_date = now + datetime.timedelta(days=1)
+ promotions[4].last_notification_scheduled_at = now - datetime.timedelta(minutes=5)
# promotions with end date before current date
# without notification sent day - should be sent for ended
- promotions[5].start_date = now - timedelta(days=2)
- promotions[5].end_date = now - timedelta(days=1)
+ promotions[5].start_date = now - datetime.timedelta(days=2)
+ promotions[5].end_date = now - datetime.timedelta(days=1)
promotions[5].last_notification_scheduled_at = None
# with notification sent day after the start date - shouldn't be sent
- promotions[6].start_date = now - timedelta(days=2)
- promotions[6].end_date = now - timedelta(days=1)
- promotions[6].last_notification_scheduled_at = now - timedelta(minutes=2)
+ promotions[6].start_date = now - datetime.timedelta(days=2)
+ promotions[6].end_date = now - datetime.timedelta(days=1)
+ promotions[6].last_notification_scheduled_at = now - datetime.timedelta(minutes=2)
# with notification sent day before the start date - should be sent for ended
- promotions[7].start_date = now - timedelta(days=2)
- promotions[7].end_date = now - timedelta(minutes=2)
- promotions[7].last_notification_scheduled_at = now - timedelta(minutes=5)
+ promotions[7].start_date = now - datetime.timedelta(days=2)
+ promotions[7].end_date = now - datetime.timedelta(minutes=2)
+ promotions[7].last_notification_scheduled_at = now - datetime.timedelta(minutes=5)
# promotions with end date after current date
# without notification sent day
- promotions[8].start_date = now + timedelta(days=2)
- promotions[8].end_date = now + timedelta(days=1)
+ promotions[8].start_date = now + datetime.timedelta(days=2)
+ promotions[8].end_date = now + datetime.timedelta(days=1)
promotions[8].last_notification_scheduled_at = None
# with notification sent day before the start date
- promotions[9].start_date = now + timedelta(days=2)
- promotions[9].end_date = now + timedelta(days=1)
- promotions[9].last_notification_scheduled_at = now - timedelta(minutes=5)
+ promotions[9].start_date = now + datetime.timedelta(days=2)
+ promotions[9].end_date = now + datetime.timedelta(days=1)
+ promotions[9].last_notification_scheduled_at = now - datetime.timedelta(minutes=5)
Promotion.objects.bulk_update(
promotions,
@@ -197,8 +197,8 @@ def test_handle_promotion_toggle(
def test_clear_promotion_rule_variants_task(promotion_list):
# given
expired_promotion = promotion_list[-1]
- expired_promotion.start_date = timezone.now() - timedelta(days=5)
- expired_promotion.end_date = timezone.now() - timedelta(days=1)
+ expired_promotion.start_date = timezone.now() - datetime.timedelta(days=5)
+ expired_promotion.end_date = timezone.now() - datetime.timedelta(days=1)
expired_promotion.save(update_fields=["start_date", "end_date"])
PromotionRuleVariant = PromotionRule.variants.through
@@ -222,8 +222,8 @@ def test_clear_promotion_rule_variants_task(promotion_list):
def test_clear_promotion_rule_variants_task_marks_products_as_dirty(promotion_list):
# given
expired_promotion = promotion_list[-1]
- expired_promotion.start_date = timezone.now() - timedelta(days=5)
- expired_promotion.end_date = timezone.now() - timedelta(days=1)
+ expired_promotion.start_date = timezone.now() - datetime.timedelta(days=5)
+ expired_promotion.end_date = timezone.now() - datetime.timedelta(days=1)
expired_promotion.save(update_fields=["start_date", "end_date"])
PromotionRuleVariant = PromotionRule.variants.through
@@ -248,7 +248,7 @@ def test_clear_promotion_rule_variants_task_marks_products_as_dirty(promotion_li
def test_set_promotion_rule_variants_task(promotion_list):
# given
- Promotion.objects.update(start_date=timezone.now() - timedelta(days=5))
+ Promotion.objects.update(start_date=timezone.now() - datetime.timedelta(days=5))
PromotionRuleVariant = PromotionRule.variants.through
PromotionRuleVariant.objects.all().delete()
diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py
index 61f03c271c..727aaf40e8 100644
--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py
+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
from unittest.mock import patch
@@ -2258,7 +2258,7 @@ def test_get_best_gift_reward_no_available_for_purchase_variants(
variants = gift_promotion_rule.gifts.all()
product_ids = [variant.product_id for variant in variants]
ProductChannelListing.objects.filter(product__in=product_ids[:1]).update(
- available_for_purchase_at=timezone.now() + timedelta(days=1)
+ available_for_purchase_at=timezone.now() + datetime.timedelta(days=1)
)
ProductChannelListing.objects.filter(product__in=product_ids[1:]).delete()
diff --git a/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py b/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py
index 6bd69eed4f..e6df63cf9b 100644
--- a/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py
+++ b/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py
@@ -1,9 +1,8 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import patch
import graphene
-import pytz
from ... import RewardValueType
from ...models import Promotion, PromotionRule
@@ -46,7 +45,7 @@ def test_mark_active_catalogue_promotion_rules_as_dirty_with_multiple_channels(
# given
second_promotion = Promotion.objects.create(
name="Promotion",
- end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ end_date=datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=30),
)
rule_for_second_promotion = PromotionRule.objects.create(
name="Percentage promotion rule",
@@ -94,7 +93,7 @@ def test_mark_active_promotion_rules_as_dirty_with_multiple_promotions_and_chann
# given
second_promotion = Promotion.objects.create(
name="Promotion",
- end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ end_date=datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=30),
)
rule_for_second_promotion = PromotionRule.objects.create(
name="Percentage promotion rule",
diff --git a/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py b/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py
index 3ba1e386b0..a74360a837 100644
--- a/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py
+++ b/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py
@@ -1,9 +1,8 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import patch
import graphene
-import pytz
from ... import RewardValueType
from ...models import Promotion, PromotionRule
@@ -28,7 +27,7 @@ def test_mark_catalogue_promotion_rules_as_dirty_single_promotion(
promotion = catalogue_promotion
second_promotion = Promotion.objects.create(
name="Promotion",
- end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ end_date=datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=30),
)
PromotionRule.objects.create(
name="Percentage promotion rule",
@@ -66,7 +65,7 @@ def test_mark_catalogue_promotion_rules_as_dirty_multiple_promotion(
promotion = catalogue_promotion
second_promotion = Promotion.objects.create(
name="Promotion",
- end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ end_date=datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=30),
)
PromotionRule.objects.create(
name="Percentage promotion rule",
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 1d9ced4e82..2bc0d80da4 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -7,7 +7,6 @@ from typing import TYPE_CHECKING, Callable, Optional, Union, overload
from uuid import UUID
import graphene
-import pytz
from django.conf import settings
from django.db import transaction
from django.db.models import Exists, OuterRef, QuerySet
@@ -488,7 +487,7 @@ def _get_available_for_purchase_variant_ids(
channel: "Channel",
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
variants = ProductVariant.objects.using(database_connection_name).filter(
id__in=available_variant_ids
)
diff --git a/saleor/giftcard/tests/test_tasks.py b/saleor/giftcard/tests/test_tasks.py
index 10b7188985..eeb3f8d157 100644
--- a/saleor/giftcard/tests/test_tasks.py
+++ b/saleor/giftcard/tests/test_tasks.py
@@ -25,11 +25,15 @@ def test_deactivate_expired_cards_task(
gift_card, gift_card_used, gift_card_expiry_date, gift_card_created_by_staff
):
# given
- gift_card.expiry_date = datetime.date.today() - datetime.timedelta(days=1)
- gift_card_used.expiry_date = datetime.date.today() - datetime.timedelta(days=10)
- gift_card_created_by_staff.expiry_date = datetime.date.today() - datetime.timedelta(
- days=10
- )
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
+ gift_card_used.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=10)
+ gift_card_created_by_staff.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=10)
gift_card_created_by_staff.is_active = False
gift_cards = [gift_card, gift_card_used]
GiftCard.objects.bulk_update(
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.py
index b6b0ed6285..f661c5a81e 100644
--- a/saleor/giftcard/tests/test_utils.py
+++ b/saleor/giftcard/tests/test_utils.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import date, timedelta
from unittest.mock import patch
import graphene
@@ -78,7 +78,9 @@ def test_add_gift_card_code_to_checkout_inactive_card(checkout, gift_card):
def test_add_gift_card_code_to_checkout_expired_card(checkout, gift_card):
# given
- gift_card.expiry_date = date.today() - timedelta(days=10)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=10)
gift_card.save(update_fields=["expiry_date"])
assert checkout.gift_cards.count() == 0
@@ -829,7 +831,9 @@ def test_is_gift_card_expired_never_expired_gift_card(gift_card):
def test_is_gift_card_expired_true(gift_card):
# given
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save(update_fields=["expiry_date"])
# when
@@ -840,7 +844,8 @@ def test_is_gift_card_expired_true(gift_card):
@pytest.mark.parametrize(
- "expiry_date", [timezone.now().date(), timezone.now().date() + timedelta(days=1)]
+ "expiry_date",
+ [timezone.now().date(), timezone.now().date() + datetime.timedelta(days=1)],
)
def test_is_gift_card_expired_false(expiry_date, gift_card):
# given
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index 6aa96bc8c3..d196cdb8a1 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -1,6 +1,6 @@
+import datetime
from collections import defaultdict
from collections.abc import Iterable
-from datetime import date
from typing import TYPE_CHECKING, Optional
from uuid import UUID
@@ -44,7 +44,7 @@ def add_gift_card_code_to_checkout(
try:
# only active gift card with currency the same as channel currency can be used
gift_card = (
- GiftCard.objects.active(date=date.today())
+ GiftCard.objects.active(date=datetime.datetime.now(tz=datetime.UTC).date())
.filter(currency=currency)
.get(code=promo_code)
)
diff --git a/saleor/graphql/account/mutations/authentication/utils.py b/saleor/graphql/account/mutations/authentication/utils.py
index 8e0dbd7f6e..3928377cd2 100644
--- a/saleor/graphql/account/mutations/authentication/utils.py
+++ b/saleor/graphql/account/mutations/authentication/utils.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import jwt
from django.conf import settings
@@ -63,7 +63,9 @@ def _does_token_match(token: str, csrf_token: str) -> bool:
def update_user_last_login_if_required(user: User):
time_now = timezone.now()
- threshold_delta = timedelta(seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD)
+ threshold_delta = datetime.timedelta(
+ seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD
+ )
if not user.last_login or user.last_login + threshold_delta < time_now:
user.last_login = time_now
diff --git a/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py b/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py
index 01ae190c95..9b97aef358 100644
--- a/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py
+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_email_change.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
from ......core.jwt import create_token
@@ -43,7 +43,7 @@ def test_email_update(
}
user = user_api_client.user
- token = create_token(payload, timedelta(hours=1))
+ token = create_token(payload, datetime.timedelta(hours=1))
variables = {"token": token, "channel": channel_PLN.slug}
response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)
content = get_graphql_content(response)
@@ -62,7 +62,7 @@ def test_email_update_to_existing_email(user_api_client, customer_user, staff_us
"new_email": staff_user.email,
"user_pk": customer_user.pk,
}
- token = create_token(payload, timedelta(hours=1))
+ token = create_token(payload, datetime.timedelta(hours=1))
variables = {"token": token}
response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)
@@ -98,7 +98,7 @@ def test_account_email_changed_webhook_event_triggered(
}
user = user_api_client.user
- token = create_token(payload, timedelta(hours=1))
+ token = create_token(payload, datetime.timedelta(hours=1))
variables = {"token": token, "channel": channel_PLN.slug}
# when
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py b/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py
index d28bdc6afa..e590e5c3d0 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py
@@ -1,8 +1,7 @@
+import datetime
import json
-from datetime import datetime, timedelta
from unittest.mock import Mock, patch
-import pytz
from freezegun import freeze_time
from ......plugins.base_plugin import ExternalAccessTokens
@@ -99,12 +98,12 @@ def test_external_obtain_access_tokens_do_not_update_last_login_when_in_threshol
"pluginId": "pluginId1",
"input": json.dumps({"code": "ABCD", "state": "stata-data"}),
}
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
expected_last_login = customer_user.last_login
expected_updated_at = customer_user.updated_at
- time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_in_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD - 1
)
@@ -145,12 +144,12 @@ def test_external_obtain_access_tokens_do_update_last_login_when_out_of_threshol
"pluginId": "pluginId1",
"input": json.dumps({"code": "ABCD", "state": "stata-data"}),
}
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
previous_last_login = customer_user.last_login
previous_updated_at = customer_user.updated_at
- time_out_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_out_of_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
)
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py b/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py
index 5163d4141a..1f0d4d5451 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py
@@ -1,8 +1,7 @@
+import datetime
import json
-from datetime import datetime, timedelta
from unittest.mock import Mock, patch
-import pytz
from freezegun import freeze_time
from ......plugins.base_plugin import ExternalAccessTokens
@@ -93,12 +92,12 @@ def test_external_refresh_do_not_update_last_login_when_in_threshold(
)
variables = {"pluginId": "pluginId1", "input": json.dumps({"refreshToken": "ABCD"})}
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
expected_last_login = customer_user.last_login
expected_updated_at = customer_user.updated_at
- time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_in_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD - 1
)
@@ -136,12 +135,12 @@ def test_external_refresh_do_update_last_login_when_out_of_threshold(
)
variables = {"pluginId": "pluginId1", "input": json.dumps({"refreshToken": "ABCD"})}
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
previous_last_login = customer_user.last_login
previous_updated_at = customer_user.updated_at
- time_out_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_out_of_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
)
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
index 1ffc22781d..795aa992b5 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
@@ -1,8 +1,7 @@
-from datetime import datetime, timedelta, timezone
+import datetime
from unittest.mock import patch
import graphene
-import pytz
from django.urls import reverse
from freezegun import freeze_time
@@ -69,16 +68,30 @@ def test_create_token(_mocked_cache, api_client, customer_user, settings):
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_ACCESS
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_ACCESS_TYPE
payload = jwt_decode(refreshToken)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_REFRESH
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_REFRESH
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_REFRESH_TYPE
assert payload["token"] == customer_user.jwt_token_key
assert payload["iss"] == build_absolute_uri(reverse("api"))
@@ -112,17 +125,31 @@ def test_create_token_with_audience(_mocked_cache, api_client, customer_user, se
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_ACCESS
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_ACCESS_TYPE
assert payload["aud"] == f"custom:{audience}"
payload = jwt_decode(refreshToken)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_REFRESH
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_REFRESH
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_REFRESH_TYPE
assert payload["token"] == customer_user.jwt_token_key
assert payload["aud"] == f"custom:{audience}"
@@ -150,9 +177,11 @@ def test_create_token_sets_cookie(
)
refresh_token = response.cookies["refreshToken"]
assert refresh_token.value == expected_refresh_token
- expected_expires = datetime.utcnow() + settings.JWT_TTL_REFRESH
- expected_expires += timedelta(seconds=1)
- expires = datetime.strptime(refresh_token["expires"], "%a, %d %b %Y %H:%M:%S %Z")
+ expected_expires = datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_REFRESH
+ expected_expires += datetime.timedelta(seconds=1)
+ expires = datetime.datetime.strptime(
+ refresh_token["expires"], "%a, %d %b %Y %H:%M:%S %Z"
+ ).replace(tzinfo=datetime.UTC)
assert expires == expected_expires
assert refresh_token["httponly"]
assert refresh_token["secure"]
@@ -240,16 +269,30 @@ def test_create_token_unconfirmed_user_unconfirmed_login_enabled(
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_ACCESS
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_ACCESS_TYPE
payload = jwt_decode(refreshToken)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_REFRESH
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_REFRESH
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_REFRESH_TYPE
assert payload["token"] == customer_user.jwt_token_key
assert payload["iss"] == build_absolute_uri(reverse("api"))
@@ -262,7 +305,7 @@ def test_create_token_deactivated_user(_mocked_cache, api_client, customer_user)
variables = {"email": customer_user.email, "password": customer_user._password}
customer_user.is_active = False
customer_user.is_confirmed = True
- customer_user.last_login = datetime(2020, 3, 18, tzinfo=timezone.utc)
+ customer_user.last_login = datetime.datetime(2020, 3, 18, tzinfo=datetime.UTC)
customer_user.save()
expected_error_code = AccountErrorCode.INACTIVE.value.upper()
@@ -283,7 +326,7 @@ def test_create_token_active_user_logged_before(
):
# given
variables = {"email": customer_user.email, "password": customer_user._password}
- customer_user.last_login = datetime(2020, 3, 18, tzinfo=timezone.utc)
+ customer_user.last_login = datetime.datetime(2020, 3, 18, tzinfo=datetime.UTC)
customer_user.save()
# when
@@ -303,16 +346,30 @@ def test_create_token_active_user_logged_before(
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_ACCESS
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_ACCESS_TYPE
payload = jwt_decode(refreshToken)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
- expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_REFRESH
- assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
+ expected_expiration_datetime = (
+ datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_REFRESH
+ )
+ assert (
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == expected_expiration_datetime
+ )
assert payload["type"] == JWT_REFRESH_TYPE
assert payload["token"] == customer_user.jwt_token_key
assert payload["iss"] == build_absolute_uri(reverse("api"))
@@ -346,12 +403,12 @@ def test_create_token_do_not_update_last_login_when_in_threshold(
):
# given
customer_password = customer_user._password
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
expected_last_login = customer_user.last_login
expected_updated_at = customer_user.updated_at
variables = {"email": customer_user.email, "password": customer_password}
- time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_in_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD - 1
)
@@ -372,13 +429,13 @@ def test_create_token_do_update_last_login_when_out_of_threshold(
):
# given
customer_password = customer_user._password
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
previous_last_login = customer_user.last_login
previous_updated_at = customer_user.updated_at
variables = {"email": customer_user.email, "password": customer_password}
- time_out_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_out_of_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
)
@@ -404,7 +461,7 @@ def test_create_token_throttling_login_attempt_delay(
# given
dummy_cache = {}
setup_mock_for_cache(dummy_cache, mocked_cache)
- now = datetime.utcnow()
+ now = datetime.datetime.now(tz=datetime.UTC)
variables = {"email": customer_user.email, "password": "incorrect-password"}
@@ -421,7 +478,7 @@ def test_create_token_throttling_login_attempt_delay(
mocked_cache.set(ip_key, ip_attempts_count, timeout=100)
mocked_cache.set(ip_user_key, ip_user_attempts_count, timeout=100)
expected_delay = get_delay_time(ip_attempts_count + 1, ip_user_attempts_count + 1)
- next_attempt = now + timedelta(seconds=expected_delay)
+ next_attempt = now + datetime.timedelta(seconds=expected_delay)
mocked_cache.set(block_key, next_attempt, timeout=100)
# when
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
index cd200ee0fd..b4788af7de 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
@@ -1,7 +1,6 @@
-from datetime import datetime, timedelta
+import datetime
import pytest
-import pytz
from django.urls import reverse
from freezegun import freeze_time
@@ -52,10 +51,12 @@ def test_refresh_token_with_audience(api_client, customer_user, settings):
assert token
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
assert (
- datetime.fromtimestamp(payload["exp"])
- == datetime.utcnow() + settings.JWT_TTL_ACCESS
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
)
assert payload["type"] == JWT_ACCESS_TYPE
assert payload["token"] == customer_user.jwt_token_key
@@ -84,10 +85,12 @@ def test_refresh_token_get_token_from_cookie(api_client, customer_user, settings
assert token
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
assert (
- datetime.fromtimestamp(payload["exp"])
- == datetime.utcnow() + settings.JWT_TTL_ACCESS
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
)
assert payload["type"] == JWT_ACCESS_TYPE
assert payload["token"] == customer_user.jwt_token_key
@@ -110,10 +113,12 @@ def test_refresh_token_get_token_from_input(api_client, customer_user, settings)
assert token
payload = jwt_decode(token)
assert payload["email"] == customer_user.email
- assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ assert datetime.datetime.fromtimestamp(
+ payload["iat"], tz=datetime.UTC
+ ) == datetime.datetime.now(tz=datetime.UTC)
assert (
- datetime.fromtimestamp(payload["exp"])
- == datetime.utcnow() + settings.JWT_TTL_ACCESS
+ datetime.datetime.fromtimestamp(payload["exp"], tz=datetime.UTC)
+ == datetime.datetime.now(tz=datetime.UTC) + settings.JWT_TTL_ACCESS
)
assert payload["type"] == JWT_ACCESS_TYPE
@@ -308,7 +313,7 @@ def test_refresh_token_do_not_update_last_login_when_in_threshold(
api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
expected_last_login = customer_user.last_login
@@ -316,7 +321,7 @@ def test_refresh_token_do_not_update_last_login_when_in_threshold(
variables = {"token": None, "csrf_token": csrf_token}
- time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_in_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD - 1
)
@@ -344,7 +349,7 @@ def test_refresh_token_do_update_last_login_when_out_of_threshold(
api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
- customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.last_login = datetime.datetime.now(tz=datetime.UTC)
customer_user.save()
previous_last_login = customer_user.last_login
@@ -352,7 +357,7 @@ def test_refresh_token_do_update_last_login_when_out_of_threshold(
variables = {"token": None, "csrf_token": csrf_token}
- time_ouf_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_ouf_of_threshold = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
)
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index eb17558995..a8b5f262a2 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -684,7 +684,7 @@ class AttributeAssignmentMixin:
attr_values: AttrValuesInput,
):
is_date_attr = attribute.input_type == AttributeInputType.DATE
- tz = datetime.timezone.utc
+ tz = datetime.UTC
if is_date_attr:
if not attr_values.date:
return ()
diff --git a/saleor/graphql/channel/mutations/base_channel_listing.py b/saleor/graphql/channel/mutations/base_channel_listing.py
index cb4dabd3e4..4e2ecba219 100644
--- a/saleor/graphql/channel/mutations/base_channel_listing.py
+++ b/saleor/graphql/channel/mutations/base_channel_listing.py
@@ -2,7 +2,6 @@ import datetime
from collections import defaultdict
from collections.abc import Iterable
-import pytz
from django.core.exceptions import ValidationError
from ....channel import models
@@ -117,7 +116,7 @@ class BaseChannelListingMutation(BaseMutation):
)
is_published = add_channel.get("is_published")
if is_published and not publication_date:
- add_channel["published_at"] = datetime.datetime.now(pytz.UTC)
+ add_channel["published_at"] = datetime.datetime.now(tz=datetime.UTC)
elif "publication_date" in add_channel or "published_at" in add_channel:
add_channel["published_at"] = publication_date
if invalid_channels:
diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.py
index fd778390c5..8d3ffe8578 100644
--- a/saleor/graphql/channel/mutations/utils.py
+++ b/saleor/graphql/channel/mutations/utils.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from typing import Optional
from django.core.exceptions import ValidationError
@@ -24,7 +24,9 @@ def clean_expire_orders_after(expire_orders_after: int) -> Optional[int]:
return expire_orders_after
-def clean_delete_expired_orders_after(delete_expired_orders_after: int) -> timedelta:
+def clean_delete_expired_orders_after(
+ delete_expired_orders_after: int,
+) -> datetime.timedelta:
if (
delete_expired_orders_after < 1
or delete_expired_orders_after > DELETE_EXPIRED_ORDERS_MAX_DAYS
@@ -38,7 +40,7 @@ def clean_delete_expired_orders_after(delete_expired_orders_after: int) -> timed
)
}
)
- return timedelta(days=delete_expired_orders_after)
+ return datetime.timedelta(days=delete_expired_orders_after)
def clean_input_order_settings(
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index 3a99ab3c9e..6e70e942d1 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import timedelta
from unittest import mock
import graphene
@@ -704,7 +704,9 @@ def test_channel_create_set_delete_expired_orders_after(
channel_data["orderSettings"]["deleteExpiredOrdersAfter"]
== delete_expired_after
)
- assert channel.delete_expired_orders_after == timedelta(days=delete_expired_after)
+ assert channel.delete_expired_orders_after == datetime.timedelta(
+ days=delete_expired_after
+ )
@pytest.mark.parametrize("delete_expired_after", [-1, 0, 121, 300])
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index d70cc5525d..32fdb8af2f 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import timedelta
from unittest.mock import call, patch
import graphene
@@ -1034,7 +1034,7 @@ def test_channel_update_delete_expired_orders_after(
channel_USD,
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=1)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=1)
channel_USD.save()
delete_expired_after = 10
@@ -1065,7 +1065,7 @@ def test_channel_update_delete_expired_orders_after(
channel_data["orderSettings"]["deleteExpiredOrdersAfter"]
== delete_expired_after
)
- assert channel_USD.delete_expired_orders_after == timedelta(
+ assert channel_USD.delete_expired_orders_after == datetime.timedelta(
days=delete_expired_after
)
@@ -1078,7 +1078,7 @@ def test_channel_update_set_incorrect_delete_expired_orders_after(
channel_USD,
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=1)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=1)
channel_USD.save()
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 671422dd04..09c8d07f23 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -13,7 +13,6 @@ from typing import (
)
import graphene
-import pytz
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
@@ -226,7 +225,7 @@ def check_lines_quantity(
def get_not_available_variants_for_purchase(
variants_id: set, channel_id: int
) -> tuple[set[int], set[str]]:
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
is_available_for_purchase = Q(
available_for_purchase_at__lte=today,
product__variants__id__in=variants_id,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 5de2f5c5e1..e4f39455cd 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
from decimal import Decimal
from unittest import mock
from unittest.mock import patch
@@ -1078,7 +1078,9 @@ def test_checkout_add_expired_gift_card_code(
staff_api_client, checkout_with_item, gift_card
):
# given
- gift_card.expiry_date = date.today() - timedelta(days=10)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=10)
gift_card.save(update_fields=["expiry_date"])
variables = {
@@ -1229,7 +1231,9 @@ def test_checkout_add_gift_card_code_in_active_gift_card(
def test_checkout_add_gift_card_code_in_expired_gift_card(
api_client, checkout_with_item, gift_card
):
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save()
variables = {
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 3d934a408c..f9f2613c44 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -1,11 +1,10 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import ANY, patch
import before_after
import graphene
import pytest
-import pytz
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models.aggregates import Sum
@@ -3018,7 +3017,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
checkout_line=other_checkout_line,
stock=stock,
quantity_reserved=quantity_available,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
checkout_line.quantity = 1
@@ -3081,7 +3080,7 @@ def test_checkout_complete_own_reservation(
checkout_line=checkout_line,
stock=stock,
quantity_reserved=quantity_available,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
manager = get_plugins_manager(allow_replica=False)
@@ -4146,7 +4145,8 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
@pytest.mark.parametrize(
- "available_for_purchase", [None, datetime.now(pytz.UTC) + timedelta(days=1)]
+ "available_for_purchase",
+ [None, datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=1)],
)
def test_checkout_complete_product_channel_listing_not_available_for_purchase(
user_api_client,
@@ -4644,7 +4644,7 @@ def test_checkout_complete_check_reservations_create(
reservations = Reservation.objects.all()
assert len(reservations) == 1
assert reservations[0].checkout_line.checkout.token == checkout.token
- assert reservations[0].reserved_until <= timezone.now() + timedelta(
+ assert reservations[0].reserved_until <= timezone.now() + datetime.timedelta(
seconds=settings.RESERVE_DURATION
)
assert Order.objects.count() == orders_count
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 7c24354477..eccef70acc 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -1,11 +1,10 @@
-from datetime import date, datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import ANY, patch
import before_after
import graphene
import pytest
-import pytz
from django.db.models.aggregates import Sum
from django.utils import timezone
from prices import TaxedMoney
@@ -1078,7 +1077,9 @@ def test_checkout_with_gift_card_not_applicable(
transaction_events_generator,
):
# given
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save(update_fields=["expiry_date"])
checkout = prepare_checkout_for_test(
@@ -3277,7 +3278,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
checkout_line=other_checkout_line,
stock=stock,
quantity_reserved=quantity_available,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
checkout_line.quantity = 1
@@ -3325,7 +3326,7 @@ def test_checkout_complete_own_reservation(
checkout_line=checkout_line,
stock=stock,
quantity_reserved=quantity_available,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
variables = {
@@ -4023,7 +4024,8 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
@pytest.mark.parametrize(
- "available_for_purchase", [None, datetime.now(pytz.UTC) + timedelta(days=1)]
+ "available_for_purchase",
+ [None, datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=1)],
)
def test_checkout_complete_product_channel_listing_not_available_for_purchase(
user_api_client,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index b3c00f2c98..147358a680 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -5,7 +5,6 @@ from unittest.mock import patch
import graphene
import pytest
-import pytz
from django.test import override_settings
from django.utils import timezone
@@ -1830,7 +1829,7 @@ def test_checkout_create_available_for_purchase_from_tomorrow_product(
product = variant.product
product.channel_listings.update(
- available_for_purchase_at=datetime.datetime.now(pytz.UTC)
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC)
+ datetime.timedelta(days=1)
)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py
index a351616571..780ad6da9f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py
@@ -1,7 +1,6 @@
-from datetime import datetime, timedelta
+import datetime
import graphene
-import pytz
from .....checkout.error_codes import CheckoutCreateFromOrderUnavailableVariantErrorCode
from .....checkout.models import Checkout
@@ -527,7 +526,7 @@ def test_checkout_create_from_order_variant_not_available_for_purchase(
user_api_client, order_with_lines
):
# given
- available_at = datetime.now(pytz.UTC) + timedelta(days=2)
+ available_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=2)
order_with_lines.user = user_api_client.user
order_with_lines.save()
Stock.objects.update(quantity=10)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index dd8f70ca4f..ab0f2f8858 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -5,7 +5,6 @@ from unittest.mock import patch
import graphene
import pytest
-import pytz
from django.test import override_settings
from django.utils import timezone
from prices import Money
@@ -1543,7 +1542,7 @@ def test_checkout_lines_add_with_available_for_purchase_from_tomorrow_product(
variant = stock.product_variant
product = stock.product_variant.product
product.channel_listings.update(
- available_for_purchase_at=datetime.datetime.now(pytz.UTC)
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC)
+ datetime.timedelta(days=1)
)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index 4a4b75fd8c..bd19dc261f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
from unittest.mock import patch
@@ -182,7 +182,7 @@ def test_checkout_remove_voucher_code_with_inactive_channel(
checkout_updated_webhook_mock, api_client, checkout_with_voucher
):
# given
- checkout_with_voucher.price_expiration = timezone.now() + timedelta(days=2)
+ checkout_with_voucher.price_expiration = timezone.now() + datetime.timedelta(days=2)
checkout_with_voucher.save(update_fields=["price_expiration"])
previous_checkout_last_change = checkout_with_voucher.last_change
@@ -309,7 +309,7 @@ def test_checkout_remove_promo_code_invalid_promo_code(
checkout_updated_webhook_mock, api_client, checkout_with_item
):
# given
- checkout_with_item.price_expiration = timezone.now() + timedelta(days=2)
+ checkout_with_item.price_expiration = timezone.now() + datetime.timedelta(days=2)
checkout_with_item.save(update_fields=["price_expiration"])
previous_checkout_last_change = checkout_with_item.last_change
variables = {
@@ -387,7 +387,7 @@ def test_checkout_remove_voucher_code_by_id_wrong_voucher(
# given
assert checkout_with_voucher.voucher_code is not None
checkout_with_voucher.gift_cards.add(gift_card)
- checkout_with_voucher.price_expiration = timezone.now() + timedelta(days=2)
+ checkout_with_voucher.price_expiration = timezone.now() + datetime.timedelta(days=2)
checkout_with_voucher.save(update_fields=["price_expiration"])
previous_checkout_last_change = checkout_with_voucher.last_change
@@ -581,7 +581,7 @@ def test_checkout_remove_voucher_code_invalidates_price(
checkout_updated_webhook_mock, api_client, checkout_with_item, voucher
):
# given
- checkout_with_item.price_expiration = timezone.now() + timedelta(days=2)
+ checkout_with_item.price_expiration = timezone.now() + datetime.timedelta(days=2)
checkout_with_item.voucher_code = voucher.code
checkout_with_item.save(update_fields=["voucher_code", "price_expiration"])
manager = get_plugins_manager(allow_replica=False)
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 4e8508dedc..4e3a9d7fb0 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -1,10 +1,9 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
import pytest
-import pytz
from django.db.models.aggregates import Sum
from django.utils import timezone
from prices import Money, TaxedMoney
@@ -1628,7 +1627,7 @@ def test_order_from_checkout_insufficient_stock_reserved_by_other_user(
checkout_line=other_checkout_line,
stock=stock,
quantity_reserved=quantity_available,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
checkout_line.quantity = 1
@@ -1678,7 +1677,7 @@ def test_order_from_checkout_own_reservation(
checkout_line=checkout_line,
stock=stock,
quantity_reserved=quantity_available,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -2302,7 +2301,8 @@ def test_order_from_draft_create_product_channel_listing_does_not_exist(
@pytest.mark.parametrize(
- "available_for_purchase", [None, datetime.now(pytz.UTC) + timedelta(days=1)]
+ "available_for_purchase",
+ [None, datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=1)],
)
def test_order_from_draft_create_product_channel_listing_not_available_for_purchase(
app_api_client,
diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.py
index b27c2f595b..b4bcc9aeba 100644
--- a/saleor/graphql/checkout/tests/test_checkout_filters.py
+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py
@@ -1,5 +1,5 @@
+import datetime
import uuid
-from datetime import date, timedelta
from decimal import Decimal
import graphene
@@ -139,16 +139,49 @@ def test_checkout_query_with_filter_channels_with_empty_channel(
(
{
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
}
},
1,
),
- ({"created": {"gte": str(date.today() - timedelta(days=3))}}, 1),
- ({"created": {"lte": str(date.today())}}, 2),
- ({"created": {"lte": str(date.today() - timedelta(days=3))}}, 1),
- ({"created": {"gte": str(date.today() + timedelta(days=1))}}, 0),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ ),
+ ({"created": {"lte": str(datetime.datetime.now(tz=datetime.UTC).date())}}, 2),
+ (
+ {
+ "created": {
+ "lte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ ),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ + datetime.timedelta(days=1)
+ )
+ }
+ },
+ 0,
+ ),
],
)
def test_checkout_query_with_filter_created(
diff --git a/saleor/graphql/checkout/tests/test_checkout_line_problems.py b/saleor/graphql/checkout/tests/test_checkout_line_problems.py
index 39f53810ba..6e8c706c00 100644
--- a/saleor/graphql/checkout/tests/test_checkout_line_problems.py
+++ b/saleor/graphql/checkout/tests/test_checkout_line_problems.py
@@ -1,7 +1,5 @@
import datetime
-import pytz
-
from ....product.models import ProductChannelListing, ProductVariantChannelListing
from ...core.utils import to_global_id_or_none
from ...tests.utils import get_graphql_content
@@ -317,7 +315,7 @@ def test_product_doesnt_have_channel_listing(
checkout = checkout_with_items_and_shipping
checkout_line = checkout.lines.first()
- available_at = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=5)
+ available_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=5)
product = checkout_line.variant.product
product.channel_listings.update(available_for_purchase_at=available_at)
diff --git a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
index e0e1885174..501f57300f 100644
--- a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
+++ b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest import mock
from unittest.mock import patch
@@ -352,7 +352,7 @@ def test_checkout_delivery_method_update_invalidate_prices(
@freeze_time("2020-12-12 12:00:00")
def test_invalidate_checkout_with_save(checkout, plugins_manager):
# given
- checkout.price_expiration = timezone.now() + timedelta(minutes=5)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(minutes=5)
checkout.save(update_fields=["price_expiration"])
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
@@ -371,8 +371,8 @@ def test_invalidate_checkout_with_save(checkout, plugins_manager):
@freeze_time("2020-12-12 12:00:00")
def test_invalidate_checkout_without_save(checkout, plugins_manager):
# given
- original_expiration = checkout.price_expiration = timezone.now() + timedelta(
- minutes=5
+ original_expiration = checkout.price_expiration = (
+ timezone.now() + datetime.timedelta(minutes=5)
)
checkout.save(update_fields=["price_expiration"])
lines, _ = fetch_checkout_lines(checkout)
diff --git a/saleor/graphql/checkout/tests/test_checkout_problems.py b/saleor/graphql/checkout/tests/test_checkout_problems.py
index 57ee1ae1ce..5b81fccc84 100644
--- a/saleor/graphql/checkout/tests/test_checkout_problems.py
+++ b/saleor/graphql/checkout/tests/test_checkout_problems.py
@@ -1,7 +1,5 @@
import datetime
-from datetime import timedelta
-import pytz
from django.utils import timezone
from ....product.models import ProductChannelListing, ProductVariantChannelListing
@@ -146,7 +144,7 @@ def test_checkout_problems_with_reservation(api_client, checkout_with_items):
stock.quantity = checkout_line.quantity
stock.save(update_fields=["quantity"])
- reserved_until = timezone.now() + timedelta(minutes=5)
+ reserved_until = timezone.now() + datetime.timedelta(minutes=5)
Reservation.objects.create(
checkout_line=checkout_line,
stock=stock,
@@ -313,7 +311,7 @@ def test_checkout_problems_when_product_doesnt_have_channel_listing(
checkout = checkout_with_items_and_shipping
checkout_line = checkout.lines.first()
- available_at = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=5)
+ available_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=5)
product = checkout_line.variant.product
product.channel_listings.update(available_for_purchase_at=available_at)
diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.py
index c696378bbb..99983869ad 100644
--- a/saleor/graphql/core/scalars.py
+++ b/saleor/graphql/core/scalars.py
@@ -1,8 +1,7 @@
+import datetime
import decimal
-from datetime import MAXYEAR, MINYEAR, datetime
import graphene
-import pytz
from graphene.types.generic import GenericScalar
from graphql.language import ast
from measurement.measures import Weight
@@ -162,10 +161,10 @@ class DateTime(graphene.DateTime):
@staticmethod
def parse_value(value):
parsed_value = graphene.DateTime.parse_value(value)
- if parsed_value is not None and isinstance(parsed_value, datetime):
- if parsed_value.year in [MINYEAR, MAXYEAR]:
+ if parsed_value is not None and isinstance(parsed_value, datetime.datetime):
+ if parsed_value.year in [datetime.MINYEAR, datetime.MAXYEAR]:
try:
- parsed_value.astimezone(tz=pytz.UTC)
+ parsed_value.astimezone(tz=datetime.UTC)
except OverflowError:
return None
return parsed_value
diff --git a/saleor/graphql/core/tests/test_validators.py b/saleor/graphql/core/tests/test_validators.py
index 466d5e8974..8ae658c39c 100644
--- a/saleor/graphql/core/tests/test_validators.py
+++ b/saleor/graphql/core/tests/test_validators.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
import pytest
@@ -52,8 +52,8 @@ def test_validate_price_precision_raise_error(value, currency):
def test_validate_end_is_after_start_raise_error():
- start_date = timezone.now() + timedelta(days=365)
- end_date = timezone.now() - timedelta(days=365)
+ start_date = timezone.now() + datetime.timedelta(days=365)
+ end_date = timezone.now() - datetime.timedelta(days=365)
with pytest.raises(ValidationError) as error:
validate_end_is_after_start(start_date, end_date)
@@ -63,8 +63,11 @@ def test_validate_end_is_after_start_raise_error():
@pytest.mark.parametrize(
("start_date", "end_date"),
[
- (timezone.now() - timedelta(days=365), timezone.now() + timedelta(days=365)),
- (timezone.now() + timedelta(days=365), None),
+ (
+ timezone.now() - datetime.timedelta(days=365),
+ timezone.now() + datetime.timedelta(days=365),
+ ),
+ (timezone.now() + datetime.timedelta(days=365), None),
],
)
def test_validate_end_is_after_start(start_date, end_date):
diff --git a/saleor/graphql/csv/tests/queries/test_export_files.py b/saleor/graphql/csv/tests/queries/test_export_files.py
index 1308b41574..a68ac59505 100644
--- a/saleor/graphql/csv/tests/queries/test_export_files.py
+++ b/saleor/graphql/csv/tests/queries/test_export_files.py
@@ -2,7 +2,6 @@ import datetime
import graphene
import pytest
-from django.utils import timezone
from .....account.models import User
from .....app.models import App
@@ -90,7 +89,7 @@ def test_filter_export_files_by_status(
("created_at_filter", "count"),
[
({"createdAt": {"gte": "2019-04-10T00:00:00+00:00"}}, 3),
- ({"createdAt": {"lte": "2019-04-10T00:00:00+00:00"}}, 2),
+ ({"createdAt": {"lte": "2019-04-10T00:00:00+00:00"}}, 4),
],
)
def test_filter_export_files_by_created_at_date(
@@ -119,7 +118,7 @@ def test_filter_export_files_by_created_at_date(
("ended_at_filter", "count"),
[
({"updatedAt": {"gte": "2019-04-18T00:00:00+00:00"}}, 3),
- ({"updatedAt": {"lte": "2019-04-18T00:00:00+00:00"}}, 2),
+ ({"updatedAt": {"lte": "2019-04-18T00:00:00+00:00"}}, 4),
],
)
def test_filter_export_files_by_ended_at_date(
@@ -254,9 +253,7 @@ def test_sort_export_files_query_by_updated_at_date(
permission_manage_apps,
staff_user,
):
- user_export_file.updated_at = datetime.datetime(
- 2010, 2, 19, tzinfo=timezone.get_current_timezone()
- )
+ user_export_file.updated_at = datetime.datetime(2010, 2, 19, tzinfo=datetime.UTC)
user_export_file.save()
second_export_file = ExportFile.objects.create(user=staff_user)
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_create.py b/saleor/graphql/discount/mutations/promotion/promotion_create.py
index 6a8e562f84..7f8ea8af06 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_create.py
@@ -1,8 +1,7 @@
+import datetime
from collections import defaultdict
-from datetime import datetime
import graphene
-import pytz
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -271,7 +270,7 @@ class PromotionCreate(ModelMutation):
Return true, when the start date is before the current date and the
promotion is not already finished.
"""
- now = datetime.now(pytz.utc)
+ now = datetime.datetime.now(tz=datetime.UTC)
start_date = instance.start_date
end_date = instance.end_date
@@ -302,7 +301,7 @@ class PromotionCreate(ModelMutation):
):
"""Send a webhook about starting promotion if it hasn't been sent yet."""
- now = datetime.now(pytz.utc)
+ now = datetime.datetime.now(tz=datetime.UTC)
cls.call_event(manager.promotion_started, instance)
instance.last_notification_scheduled_at = now
instance.save(update_fields=["last_notification_scheduled_at"])
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_update.py b/saleor/graphql/discount/mutations/promotion/promotion_update.py
index 3f5ddca319..b885afa9bd 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_update.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_update.py
@@ -1,8 +1,7 @@
-from datetime import datetime
+import datetime
from typing import Optional
import graphene
-import pytz
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -123,7 +122,7 @@ class PromotionUpdate(ModelMutation):
:return: "started" if promotion has started, "ended" if promotion has ended or
None if there was no toggle.
"""
- now = datetime.now(pytz.utc)
+ now = datetime.datetime.now(tz=datetime.UTC)
notification_date = instance.last_notification_scheduled_at
start_date = clean_input.get("start_date")
end_date = clean_input.get("end_date")
@@ -165,7 +164,9 @@ class PromotionUpdate(ModelMutation):
event = manager.promotion_ended
if event:
cls.call_event(event, instance)
- instance.last_notification_scheduled_at = datetime.now(pytz.utc)
+ instance.last_notification_scheduled_at = datetime.datetime.now(
+ tz=datetime.UTC
+ )
instance.save(update_fields=["last_notification_scheduled_at"])
@classmethod
diff --git a/saleor/graphql/discount/mutations/sale/sale_create.py b/saleor/graphql/discount/mutations/sale/sale_create.py
index 0006d27ff3..49183979d2 100644
--- a/saleor/graphql/discount/mutations/sale/sale_create.py
+++ b/saleor/graphql/discount/mutations/sale/sale_create.py
@@ -1,7 +1,6 @@
-from datetime import datetime
+import datetime
import graphene
-import pytz
from django.core.exceptions import ValidationError
from .....core.tracing import traced_atomic_transaction
@@ -144,7 +143,7 @@ class SaleCreate(ModelMutation):
Send the notification when the start date is before the current date and the
sale is not already finished.
"""
- now = datetime.now(pytz.utc)
+ now = datetime.datetime.now(tz=datetime.UTC)
start_date = instance.start_date
end_date = instance.end_date
diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.py
index 885efcdfee..39dff95c72 100644
--- a/saleor/graphql/discount/mutations/sale/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_update.py
@@ -1,7 +1,6 @@
-from datetime import datetime
+import datetime
import graphene
-import pytz
from django.core.exceptions import ValidationError
from django.db.models import Exists, OuterRef
@@ -235,7 +234,7 @@ class SaleUpdate(ModelMutation):
and the notification_date is not set or the last notification was sent
before start or end date.
"""
- now = datetime.now(pytz.utc)
+ now = datetime.datetime.now(tz=datetime.UTC)
notification_date = instance.last_notification_scheduled_at
start_date = input.get("start_date")
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
index 933f7fe517..7cb3788da2 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
import graphene
@@ -43,8 +43,8 @@ def test_promotion_create(
):
# given
staff_api_client.user.groups.add(permission_group_manage_discounts)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
rule_1_channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
rule_2_channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_update.py b/saleor/graphql/discount/tests/benchmark/test_promotion_update.py
index 5b9a85816d..f521394169 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_update.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_update.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import graphene
import pytest
@@ -19,8 +19,8 @@ def test_promotion_update(
):
# given
staff_api_client.user.groups.add(permission_group_manage_discounts)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
variables = {
"id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id),
diff --git a/saleor/graphql/discount/tests/deprecated/test_voucher_create.py b/saleor/graphql/discount/tests/deprecated/test_voucher_create.py
index 6c24b065cc..f4fe7a0f5b 100644
--- a/saleor/graphql/discount/tests/deprecated/test_voucher_create.py
+++ b/saleor/graphql/discount/tests/deprecated/test_voucher_create.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import timedelta
from unittest.mock import call, patch
import graphene
@@ -52,8 +52,8 @@ mutation voucherCreate(
def test_create_voucher(staff_api_client, permission_manage_discounts):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"name": "test voucher",
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
@@ -103,8 +103,8 @@ def test_create_voucher_trigger_webhook(
name = "test voucher"
code = "testcode123"
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"name": name,
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
@@ -153,8 +153,8 @@ def test_create_voucher_trigger_webhook(
def test_create_voucher_with_empty_code(staff_api_client, permission_manage_discounts):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"name": "test voucher",
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
@@ -183,8 +183,8 @@ def test_create_voucher_with_existing_gift_card_code(
staff_api_client, gift_card, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"name": "test voucher",
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
@@ -215,8 +215,8 @@ def test_create_voucher_with_existing_voucher_code(
staff_api_client, voucher_shipping_type, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"name": "test voucher",
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
@@ -247,8 +247,8 @@ def test_create_voucher_with_enddate_before_startdate(
staff_api_client, voucher_shipping_type, permission_manage_discounts
):
# given
- start_date = timezone.now() + timedelta(days=365)
- end_date = timezone.now() - timedelta(days=365)
+ start_date = timezone.now() + datetime.timedelta(days=365)
+ end_date = timezone.now() - datetime.timedelta(days=365)
variables = {
"name": "test voucher",
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_create.py
index b3b1f97830..a52ce15439 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_create.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
from unittest.mock import ANY, patch
@@ -76,8 +76,8 @@ def test_promotion_create_by_staff_user(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
rule_1_channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
rule_2_channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
@@ -193,8 +193,8 @@ def test_promotion_create_by_app(
product,
):
# given
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
promotion_name = "test promotion"
catalogue_predicate = {
@@ -274,8 +274,8 @@ def test_promotion_create_by_customer(
category,
):
# given
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
promotion_name = "test promotion"
catalogue_predicate = {
@@ -326,8 +326,8 @@ def test_promotion_create_with_order_rule(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
order_predicate = {
@@ -388,8 +388,8 @@ def test_promotion_create_fixed_reward_value_multiple_currencies(
product,
):
# given
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [
graphene.Node.to_global_id("Channel", channel.pk)
for channel in [channel_USD, channel_PLN]
@@ -459,8 +459,8 @@ def test_promotion_create_invalid_price_precision(
product,
):
# given
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
promotion_name = "test promotion"
@@ -526,8 +526,8 @@ def test_promotion_create_invalid_percentage_value(
product,
):
# given
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [
graphene.Node.to_global_id("Channel", channel.pk)
for channel in [channel_USD, channel_PLN]
@@ -599,7 +599,7 @@ def test_promotion_create_only_name_and_end_date(
product,
):
# given
- end_date = timezone.now() + timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
variables = {
@@ -651,8 +651,8 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() + timedelta(days=10)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() + datetime.timedelta(days=10)
+ end_date = timezone.now() + datetime.timedelta(days=30)
rule_1_channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
rule_2_channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
@@ -765,8 +765,8 @@ def test_promotion_create_missing_predicate(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
catalogue_predicate = {
@@ -841,8 +841,8 @@ def test_promotion_create_missing_reward_value(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
catalogue_predicate = {
@@ -910,8 +910,8 @@ def test_promotion_create_missing_reward_value_type(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
catalogue_predicate = {
@@ -978,8 +978,8 @@ def test_promotion_create_invalid_channel_id(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
catalogue_predicate = {
@@ -1050,8 +1050,8 @@ def test_promotion_create_mixed_catalogue_and_order_rules(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
rule_1_channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
rule_2_channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
@@ -1139,8 +1139,8 @@ def test_promotion_create_mixed_currencies_for_price_based_predicate(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
order_predicate = {
@@ -1203,8 +1203,8 @@ def test_promotion_create_multiple_errors(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [graphene.Node.to_global_id("Channel", -1)]
promotion_name = "test promotion"
@@ -1287,8 +1287,8 @@ def test_promotion_create_end_date_before_start_date(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() + timedelta(days=30)
- end_date = timezone.now() - timedelta(days=30)
+ start_date = timezone.now() + datetime.timedelta(days=30)
+ end_date = timezone.now() - datetime.timedelta(days=30)
promotion_name = "test promotion"
catalogue_predicate = {
@@ -1358,8 +1358,8 @@ def test_promotion_create_invalid_catalogue_predicate(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
rule_1_channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
rule_2_channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
@@ -1448,8 +1448,8 @@ def test_promotion_create_exceeds_rules_number_limit(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
order_predicate = {
@@ -1508,8 +1508,8 @@ def test_promotion_create_exceeds_gifts_number_limit(
# given
gift_limit = 1
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
promotion_name = "test promotion"
order_predicate = {
@@ -1571,8 +1571,8 @@ def test_promotion_create_rules_without_channels_and_percentage_reward(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
catalogue_predicate = {
"variantPredicate": {
@@ -2066,8 +2066,8 @@ def test_promotion_create_without_catalogue_predicate(
product,
):
# given
- start_date = timezone.now() - timedelta(days=30)
- end_date = timezone.now() + timedelta(days=30)
+ start_date = timezone.now() - datetime.timedelta(days=30)
+ end_date = timezone.now() + datetime.timedelta(days=30)
channel_ids = [
graphene.Node.to_global_id("Channel", channel.pk)
for channel in [channel_USD, channel_PLN]
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_update.py
index 362ac6cfe9..51a6275037 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_update.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
import graphene
@@ -50,8 +50,8 @@ def test_promotion_update_by_staff_user(
# given
promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=1)
- end_date = timezone.now() + timedelta(days=10)
+ start_date = timezone.now() - datetime.timedelta(days=1)
+ end_date = timezone.now() + datetime.timedelta(days=10)
new_promotion_name = "new test promotion"
variables = {
@@ -107,7 +107,7 @@ def test_promotion_update_by_app(
promotion.end_date = None
promotion.save(update_fields=["start_date", "end_date"])
- end_date = timezone.now() + timedelta(days=2)
+ end_date = timezone.now() + datetime.timedelta(days=2)
new_promotion_name = "new test promotion"
variables = {
@@ -159,7 +159,9 @@ def test_promotion_update_dates_dont_change(
# given
promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- promotion.last_notification_scheduled_at = timezone.now() - timedelta(hours=1)
+ promotion.last_notification_scheduled_at = timezone.now() - datetime.timedelta(
+ hours=1
+ )
promotion.save(update_fields=["last_notification_scheduled_at"])
previous_notification_date = promotion.last_notification_scheduled_at
@@ -216,8 +218,8 @@ def test_promotion_update_by_customer(
):
# given
promotion = catalogue_promotion
- start_date = timezone.now() + timedelta(days=1)
- end_date = timezone.now() + timedelta(days=10)
+ start_date = timezone.now() + datetime.timedelta(days=1)
+ end_date = timezone.now() + datetime.timedelta(days=10)
new_promotion_name = "new test promotion"
variables = {
@@ -251,8 +253,8 @@ def test_promotion_update_end_date_before_start_date(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() + timedelta(days=1)
- end_date = timezone.now() - timedelta(days=10)
+ start_date = timezone.now() + datetime.timedelta(days=1)
+ end_date = timezone.now() - datetime.timedelta(days=10)
new_promotion_name = "new test promotion"
variables = {
@@ -290,8 +292,8 @@ def test_promotion_update_clears_old_sale_id(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=1)
- end_date = timezone.now() + timedelta(days=10)
+ start_date = timezone.now() - datetime.timedelta(days=1)
+ end_date = timezone.now() + datetime.timedelta(days=10)
promotion = promotion_converted_from_sale
assert promotion.old_sale_id
@@ -336,8 +338,8 @@ def test_promotion_update_events(
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- start_date = timezone.now() - timedelta(days=1)
- end_date = timezone.now() + timedelta(days=10)
+ start_date = timezone.now() - datetime.timedelta(days=1)
+ end_date = timezone.now() + datetime.timedelta(days=10)
variables = {
"id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id),
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_create.py b/saleor/graphql/discount/tests/mutations/test_sale_create.py
index 895a1f280e..c342b73f95 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_create.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
import graphene
@@ -51,8 +51,8 @@ def test_create_sale(
):
# given
query = SALE_CREATE_MUTATION
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
product_ids = [
graphene.Node.to_global_id("Product", product.id) for product in product_list
]
@@ -115,7 +115,7 @@ def test_create_sale_only_start_date(
):
# given
query = SALE_CREATE_MUTATION
- start_date = timezone.now() - timedelta(days=10)
+ start_date = timezone.now() - datetime.timedelta(days=10)
product_ids = [
graphene.Node.to_global_id("Product", product.id) for product in product_list
]
@@ -160,8 +160,8 @@ def test_create_sale_with_end_date_before_startdate(
):
# given
query = SALE_CREATE_MUTATION
- start_date = timezone.now() + timedelta(days=365)
- end_date = timezone.now() - timedelta(days=365)
+ start_date = timezone.now() + datetime.timedelta(days=365)
+ end_date = timezone.now() - datetime.timedelta(days=365)
variables = {
"input": {
"name": "test sale",
@@ -196,8 +196,8 @@ def test_create_sale_start_date_and_end_date_before_current_date(
):
# given
query = SALE_CREATE_MUTATION
- start_date = timezone.now() - timedelta(days=20)
- end_date = timezone.now() - timedelta(days=10)
+ start_date = timezone.now() - datetime.timedelta(days=20)
+ end_date = timezone.now() - datetime.timedelta(days=10)
product_ids = [
graphene.Node.to_global_id("Product", product.id) for product in product_list
]
@@ -248,8 +248,8 @@ def test_create_sale_start_date_and_end_date_after_current_date(
):
# given
query = SALE_CREATE_MUTATION
- start_date = timezone.now() + timedelta(days=10)
- end_date = timezone.now() + timedelta(days=20)
+ start_date = timezone.now() + datetime.timedelta(days=10)
+ end_date = timezone.now() + datetime.timedelta(days=20)
product_ids = [
graphene.Node.to_global_id("Product", product.id) for product in product_list
]
@@ -300,8 +300,8 @@ def test_create_sale_empty_predicate(
):
# given
query = SALE_CREATE_MUTATION
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
"name": "test sale",
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_update.py b/saleor/graphql/discount/tests/mutations/test_sale_update.py
index 2d2c6d2632..db779c15ad 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_update.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
import graphene
@@ -183,7 +183,7 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
- start_date = timezone.now() + timedelta(days=1)
+ start_date = timezone.now() + datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -241,13 +241,13 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(
query = SALE_UPDATE_MUTATION
promotion = promotion_converted_from_sale
- last_notification_scheduled_at = timezone.now() - timedelta(minutes=5)
+ last_notification_scheduled_at = timezone.now() - datetime.timedelta(minutes=5)
promotion.last_notification_scheduled_at = last_notification_scheduled_at
promotion.save(update_fields=["last_notification_scheduled_at"])
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
- start_date = timezone.now() - timedelta(days=1)
+ start_date = timezone.now() - datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -313,7 +313,7 @@ def test_update_sale_start_date_before_current_date_notification_sent(
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
- start_date = timezone.now() - timedelta(days=1)
+ start_date = timezone.now() - datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -372,12 +372,12 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(
query = SALE_UPDATE_MUTATION
promotion = promotion_converted_from_sale
- promotion.start_date = timezone.now() - timedelta(days=1)
+ promotion.start_date = timezone.now() - datetime.timedelta(days=1)
promotion.save(update_fields=["start_date"])
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
- end_date = timezone.now() + timedelta(days=1)
+ end_date = timezone.now() + datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -437,14 +437,14 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(
now = timezone.now()
promotion = promotion_converted_from_sale
- last_notification_scheduled_at = now - timedelta(minutes=5)
+ last_notification_scheduled_at = now - datetime.timedelta(minutes=5)
promotion.last_notification_scheduled_at = last_notification_scheduled_at
- promotion.start_date = now - timedelta(days=2)
+ promotion.start_date = now - datetime.timedelta(days=2)
promotion.save(update_fields=["last_notification_scheduled_at", "start_date"])
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
- end_date = now - timedelta(days=1)
+ end_date = now - datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -503,12 +503,12 @@ def test_update_sale_end_date_before_current_date_notification_sent(
promotion = promotion_converted_from_sale
promotion.last_notification_scheduled_at = None
- promotion.start_date = timezone.now() - timedelta(days=2)
+ promotion.start_date = timezone.now() - datetime.timedelta(days=2)
promotion.save(update_fields=["last_notification_scheduled_at", "start_date"])
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
- end_date = timezone.now() - timedelta(days=1)
+ end_date = timezone.now() - datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -775,9 +775,9 @@ def test_update_sale_end_date_before_start_date(
query = SALE_UPDATE_MUTATION
promotion = promotion_converted_from_sale
- promotion.start_date = timezone.now() + timedelta(days=1)
+ promotion.start_date = timezone.now() + datetime.timedelta(days=1)
promotion.save(update_fields=["start_date"])
- end_date = timezone.now() - timedelta(days=1)
+ end_date = timezone.now() - datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),
@@ -827,9 +827,9 @@ def test_update_sale_with_none_values(
promotion = promotion_converted_from_sale
promotion.name = "Sale name"
- start_date = timezone.now() + timedelta(days=1)
+ start_date = timezone.now() + datetime.timedelta(days=1)
promotion.start_date = start_date
- promotion.end_date = timezone.now() + timedelta(days=5)
+ promotion.end_date = timezone.now() + datetime.timedelta(days=5)
promotion.save(update_fields=["name", "start_date", "end_date"])
variables = {
@@ -882,7 +882,7 @@ def test_update_sale_with_promotion_id(
# given
query = SALE_UPDATE_MUTATION
promotion = promotion_converted_from_sale
- end_date = timezone.now() - timedelta(days=1)
+ end_date = timezone.now() - datetime.timedelta(days=1)
variables = {
"id": graphene.Node.to_global_id("Promotion", promotion.id),
diff --git a/saleor/graphql/discount/tests/mutations/test_voucher_create.py b/saleor/graphql/discount/tests/mutations/test_voucher_create.py
index e19be66dbf..ec75eb9fef 100644
--- a/saleor/graphql/discount/tests/mutations/test_voucher_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_voucher_create.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import timedelta
from unittest.mock import call, patch
import graphene
@@ -66,8 +66,8 @@ def test_create_voucher(
category,
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
name = "test voucher"
variables = {
@@ -127,8 +127,8 @@ def test_create_voucher_no_codes(
category,
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
name = "test voucher"
variables = {
@@ -171,8 +171,8 @@ def test_create_voucher_return_error_when_code_and_codes_args_combined(
staff_api_client, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
@@ -208,8 +208,8 @@ def test_create_voucher_return_error_when_code_or_codes_arg_not_in_input(
staff_api_client, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
@@ -254,8 +254,8 @@ def test_create_voucher_trigger_webhook(
mocked_get_webhooks_for_voucher_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
code_1 = "testcode123"
code_2 = "testcode456"
@@ -330,8 +330,8 @@ def test_create_voucher_trigger_webhook(
def test_create_voucher_with_empty_code(staff_api_client, permission_manage_discounts):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
"name": "test voucher",
@@ -361,8 +361,8 @@ def test_create_voucher_with_spaces_in_code(
staff_api_client, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
"name": "test voucher",
@@ -392,8 +392,8 @@ def test_create_voucher_with_duplicated_codes(
staff_api_client, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
"name": "test voucher",
@@ -426,8 +426,8 @@ def test_create_voucher_with_existing_gift_card_code(
staff_api_client, gift_card, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
variables = {
"input": {
"name": "test voucher",
@@ -462,8 +462,8 @@ def test_create_voucher_with_existing_voucher_code(
staff_api_client, voucher_shipping_type, permission_manage_discounts
):
# given
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
+ start_date = timezone.now() - datetime.timedelta(days=365)
+ end_date = timezone.now() + datetime.timedelta(days=365)
code = voucher_shipping_type.codes.first().code
variables = {
"input": {
@@ -495,8 +495,8 @@ def test_create_voucher_with_enddate_before_startdate(
staff_api_client, permission_manage_discounts
):
# given
- start_date = timezone.now() + timedelta(days=365)
- end_date = timezone.now() - timedelta(days=365)
+ start_date = timezone.now() + datetime.timedelta(days=365)
+ end_date = timezone.now() - datetime.timedelta(days=365)
variables = {
"input": {
diff --git a/saleor/graphql/discount/tests/queries/test_promotions.py b/saleor/graphql/discount/tests/queries/test_promotions.py
index 2404830704..5949cce2be 100644
--- a/saleor/graphql/discount/tests/queries/test_promotions.py
+++ b/saleor/graphql/discount/tests/queries/test_promotions.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from django.utils import timezone
@@ -128,7 +128,7 @@ def test_query_promotions_pagination(
"where": {
"endDate": {
"range": {
- "gte": timezone.now() + timedelta(days=15),
+ "gte": timezone.now() + datetime.timedelta(days=15),
}
}
},
diff --git a/saleor/graphql/discount/tests/queries/test_promotions_filtering.py b/saleor/graphql/discount/tests/queries/test_promotions_filtering.py
index 6647f8bc39..073e29b348 100644
--- a/saleor/graphql/discount/tests/queries/test_promotions_filtering.py
+++ b/saleor/graphql/discount/tests/queries/test_promotions_filtering.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import graphene
import pytest
@@ -107,8 +107,8 @@ def test_query_promotions_filter_by_name(
(
{
"range": {
- "gte": (timezone.now() + timedelta(days=5)).isoformat(),
- "lte": (timezone.now() + timedelta(days=25)).isoformat(),
+ "gte": (timezone.now() + datetime.timedelta(days=5)).isoformat(),
+ "lte": (timezone.now() + datetime.timedelta(days=25)).isoformat(),
}
},
[0, 1],
@@ -116,7 +116,7 @@ def test_query_promotions_filter_by_name(
(
{
"range": {
- "gte": (timezone.now() + timedelta(days=5)).isoformat(),
+ "gte": (timezone.now() + datetime.timedelta(days=5)).isoformat(),
}
},
[0, 1, 2],
@@ -124,7 +124,7 @@ def test_query_promotions_filter_by_name(
(
{
"range": {
- "lte": (timezone.now() + timedelta(days=25)).isoformat(),
+ "lte": (timezone.now() + datetime.timedelta(days=25)).isoformat(),
}
},
[0, 1],
@@ -132,7 +132,7 @@ def test_query_promotions_filter_by_name(
(
{
"range": {
- "lte": (timezone.now() - timedelta(days=5)).isoformat(),
+ "lte": (timezone.now() - datetime.timedelta(days=5)).isoformat(),
}
},
[],
@@ -175,8 +175,8 @@ def test_query_promotions_filter_by_end_date(
(
{
"range": {
- "gte": (timezone.now() + timedelta(days=3)).isoformat(),
- "lte": (timezone.now() + timedelta(days=25)).isoformat(),
+ "gte": (timezone.now() + datetime.timedelta(days=3)).isoformat(),
+ "lte": (timezone.now() + datetime.timedelta(days=25)).isoformat(),
}
},
[1, 2],
@@ -184,7 +184,7 @@ def test_query_promotions_filter_by_end_date(
(
{
"range": {
- "gte": (timezone.now() + timedelta(days=3)).isoformat(),
+ "gte": (timezone.now() + datetime.timedelta(days=3)).isoformat(),
}
},
[1, 2],
@@ -192,7 +192,7 @@ def test_query_promotions_filter_by_end_date(
(
{
"range": {
- "lte": (timezone.now() + timedelta(days=25)).isoformat(),
+ "lte": (timezone.now() + datetime.timedelta(days=25)).isoformat(),
}
},
[0, 1, 2],
@@ -200,7 +200,7 @@ def test_query_promotions_filter_by_end_date(
(
{
"range": {
- "lte": (timezone.now() - timedelta(days=5)).isoformat(),
+ "lte": (timezone.now() - datetime.timedelta(days=5)).isoformat(),
}
},
[],
diff --git a/saleor/graphql/discount/tests/queries/test_promotions_sorting.py b/saleor/graphql/discount/tests/queries/test_promotions_sorting.py
index ab3dfab8dc..c8a15f2b3e 100644
--- a/saleor/graphql/discount/tests/queries/test_promotions_sorting.py
+++ b/saleor/graphql/discount/tests/queries/test_promotions_sorting.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -102,7 +102,7 @@ def test_sorting_promotions_by_start_date(
):
# given
promotion = catalogue_promotion
- promotion.start_date = timezone.now() + timedelta(days=3)
+ promotion.start_date = timezone.now() + datetime.timedelta(days=3)
promotion.save(update_fields=["start_date"])
promotion_list.insert(1, promotion)
variables = {
diff --git a/saleor/graphql/discount/tests/queries/test_sales_filtering.py b/saleor/graphql/discount/tests/queries/test_sales_filtering.py
index 5d0d1683ab..071abb35fb 100644
--- a/saleor/graphql/discount/tests/queries/test_sales_filtering.py
+++ b/saleor/graphql/discount/tests/queries/test_sales_filtering.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -28,7 +28,7 @@ QUERY_SALES_WITH_FILTER = """
(
{"status": "ACTIVE"},
timezone.now().replace(year=2015, month=1, day=1),
- timezone.now() + timedelta(days=365),
+ timezone.now() + datetime.timedelta(days=365),
2,
),
(
@@ -39,8 +39,8 @@ QUERY_SALES_WITH_FILTER = """
),
(
{"status": "SCHEDULED"},
- timezone.now() + timedelta(days=3),
- timezone.now() + timedelta(days=10),
+ timezone.now() + datetime.timedelta(days=3),
+ timezone.now() + datetime.timedelta(days=10),
1,
),
],
diff --git a/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py b/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py
index 3b182b39d0..0eb2528538 100644
--- a/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py
+++ b/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -29,7 +29,7 @@ QUERY_VOUCHERS_WITH_FILTER = """
(
{"status": "ACTIVE"},
timezone.now().replace(year=2015, month=1, day=1),
- timezone.now() + timedelta(days=365),
+ timezone.now() + datetime.timedelta(days=365),
2,
),
(
@@ -40,8 +40,8 @@ QUERY_VOUCHERS_WITH_FILTER = """
),
(
{"status": "SCHEDULED"},
- timezone.now() + timedelta(days=3),
- timezone.now() + timedelta(days=10),
+ timezone.now() + datetime.timedelta(days=3),
+ timezone.now() + datetime.timedelta(days=10),
1,
),
],
diff --git a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
index 3b0ed5c096..446a3c42d2 100644
--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
import graphene
import pytest
@@ -112,7 +112,9 @@ def test_update_gift_card(
):
# given
initial_balance = 100.0
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
old_tag = gift_card.tags.first()
tag = "new-gift-card-tag"
variables = {
diff --git a/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_activate.py b/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_activate.py
index 92a3a562b6..a393631050 100644
--- a/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_activate.py
+++ b/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_activate.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
from unittest import mock
import graphene
@@ -150,8 +150,12 @@ def test_gift_card_bulk_activate_expired_cards(
# given
gift_card.is_active = False
gift_card_expiry_date.is_active = True
- gift_card_created_by_staff.expiry_date = date.today() - timedelta(days=2)
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card_created_by_staff.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=2)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_cards = [gift_card, gift_card_expiry_date, gift_card_created_by_staff]
GiftCard.objects.bulk_update(gift_cards, ["is_active", "expiry_date"])
diff --git a/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_create.py b/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_create.py
index 5e5fcfafef..5bcf443c9f 100644
--- a/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_create.py
+++ b/saleor/graphql/giftcard/tests/bulk_mutations/test_gift_card_bulk_create.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
from unittest import mock
import pytest
@@ -232,7 +232,9 @@ def test_create_gift_cards_with_expiry_date_by_app(
tag = "gift-card-tag"
count = 5
is_active = False
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
variables = {
"input": {
"count": count,
@@ -344,7 +346,9 @@ def test_create_gift_cards_invalid_count_value(
currency = "USD"
tag = "gift-card-tag"
is_active = False
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
variables = {
"input": {
"count": count_value,
@@ -392,7 +396,9 @@ def test_create_gift_cards_too_many_decimal_places_in_balance_amount(
currency = "USD"
tag = "gift-card-tag"
is_active = False
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
variables = {
"input": {
"count": 2,
@@ -440,7 +446,9 @@ def test_create_gift_cards_zero_balance_amount(
currency = "USD"
tag = "gift-card-tag"
is_active = False
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
variables = {
"input": {
"count": 2,
@@ -477,7 +485,10 @@ def test_create_gift_cards_zero_balance_amount(
assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
[email protected]("date_value", [date(1999, 1, 1), date.today()])
+ "date_value",
+ [datetime.date(1999, 1, 1), datetime.datetime.now(tz=datetime.UTC).date()],
+)
def test_create_gift_cards_invalid_expiry_date(
date_value,
app_api_client,
diff --git a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
index 267e0a9a3d..8de75ed672 100644
--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
@@ -1,4 +1,4 @@
-from datetime import date
+import datetime
from ....tests.utils import get_graphql_content
@@ -59,8 +59,8 @@ def test_create_never_expiry_gift_card(
initial_balance = 100
currency = "USD"
tag = "gift-card-tag"
- start_date = date(day=1, month=1, year=2018)
- end_date = date(day=1, month=1, year=2019)
+ start_date = datetime.date(day=1, month=1, year=2018)
+ end_date = datetime.date(day=1, month=1, year=2019)
initial_balance = 100
variables = {
"balance": {
diff --git a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py
index b25455c1e3..34b7ab03eb 100644
--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py
+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py
@@ -1,4 +1,4 @@
-from datetime import date
+import datetime
import graphene
@@ -25,7 +25,7 @@ def test_query_gift_card(
):
query = QUERY_GIFT_CARD_BY_ID
- end_date = date(day=1, month=1, year=2018)
+ end_date = datetime.date(day=1, month=1, year=2018)
gift_card.expiry_date = end_date
gift_card.save(update_fields=["expiry_date"])
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
index f9376f97ac..7fd6e78d53 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import date, timedelta
from unittest import mock
import graphene
@@ -161,7 +161,9 @@ def test_activate_expired_gift_card(
):
# given
gift_card.is_active = False
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save(update_fields=["expiry_date", "is_active"])
variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.id)}
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py
index c83c1007c5..8e5c6793f6 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import date, timedelta
from unittest import mock
import graphene
@@ -167,7 +167,9 @@ def test_gift_card_add_note_expired_card(
# given
staff_user = staff_api_client.user
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save(update_fields=["expiry_date"])
gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
index 96eca554aa..7273f296bf 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import date, timedelta
from unittest import mock
import graphene
@@ -520,7 +520,9 @@ def test_create_gift_card_with_expiry_date(
# given
initial_balance = 100
currency = "USD"
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
tag = "gift-card-tag"
variables = {
"input": {
@@ -583,7 +585,10 @@ def test_create_gift_card_with_expiry_date(
)
[email protected]("date_value", [date(1999, 1, 1), date.today()])
+ "date_value",
+ [datetime.date(1999, 1, 1), datetime.datetime.now(tz=datetime.UTC).date()],
+)
def test_create_gift_card_with_expiry_date_type_invalid(
date_value,
staff_api_client,
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py
index a0b59d8d25..9a278a6b4b 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import date, timedelta
from unittest import mock
import graphene
@@ -313,7 +313,9 @@ def test_resend_gift_card_expired_card(
permission_manage_apps,
):
# given
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save(update_fields=["expiry_date"])
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
index c34849ea3f..fa5869d46e 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import date, timedelta
from unittest import mock
import graphene
@@ -107,7 +107,9 @@ def test_update_gift_card(
initial_balance = 100.0
currency = gift_card.currency
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
old_tag = gift_card.tags.first().name
new_tag = "new-gift-card-tag"
tags_count = GiftCardTag.objects.count()
@@ -228,7 +230,9 @@ def test_update_gift_card_by_app(
initial_balance = 100.0
currency = gift_card.currency
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
new_tag = gift_card_tag_list[0].name
tags_count = GiftCardTag.objects.count()
variables = {
@@ -496,7 +500,9 @@ def test_update_used_gift_card_to_expiry_date(
):
# given
gift_card = gift_card_used
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
@@ -576,7 +582,9 @@ def test_update_gift_card_date_in_past(
permission_manage_apps,
):
# given
- date_value = date.today() - timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() - datetime.timedelta(
+ days=365
+ )
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
@@ -614,7 +622,9 @@ def test_update_gift_card_expired_card(
permission_manage_apps,
):
# given
- gift_card.expiry_date = date.today() - timedelta(days=1)
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
gift_card.save(update_fields=["expiry_date"])
variables = {
@@ -753,7 +763,9 @@ def test_update_gift_card_trigger_webhook(
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
initial_balance = 100.0
- date_value = date.today() + timedelta(days=365)
+ date_value = datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(
+ days=365
+ )
new_tag = "new-gift-card-tag"
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.py
index 4058f90ec2..680e6c2820 100644
--- a/saleor/graphql/giftcard/types.py
+++ b/saleor/graphql/giftcard/types.py
@@ -204,14 +204,22 @@ class GiftCardEvent(ModelObjectType[models.GiftCardEvent]):
def resolve_expiry_date(root: models.GiftCardEvent, _info):
expiry_date = root.parameters.get("expiry_date")
return (
- datetime.datetime.strptime(expiry_date, "%Y-%m-%d") if expiry_date else None
+ datetime.datetime.strptime(expiry_date, "%Y-%m-%d").replace(
+ tzinfo=datetime.UTC
+ )
+ if expiry_date
+ else None
)
@staticmethod
def resolve_old_expiry_date(root: models.GiftCardEvent, _info):
expiry_date = root.parameters.get("old_expiry_date")
return (
- datetime.datetime.strptime(expiry_date, "%Y-%m-%d") if expiry_date else None
+ datetime.datetime.strptime(expiry_date, "%Y-%m-%d").replace(
+ tzinfo=datetime.UTC
+ )
+ if expiry_date
+ else None
)
diff --git a/saleor/graphql/meta/tests/mutations/test_checkout.py b/saleor/graphql/meta/tests/mutations/test_checkout.py
index 33313b3262..9fbc73c9df 100644
--- a/saleor/graphql/meta/tests/mutations/test_checkout.py
+++ b/saleor/graphql/meta/tests/mutations/test_checkout.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
import graphene
@@ -391,7 +391,7 @@ def test_add_metadata_for_checkout_triggers_webhooks_with_checkout_updated(
) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- checkout.price_expiration = timezone.now() - timedelta(hours=10)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(hours=10)
checkout.save(update_fields=["price_expiration"])
# when
response = execute_update_public_metadata_for_item(
@@ -472,7 +472,7 @@ def test_add_metadata_for_checkout_triggers_webhooks_with_updated_metadata(
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- checkout.price_expiration = timezone.now() - timedelta(hours=10)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(hours=10)
checkout.save(update_fields=["price_expiration"])
# when
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index a5e6291c3c..f30a3d22a2 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -1,9 +1,9 @@
import copy
+import datetime
from collections import defaultdict
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from dataclasses import fields as dataclass_fields
-from datetime import datetime, timedelta
from decimal import Decimal
from typing import Any, Optional
from uuid import UUID
@@ -767,14 +767,14 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
return object_storage
@classmethod
- def is_datetime_valid(cls, date: datetime) -> bool:
+ def is_datetime_valid(cls, date: datetime.datetime) -> bool:
"""We accept future time values with 5 minutes from current time.
Some systems might have incorrect time that is in the future compared to Saleor.
At the same time, we don't want to create orders that are too far in the future.
"""
current_time = timezone.now()
- future_time = current_time + timedelta(minutes=MINUTES_DIFF)
+ future_time = current_time + datetime.timedelta(minutes=MINUTES_DIFF)
if not date.tzinfo:
raise ValidationError(
message="Input 'date' must be timezone-aware. "
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index 2198440e94..f14a54d949 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1,9 +1,8 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import call, patch
import graphene
-import pytz
from django.db.models import Sum
from django.test import override_settings
from freezegun import freeze_time
@@ -932,7 +931,8 @@ def test_draft_order_complete_unavailable_for_purchase(
product = order.lines.first().variant.product
product.channel_listings.update(
- available_for_purchase_at=datetime.now(pytz.UTC) + timedelta(days=5)
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC)
+ + datetime.timedelta(days=5)
)
order_id = graphene.Node.to_global_id("Order", order.id)
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index 02671f8da3..bd7d01e8e6 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -1,10 +1,9 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import Mock, patch
import graphene
import pytest
-import pytz
from django.test import override_settings
from prices import Money
@@ -2141,7 +2140,7 @@ def test_draft_order_create_with_channel_with_unpublished_product_by_date(
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
- next_day = datetime.now(pytz.UTC) + timedelta(days=1)
+ next_day = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=1)
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
variant_1 = product_without_shipping.variants.first()
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
index c476353add..74db145b14 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_create.py
@@ -1,5 +1,5 @@
import copy
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import patch
@@ -1991,7 +1991,7 @@ def test_order_bulk_create_error_order_future_date(
orders_count = Order.objects.count()
order = order_bulk_input
- order["createdAt"] = timezone.now() + timedelta(minutes=MINUTES_DIFF + 1)
+ order["createdAt"] = timezone.now() + datetime.timedelta(minutes=MINUTES_DIFF + 1)
staff_api_client.user.user_permissions.add(
permission_manage_orders_import,
@@ -2027,7 +2027,9 @@ def test_order_bulk_create_invalid_date_format(
orders_count = Order.objects.count()
order = order_bulk_input
- current_time = datetime.now() + timedelta(minutes=MINUTES_DIFF + 1)
+ current_time = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ minutes=MINUTES_DIFF + 1
+ )
order["createdAt"] = current_time.strftime("%Y-%m-%dT%H:%M:%S")
staff_api_client.user.user_permissions.add(
@@ -2064,7 +2066,7 @@ def test_order_bulk_create_error_order_line_future_date(
orders_count = Order.objects.count()
order = order_bulk_input
- order["lines"][0]["createdAt"] = timezone.now() + timedelta(
+ order["lines"][0]["createdAt"] = timezone.now() + datetime.timedelta(
minutes=MINUTES_DIFF + 1
)
@@ -2373,7 +2375,9 @@ def test_order_bulk_create_error_note_with_future_date(
orders_count = Order.objects.count()
order = order_bulk_input
- order["notes"][0]["date"] = timezone.now() + timedelta(minutes=MINUTES_DIFF + 1)
+ order["notes"][0]["date"] = timezone.now() + datetime.timedelta(
+ minutes=MINUTES_DIFF + 1
+ )
staff_api_client.user.user_permissions.add(
permission_manage_orders_import,
@@ -3080,7 +3084,7 @@ def test_order_bulk_create_error_invoice_future_date(
invoice_count = Order.objects.count()
order = order_bulk_input
- order["invoices"][0]["createdAt"] = timezone.now() + timedelta(
+ order["invoices"][0]["createdAt"] = timezone.now() + datetime.timedelta(
minutes=MINUTES_DIFF + 1
)
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index 093be12fb4..4effe744fc 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -1,10 +1,9 @@
-from datetime import datetime
+import datetime
from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
-import pytz
from django.db.models import Sum
from django.test import override_settings
@@ -310,7 +309,7 @@ def test_order_lines_create_for_just_published_product(
order.save(update_fields=["status"])
variant = variant_with_many_stocks
product_listing = variant.product.channel_listings.get(channel=order.channel)
- product_listing.published_at = datetime.now(pytz.utc)
+ product_listing.published_at = datetime.datetime.now(tz=datetime.UTC)
product_listing.save(update_fields=["published_at"])
quantity = 1
diff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
index de79b9412f..9c69407149 100644
--- a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
from decimal import Decimal
import graphene
@@ -115,16 +115,49 @@ def test_draft_order_query_with_filter_customer_fields(
(
{
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
}
},
1,
),
- ({"created": {"gte": str(date.today() - timedelta(days=3))}}, 1),
- ({"created": {"lte": str(date.today())}}, 2),
- ({"created": {"lte": str(date.today() - timedelta(days=3))}}, 1),
- ({"created": {"gte": str(date.today() + timedelta(days=1))}}, 0),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ ),
+ ({"created": {"lte": str(datetime.datetime.now(tz=datetime.UTC).date())}}, 2),
+ (
+ {
+ "created": {
+ "lte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ ),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ + datetime.timedelta(days=1)
+ )
+ }
+ },
+ 0,
+ ),
({"created": {"gte": None}}, 2),
({"created": {"lte": None}}, 2),
],
diff --git a/saleor/graphql/order/tests/queries/test_order_can_finalize.py b/saleor/graphql/order/tests/queries/test_order_can_finalize.py
index 98e4c245a0..0c6cee90bf 100644
--- a/saleor/graphql/order/tests/queries/test_order_can_finalize.py
+++ b/saleor/graphql/order/tests/queries/test_order_can_finalize.py
@@ -1,7 +1,6 @@
-from datetime import datetime, timedelta
+import datetime
import graphene
-import pytz
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
@@ -148,7 +147,8 @@ def test_can_finalize_order_product_available_for_purchase_from_tomorrow(
line = order.lines.first()
product = line.variant.product
product.channel_listings.update(
- available_for_purchase_at=datetime.now(pytz.UTC) + timedelta(days=1)
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC)
+ + datetime.timedelta(days=1)
)
order_id = graphene.Node.to_global_id("Order", order.id)
diff --git a/saleor/graphql/order/tests/queries/test_order_with_filter.py b/saleor/graphql/order/tests/queries/test_order_with_filter.py
index 2b0e6126a1..d53b4b4c9c 100644
--- a/saleor/graphql/order/tests/queries/test_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_order_with_filter.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
from decimal import Decimal
import graphene
@@ -258,16 +258,49 @@ def test_order_query_with_filter_gift_card_bought_false(
(
{
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
}
},
1,
),
- ({"created": {"gte": str(date.today() - timedelta(days=3))}}, 1),
- ({"created": {"lte": str(date.today())}}, 2),
- ({"created": {"lte": str(date.today() - timedelta(days=3))}}, 1),
- ({"created": {"gte": str(date.today() + timedelta(days=1))}}, 0),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ ),
+ ({"created": {"lte": str(datetime.datetime.now(tz=datetime.UTC).date())}}, 2),
+ (
+ {
+ "created": {
+ "lte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ ),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ + datetime.timedelta(days=1)
+ )
+ }
+ },
+ 0,
+ ),
],
)
def test_order_query_with_filter_created(
@@ -536,9 +569,9 @@ def preorders(orders, product):
)
for i in (1, 2, 3, 4)
]
- variants[1].preorder_end_date = timezone.now() + timedelta(days=1)
+ variants[1].preorder_end_date = timezone.now() + datetime.timedelta(days=1)
variants[2].preorder_end_date = timezone.now()
- variants[3].preorder_end_date = timezone.now() - timedelta(days=1)
+ variants[3].preorder_end_date = timezone.now() - datetime.timedelta(days=1)
ProductVariant.objects.bulk_create(variants)
lines = [
diff --git a/saleor/graphql/order/tests/queries/test_pagination.py b/saleor/graphql/order/tests/queries/test_pagination.py
index f84bbead5c..adf69bc674 100644
--- a/saleor/graphql/order/tests/queries/test_pagination.py
+++ b/saleor/graphql/order/tests/queries/test_pagination.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
from decimal import Decimal
import graphene
@@ -142,17 +142,57 @@ QUERY_DRAFT_ORDERS_WITH_PAGINATION = """
(
{
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
}
},
[3.0, 2.0],
3,
),
- ({"created": {"gte": str(date.today() - timedelta(days=3))}}, [3.0, 2.0], 3),
- ({"created": {"lte": str(date.today())}}, [0.0, 3.0], 4),
- ({"created": {"lte": str(date.today() - timedelta(days=3))}}, [0.0], 1),
- ({"created": {"gte": str(date.today() + timedelta(days=1))}}, [], 0),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ [3.0, 2.0],
+ 3,
+ ),
+ (
+ {"created": {"lte": str(datetime.datetime.now(tz=datetime.UTC).date())}},
+ [0.0, 3.0],
+ 4,
+ ),
+ (
+ {
+ "created": {
+ "lte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ [0.0],
+ 1,
+ ),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ + datetime.timedelta(days=1)
+ )
+ }
+ },
+ [],
+ 0,
+ ),
],
)
def test_order_query_pagination_with_filter_created(
@@ -359,17 +399,57 @@ def test_draft_order_query_pagination_with_filter_customer_fields(
(
{
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
}
},
3,
[3.0, 2.0],
),
- ({"created": {"gte": str(date.today() - timedelta(days=3))}}, 3, [3.0, 2.0]),
- ({"created": {"lte": str(date.today())}}, 4, [0.0, 3.0]),
- ({"created": {"lte": str(date.today() - timedelta(days=3))}}, 1, [0.0]),
- ({"created": {"gte": str(date.today() + timedelta(days=1))}}, 0, []),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 3,
+ [3.0, 2.0],
+ ),
+ (
+ {"created": {"lte": str(datetime.datetime.now(tz=datetime.UTC).date())}},
+ 4,
+ [0.0, 3.0],
+ ),
+ (
+ {
+ "created": {
+ "lte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ )
+ }
+ },
+ 1,
+ [0.0],
+ ),
+ (
+ {
+ "created": {
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ + datetime.timedelta(days=1)
+ )
+ }
+ },
+ 0,
+ [],
+ ),
],
)
def test_draft_order_query_pagination_with_filter_created(
diff --git a/saleor/graphql/order/tests/test_draft_order_validate.py b/saleor/graphql/order/tests/test_draft_order_validate.py
index c5c4943773..5ef79560cc 100644
--- a/saleor/graphql/order/tests/test_draft_order_validate.py
+++ b/saleor/graphql/order/tests/test_draft_order_validate.py
@@ -1,8 +1,7 @@
-from datetime import datetime, timedelta
+import datetime
from unittest.mock import patch
import pytest
-import pytz
from django.core.exceptions import ValidationError
from ....order.error_codes import OrderErrorCode
@@ -124,7 +123,8 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(
line = order.lines.first()
variant = line.variant
variant.product.channel_listings.update(
- available_for_purchase_at=datetime.now(pytz.UTC) + timedelta(days=2)
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC)
+ + datetime.timedelta(days=2)
)
line.refresh_from_db()
diff --git a/saleor/graphql/order/tests/test_homepage.py b/saleor/graphql/order/tests/test_homepage.py
index 48972ea4c2..42f3d5b5d0 100644
--- a/saleor/graphql/order/tests/test_homepage.py
+++ b/saleor/graphql/order/tests/test_homepage.py
@@ -1,4 +1,4 @@
-from datetime import date, timedelta
+import datetime
import pytest
from prices import Money
@@ -351,8 +351,11 @@ def test_orders_total_count_without_channel(
permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
}
}
@@ -375,8 +378,11 @@ def test_orders_total_count_channel_USD(
permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
},
"channel": channel_USD.slug,
}
@@ -400,8 +406,11 @@ def test_orders_total_count_channel_PLN(
permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
},
"channel": channel_PLN.slug,
}
@@ -425,8 +434,11 @@ def test_orders_total_count_as_staff(
permission_group_manage_orders.user_set.add(staff_api_client.user)
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
},
"channel": channel_USD.slug,
}
@@ -449,8 +461,11 @@ def test_orders_total_count_as_app(
# given
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
},
"channel": channel_USD.slug,
}
@@ -474,8 +489,11 @@ def test_orders_total_count_as_customer(
# given
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
},
"channel": channel_USD.slug,
}
@@ -496,8 +514,11 @@ def test_orders_total_count_as_anonymous(
# given
variables = {
"created": {
- "gte": str(date.today() - timedelta(days=3)),
- "lte": str(date.today()),
+ "gte": str(
+ datetime.datetime.now(tz=datetime.UTC).date()
+ - datetime.timedelta(days=3)
+ ),
+ "lte": str(datetime.datetime.now(tz=datetime.UTC).date()),
},
"channel": channel_USD.slug,
}
diff --git a/saleor/graphql/page/mutations/page_create.py b/saleor/graphql/page/mutations/page_create.py
index e71bf5039a..b5646ef12d 100644
--- a/saleor/graphql/page/mutations/page_create.py
+++ b/saleor/graphql/page/mutations/page_create.py
@@ -1,7 +1,6 @@
-from datetime import datetime
+import datetime
import graphene
-import pytz
from django.core.exceptions import ValidationError
from ....core.tracing import traced_atomic_transaction
@@ -101,7 +100,7 @@ class PageCreate(ModelMutation):
"publication_date"
)
if is_published and not publication_date:
- cleaned_input["published_at"] = datetime.now(pytz.UTC)
+ cleaned_input["published_at"] = datetime.datetime.now(tz=datetime.UTC)
elif "publication_date" in cleaned_input or "published_at" in cleaned_input:
cleaned_input["published_at"] = publication_date
diff --git a/saleor/graphql/page/tests/deprecated/test_page_create.py b/saleor/graphql/page/tests/deprecated/test_page_create.py
index c2998152bb..d7aa39994a 100644
--- a/saleor/graphql/page/tests/deprecated/test_page_create.py
+++ b/saleor/graphql/page/tests/deprecated/test_page_create.py
@@ -1,7 +1,6 @@
-from datetime import datetime, timedelta
+import datetime
import graphene
-import pytz
from django.utils.text import slugify
from .....page.error_codes import PageErrorCode
@@ -58,7 +57,9 @@ def test_page_create_mutation_with_publication_date(
page_content = dummy_editorjs("test content", True)
page_title = "test title"
page_is_published = True
- publication_date = datetime.now(pytz.utc) + timedelta(days=5)
+ publication_date = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ days=5
+ )
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
# Default attributes defined in product_type fixture
@@ -116,8 +117,10 @@ def test_page_create_mutation_publication_date_and_published_at_provided(
page_content = dummy_editorjs("test content", True)
page_title = "test title"
page_is_published = True
- publication_date = datetime.now(pytz.utc) + timedelta(days=5)
- published_at = datetime.now(pytz.utc) + timedelta(days=5)
+ publication_date = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ days=5
+ )
+ published_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=5)
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
# test creating root page
diff --git a/saleor/graphql/page/tests/deprecated/test_page_update.py b/saleor/graphql/page/tests/deprecated/test_page_update.py
index 39cbb00aa4..7e359577f0 100644
--- a/saleor/graphql/page/tests/deprecated/test_page_update.py
+++ b/saleor/graphql/page/tests/deprecated/test_page_update.py
@@ -1,7 +1,6 @@
-from datetime import datetime, timedelta
+import datetime
import graphene
-import pytz
from .....page.error_codes import PageErrorCode
from .....page.models import Page
@@ -54,7 +53,9 @@ def test_update_page_publication_date(
"page_type": page_type,
}
page = Page.objects.create(**data)
- publication_date = datetime.now(pytz.utc) + timedelta(days=5)
+ publication_date = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ days=5
+ )
page_id = graphene.Node.to_global_id("Page", page.id)
variables = {
"id": page_id,
@@ -85,8 +86,10 @@ def test_page_update_mutation_publication_date_and_published_at_provided(
"page_type": page_type,
}
page = Page.objects.create(**data)
- published_at = datetime.now(pytz.utc) + timedelta(days=5)
- publication_date = datetime.now(pytz.utc) + timedelta(days=5)
+ published_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=5)
+ publication_date = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ days=5
+ )
page_id = graphene.Node.to_global_id("Page", page.id)
# test creating root page
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 06c898aac2..d0364a1046 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -1,10 +1,9 @@
-from datetime import datetime, timedelta
+import datetime
from functools import partial
from unittest import mock
from unittest.mock import ANY
import graphene
-import pytz
from django.conf import settings
from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
@@ -104,7 +103,10 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages, page_ty
assert data["page"]["content"] == page_content
assert data["page"]["slug"] == page_slug
assert data["page"]["isPublished"] == page_is_published
- assert data["page"]["publishedAt"] == datetime.now(pytz.utc).isoformat()
+ assert (
+ data["page"]["publishedAt"]
+ == datetime.datetime.now(tz=datetime.UTC).isoformat()
+ )
assert data["page"]["pageType"]["id"] == page_type_id
values = (
data["page"]["attributes"][0]["values"][0]["slug"],
@@ -122,7 +124,9 @@ def test_page_create_mutation_with_published_at_date(
page_content = dummy_editorjs("test content", True)
page_title = "test title"
page_is_published = True
- published_at = datetime.now(pytz.utc).replace(microsecond=0) + timedelta(days=5)
+ published_at = datetime.datetime.now(tz=datetime.UTC).replace(
+ microsecond=0
+ ) + datetime.timedelta(days=5)
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
# Default attributes defined in product_type fixture
@@ -692,7 +696,7 @@ def test_create_page_with_page_reference_attribute(
assert page_type_page_reference_attribute.values.count() == values_count + 1
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_page_with_date_attribute(
staff_api_client,
permission_manage_pages,
@@ -706,7 +710,7 @@ def test_create_page_with_date_attribute(
page_title = "test title"
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
date_attribute_id = graphene.Node.to_global_id("Attribute", date_attribute.id)
- date_time_value = datetime.now(tz=pytz.utc)
+ date_time_value = datetime.datetime.now(tz=datetime.UTC)
date_value = date_time_value.date()
variables = {
@@ -752,7 +756,7 @@ def test_create_page_with_date_attribute(
assert expected_attributes_data in data["page"]["attributes"]
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_page_with_date_time_attribute(
staff_api_client,
permission_manage_pages,
@@ -768,7 +772,7 @@ def test_create_page_with_date_time_attribute(
date_time_attribute_id = graphene.Node.to_global_id(
"Attribute", date_time_attribute.id
)
- date_time_value = datetime.now(tz=pytz.utc)
+ date_time_value = datetime.datetime.now(tz=datetime.UTC)
variables = {
"input": {
"title": page_title,
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 250e4fb05c..a26b6c8b62 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -1,11 +1,10 @@
-from datetime import datetime, timedelta
+import datetime
from functools import partial
from unittest import mock
from unittest.mock import ANY
import graphene
import pytest
-import pytz
from django.conf import settings
from django.utils import timezone
from django.utils.functional import SimpleLazyObject
@@ -952,7 +951,10 @@ def test_public_page_sets_publication_date(
assert not data["errors"]
assert data["page"]["isPublished"] is True
- assert data["page"]["publishedAt"] == datetime.now(pytz.utc).isoformat()
+ assert (
+ data["page"]["publishedAt"]
+ == datetime.datetime.now(tz=datetime.UTC).isoformat()
+ )
def test_update_page_publication_date(
@@ -964,7 +966,9 @@ def test_update_page_publication_date(
"page_type": page_type,
}
page = Page.objects.create(**data)
- published_at = datetime.now(pytz.utc).replace(microsecond=0) + timedelta(days=5)
+ published_at = datetime.datetime.now(tz=datetime.UTC).replace(
+ microsecond=0
+ ) + datetime.timedelta(days=5)
page_id = graphene.Node.to_global_id("Page", page.id)
variables = {
"id": page_id,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 49d817c897..b434667d33 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -1,11 +1,10 @@
-from datetime import datetime
+import datetime
from decimal import Decimal
from unittest.mock import patch
from uuid import uuid4
import graphene
import pytest
-import pytz
from django.utils import timezone
from freezegun import freeze_time
@@ -1294,7 +1293,7 @@ def test_transaction_event_updates_checkout_payment_statuses(
@pytest.mark.parametrize(
"current_last_transaction_modified_at",
- [None, datetime(2000, 5, 31, 12, 0, 0, tzinfo=pytz.UTC)],
+ [None, datetime.datetime(2000, 5, 31, 12, 0, 0, tzinfo=datetime.UTC)],
)
@freeze_time("2018-05-31 12:00:01")
def test_transaction_event_updates_checkout_last_transaction_modified_at(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 025a0141c6..eb812f8a43 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -1,8 +1,8 @@
+import datetime
from decimal import Decimal
from unittest import mock
import pytest
-import pytz
from django.conf import settings
from django.test import override_settings
from django.utils import timezone
@@ -2432,7 +2432,7 @@ def test_customer_ip_address_ipv6(
@freeze_time("2023-03-18 12:00:00")
@pytest.mark.parametrize(
"previous_last_transaction_modified_at",
- [None, timezone.datetime(2020, 1, 1, tzinfo=pytz.UTC)],
+ [None, datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)],
)
@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index 5bcd0b87e2..f28fc0ae33 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -4,7 +4,6 @@ from unittest import mock
import graphene
import pytest
-import pytz
from django.utils import timezone
from freezegun import freeze_time
@@ -1958,7 +1957,7 @@ def test_transaction_process_for_disabled_app(
@freeze_time("2023-03-18 12:00:00")
@pytest.mark.parametrize(
"previous_last_transaction_modified_at",
- [None, datetime.datetime(2020, 1, 1, tzinfo=pytz.UTC)],
+ [None, datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)],
)
@mock.patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_process_session")
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index 51eaac6f19..2386310a4f 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -1,8 +1,7 @@
+import datetime
from collections import defaultdict
-from datetime import datetime
import graphene
-import pytz
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db.models import F
@@ -351,14 +350,16 @@ class ProductBulkCreate(BaseMutation):
if is_available_for_purchase is False:
channel_data["available_for_purchase_at"] = None
elif is_available_for_purchase is True and not available_for_purchase_at:
- channel_data["available_for_purchase_at"] = datetime.now(pytz.UTC)
+ channel_data["available_for_purchase_at"] = datetime.datetime.now(
+ tz=datetime.UTC
+ )
else:
channel_data["available_for_purchase_at"] = available_for_purchase_at
@staticmethod
def set_published_at(channel_data):
if channel_data.get("is_published") and not channel_data.get("published_at"):
- channel_data["published_at"] = datetime.now(pytz.UTC)
+ channel_data["published_at"] = datetime.datetime.now(tz=datetime.UTC)
@classmethod
def clean_product_channel_listings(
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index ce3e6f196c..88199c8139 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -5,7 +5,6 @@ from typing import Optional, TypedDict
import django_filters
import graphene
-import pytz
from django.db.models import Exists, FloatField, OuterRef, Q, Subquery, Sum
from django.db.models.expressions import ExpressionWrapper
from django.db.models.fields import IntegerField
@@ -186,13 +185,13 @@ def _clean_product_attributes_date_time_range_filter_input(
if lte := val_range.get("lte"):
if not isinstance(lte, datetime.datetime):
lte = datetime.datetime.combine(
- lte, datetime.datetime.max.time(), tzinfo=pytz.UTC
+ lte, datetime.datetime.max.time(), tzinfo=datetime.UTC
)
filters["date_time__lte"] = lte
if gte := val_range.get("gte"):
if not isinstance(gte, datetime.datetime):
gte = datetime.datetime.combine(
- gte, datetime.datetime.min.time(), tzinfo=pytz.UTC
+ gte, datetime.datetime.min.time(), tzinfo=datetime.UTC
)
filters["date_time__gte"] = gte
return matching_attributes.filter(**filters)
@@ -540,7 +539,7 @@ def _filter_products_is_published(qs, _, value, channel_slug):
def _filter_products_is_available(qs, _, value, channel_slug):
channel = Channel.objects.using(qs.db).filter(slug=channel_slug).values("pk")
- now = datetime.datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
if value:
product_channel_listings = (
ProductChannelListing.objects.using(qs.db)
@@ -883,7 +882,7 @@ def where_filter_products_is_available(qs, _, value, channel_slug):
if value is None:
return qs.none()
channel = Channel.objects.using(qs.db).filter(slug=channel_slug).values("pk")
- now = datetime.datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
if value:
product_channel_listings = (
ProductChannelListing.objects.using(qs.db)
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index b50e0e0014..ba0031c486 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -1,9 +1,8 @@
+import datetime
from collections import defaultdict
-from datetime import datetime
from typing import TYPE_CHECKING
import graphene
-import pytz
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
@@ -263,7 +262,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
if is_available_for_purchase is False:
return None
elif is_available_for_purchase is True and not available_for_purchase_date:
- return datetime.now(pytz.UTC)
+ return datetime.datetime.now(tz=datetime.UTC)
return available_for_purchase_date
@classmethod
diff --git a/saleor/graphql/product/mutations/collection/collection_create.py b/saleor/graphql/product/mutations/collection/collection_create.py
index 19fb23bc38..53bd43f6d3 100644
--- a/saleor/graphql/product/mutations/collection/collection_create.py
+++ b/saleor/graphql/product/mutations/collection/collection_create.py
@@ -1,7 +1,6 @@
import datetime
import graphene
-import pytz
from django.core.exceptions import ValidationError
from .....core.utils.date_time import convert_to_utc_date_time
@@ -107,7 +106,7 @@ class CollectionCreate(ModelMutation):
is_published = cleaned_input.get("is_published")
publication_date = cleaned_input.get("publication_date")
if is_published and not publication_date:
- cleaned_input["published_at"] = datetime.datetime.now(pytz.UTC)
+ cleaned_input["published_at"] = datetime.datetime.now(tz=datetime.UTC)
elif publication_date:
cleaned_input["published_at"] = convert_to_utc_date_time(publication_date)
clean_seo_fields(cleaned_input)
diff --git a/saleor/graphql/product/tests/deprecated/test_collection_channel_listing_update.py b/saleor/graphql/product/tests/deprecated/test_collection_channel_listing_update.py
index cd6e806c95..9000be69ae 100644
--- a/saleor/graphql/product/tests/deprecated/test_collection_channel_listing_update.py
+++ b/saleor/graphql/product/tests/deprecated/test_collection_channel_listing_update.py
@@ -1,7 +1,6 @@
import datetime
import graphene
-import pytz
from .....product.error_codes import CollectionErrorCode
from ....tests.utils import get_graphql_content
@@ -41,7 +40,7 @@ def test_collection_channel_listing_update_as_staff_user(
channel_PLN,
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -97,7 +96,7 @@ def test_collection_channel_listing_update_as_app(
channel_PLN,
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -152,7 +151,7 @@ def test_collection_channel_listing_update_add_channel(
channel_PLN,
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -203,7 +202,7 @@ def test_collection_channel_listing_update_update_publication_date(
staff_api_client, collection, permission_manage_products, channel_USD
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
@@ -240,8 +239,8 @@ def test_collection_channel_listing_update_update_publication_date_and_published
):
"""Test that filtering by publication time and date are mutually exclusive."""
# given
- publication_date = datetime.date.today()
- published_at = datetime.datetime.now(pytz.utc)
+ published_at = datetime.datetime.now(tz=datetime.UTC)
+ publication_date = published_at.date()
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
diff --git a/saleor/graphql/product/tests/deprecated/test_collection_sorting.py b/saleor/graphql/product/tests/deprecated/test_collection_sorting.py
index fa34984ba8..74a865bdf6 100644
--- a/saleor/graphql/product/tests/deprecated/test_collection_sorting.py
+++ b/saleor/graphql/product/tests/deprecated/test_collection_sorting.py
@@ -1,7 +1,6 @@
import datetime
import pytest
-import pytz
from .....product.models import Collection, CollectionChannelListing
from ....tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -34,13 +33,13 @@ def collections_for_sorting_with_channels(channel_USD, channel_PLN):
),
CollectionChannelListing(
collection=collections[2],
- published_at=datetime.datetime(2004, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2004, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_USD,
),
CollectionChannelListing(
collection=collections[3],
- published_at=datetime.datetime(2003, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2003, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_USD,
),
@@ -59,13 +58,13 @@ def collections_for_sorting_with_channels(channel_USD, channel_PLN):
),
CollectionChannelListing(
collection=collections[2],
- published_at=datetime.datetime(2002, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2002, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_PLN,
),
CollectionChannelListing(
collection=collections[4],
- published_at=datetime.datetime(2001, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2001, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_PLN,
),
diff --git a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py
index fda4883229..10c254fff7 100644
--- a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py
@@ -2,7 +2,6 @@ import datetime
from unittest.mock import patch
import graphene
-import pytz
from freezegun import freeze_time
from .....product.error_codes import ProductErrorCode
@@ -69,7 +68,7 @@ def test_product_channel_listing_update_as_staff_user(
channel_PLN,
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
available_for_purchase_date = datetime.date(2007, 1, 1)
@@ -152,7 +151,7 @@ def test_product_channel_listing_update_trigger_webhook_product_updated(
channel_PLN,
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
available_for_purchase_date = datetime.date(2007, 1, 1)
@@ -189,7 +188,7 @@ def test_product_channel_listing_update_add_channel(
staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
available_for_purchase_date = datetime.date(2007, 1, 1)
@@ -244,7 +243,7 @@ def test_product_channel_listing_update_update_publication_data(
staff_api_client, product, permission_manage_products, channel_USD
):
# given
- publication_date = datetime.date.today()
+ publication_date = datetime.datetime.now(tz=datetime.UTC).date()
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
@@ -293,8 +292,8 @@ def test_product_channel_listing_update_update_publication_date_and_published_at
):
"""Test that filtering by publication time and date are mutually exclusive."""
# given
- publication_date = datetime.date.today()
- published_at = datetime.datetime.now(pytz.utc)
+ published_at = datetime.datetime.now(tz=datetime.UTC)
+ publication_date = published_at.date()
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
@@ -379,7 +378,9 @@ def test_product_channel_listing_update_update_is_available_for_purchase_future_
# given
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- available_for_purchase_date = datetime.date.today() + datetime.timedelta(days=1)
+ available_for_purchase_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() + datetime.timedelta(days=1)
variables = {
"id": product_id,
"input": {
@@ -424,7 +425,9 @@ def test_product_channel_listing_update_update_is_available_for_purchase_false_a
# given
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- available_for_purchase_date = datetime.date.today() + datetime.timedelta(days=1)
+ available_for_purchase_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() + datetime.timedelta(days=1)
variables = {
"id": product_id,
"input": {
@@ -461,8 +464,8 @@ def test_product_channel_listing_update_available_for_purchase_both_date_value_g
):
"""Test that filtering by availability time and date are mutually exclusive."""
# given
- available_for_purchase_date = datetime.date.today()
- available_for_purchase_at = datetime.datetime.now(pytz.utc)
+ available_for_purchase_date = datetime.datetime.now(tz=datetime.UTC).date()
+ available_for_purchase_at = datetime.datetime.now(tz=datetime.UTC)
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
diff --git a/saleor/graphql/product/tests/deprecated/test_product_sorting.py b/saleor/graphql/product/tests/deprecated/test_product_sorting.py
index a07e0954e8..2622497bdb 100644
--- a/saleor/graphql/product/tests/deprecated/test_product_sorting.py
+++ b/saleor/graphql/product/tests/deprecated/test_product_sorting.py
@@ -1,8 +1,7 @@
-from datetime import datetime, timedelta
+import datetime
import graphene
import pytest
-import pytz
from django.utils import timezone
from freezegun import freeze_time
@@ -37,7 +36,7 @@ def test_sort_products_by_publication_date(
product_channel_listings = []
for iter_value, product in enumerate(product_list):
product_channel_listing = product.channel_listings.get(channel=channel_USD)
- product_channel_listing.published_at = timezone.now() - timedelta(
+ product_channel_listing.published_at = timezone.now() - datetime.timedelta(
days=iter_value
)
product_channel_listings.append(product_channel_listing)
@@ -133,7 +132,7 @@ def test_pagination_for_sorting_products_by_publication_date(
listings_in_bulk = {listing.product_id: listing for listing in channel_listings}
for product in product_list:
listing = listings_in_bulk.get(product.id)
- listing.published_at = datetime.now(pytz.UTC)
+ listing.published_at = datetime.datetime.now(tz=datetime.UTC)
ProductChannelListing.objects.bulk_update(channel_listings, ["published_at"])
@@ -203,14 +202,14 @@ def test_pagination_for_sorting_collections_by_publication_date(
Collection(name="Coll3", slug="collection-3"),
]
)
- now = datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
CollectionChannelListing.objects.bulk_create(
[
CollectionChannelListing(
channel=channel_USD,
collection=collection,
is_published=True,
- published_at=now - timedelta(days=num),
+ published_at=now - datetime.timedelta(days=num),
)
for num, collection in enumerate(collections)
]
diff --git a/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py
index 00ec33fa82..99cebdf899 100644
--- a/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+import datetime
from unittest.mock import ANY, patch
from uuid import uuid4
@@ -653,7 +653,7 @@ def test_product_variant_bulk_create_preorder_channel_listings_input(
global_threshold = 10
end_date = (
- (datetime.now() + timedelta(days=3))
+ (datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=3))
.astimezone()
.replace(microsecond=0)
.isoformat()
diff --git a/saleor/graphql/product/tests/mutations/test_collection_channel_listing_update.py b/saleor/graphql/product/tests/mutations/test_collection_channel_listing_update.py
index 50b98025c2..4195e9a8dd 100644
--- a/saleor/graphql/product/tests/mutations/test_collection_channel_listing_update.py
+++ b/saleor/graphql/product/tests/mutations/test_collection_channel_listing_update.py
@@ -1,7 +1,6 @@
import datetime
import graphene
-import pytz
from freezegun import freeze_time
from .....product.error_codes import CollectionErrorCode
@@ -177,7 +176,7 @@ def test_collection_channel_listing_update_as_staff_user(
channel_PLN,
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -233,7 +232,7 @@ def test_collection_channel_listing_update_as_app(
channel_PLN,
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -328,7 +327,7 @@ def test_collection_channel_listing_update_add_channel(
channel_PLN,
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
variables = {
@@ -413,7 +412,7 @@ def test_collection_channel_listing_update_update_publication_date(
staff_api_client, collection, permission_manage_products, channel_USD
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
@@ -517,7 +516,7 @@ def test_collection_channel_listing_update_add_channel_without_publication_date(
assert collection_data["channelListings"][1]["isPublished"] is True
assert (
collection_data["channelListings"][1]["publishedAt"]
- == datetime.datetime.now(pytz.utc).isoformat()
+ == datetime.datetime.now(tz=datetime.UTC).isoformat()
)
assert collection_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
@@ -551,6 +550,6 @@ def test_collection_channel_listing_update_publish_without_publication_date(
assert collection_data["channelListings"][0]["isPublished"] is True
assert (
collection_data["channelListings"][0]["publishedAt"]
- == datetime.datetime.now(pytz.utc).isoformat()
+ == datetime.datetime.now(tz=datetime.UTC).isoformat()
)
assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
index ecfec4db16..51261d9832 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -6,7 +6,6 @@ from uuid import uuid4
import graphene
import pytest
-import pytz
from .....attribute.tests.model_helpers import (
get_product_attribute_values,
@@ -1098,7 +1097,7 @@ def test_product_bulk_create_with_channel_listings(
product_tax_rate = "STANDARD"
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- publication_at = datetime.datetime.now(pytz.utc)
+ publication_at = datetime.datetime.now(tz=datetime.UTC)
channel_listings = [
{
@@ -1733,7 +1732,7 @@ def test_product_bulk_create_with_variants_and_channel_listings(
variant_2_name = "new-variant-2-name"
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- publication_at = datetime.datetime.now(pytz.utc)
+ publication_at = datetime.datetime.now(tz=datetime.UTC)
product_channel_listings = [
{
@@ -1857,7 +1856,7 @@ def test_product_bulk_create_with_variants_and_channel_listings_with_wrong_price
variant_1_name = "new-variant-1-name"
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- publication_at = datetime.datetime.now(pytz.utc)
+ publication_at = datetime.datetime.now(tz=datetime.UTC)
product_channel_listings = [
{
diff --git a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
index d2c1e91320..228c3b7e22 100644
--- a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
@@ -2,7 +2,6 @@ import datetime
from unittest.mock import patch
import graphene
-import pytz
from django.utils import timezone
from freezegun import freeze_time
@@ -203,10 +202,10 @@ def test_product_channel_listing_update_as_staff_user(
staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
- available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=pytz.utc)
+ available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=datetime.UTC)
variables = {
"id": product_id,
"input": {
@@ -281,10 +280,10 @@ def test_product_channel_listing_update_trigger_webhook_product_updated(
channel_USD,
):
# given
- publication_date = datetime.datetime.now(pytz.utc)
+ publication_date = datetime.datetime.now(tz=datetime.UTC)
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=pytz.utc)
+ available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=datetime.UTC)
variables = {
"id": product_id,
"input": {
@@ -321,10 +320,10 @@ def test_product_channel_listing_update_as_app(
app_api_client, product, permission_manage_products, channel_USD, channel_PLN
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
- available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=pytz.utc)
+ available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=datetime.UTC)
variables = {
"id": product_id,
"input": {
@@ -419,10 +418,10 @@ def test_product_channel_listing_update_add_channel(
staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
- available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=pytz.utc)
+ available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=datetime.UTC)
variables = {
"id": product_id,
"input": {
@@ -499,7 +498,7 @@ def test_product_channel_listing_update_add_channel_without_publication_date(
assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
assert product_data["channelListings"][1]["isPublished"] is True
assert (
- datetime.datetime.now(pytz.UTC).isoformat()
+ datetime.datetime.now(tz=datetime.UTC).isoformat()
== product_data["channelListings"][1]["publishedAt"]
)
assert product_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
@@ -533,7 +532,7 @@ def test_product_channel_listing_update_unpublished(
assert product_data["slug"] == product.slug
assert product_data["channelListings"][0]["isPublished"] is False
assert (
- datetime.datetime.now(pytz.UTC).isoformat()
+ datetime.datetime.now(tz=datetime.UTC).isoformat()
== product_data["channelListings"][0]["publishedAt"]
)
assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
@@ -573,7 +572,7 @@ def test_product_channel_listing_update_publish_without_publication_date(
assert product_data["slug"] == product.slug
assert product_data["channelListings"][0]["isPublished"] is True
assert (
- datetime.datetime.now(pytz.UTC).isoformat()
+ datetime.datetime.now(tz=datetime.UTC).isoformat()
== product_data["channelListings"][0]["publishedAt"]
)
assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
@@ -656,7 +655,7 @@ def test_product_channel_listing_update_update_publication_data(
staff_api_client, product, permission_manage_products, channel_USD
):
# given
- publication_date = datetime.datetime.now(pytz.utc).replace(microsecond=0)
+ publication_date = datetime.datetime.now(tz=datetime.UTC).replace(microsecond=0)
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
@@ -770,7 +769,7 @@ def test_product_channel_listing_update_update_is_available_for_purchase_without
assert product_data["channelListings"][0]["visibleInListings"] is True
assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
assert (
- datetime.datetime.now(pytz.UTC).isoformat()
+ datetime.datetime.now(tz=datetime.UTC).isoformat()
== product_data["channelListings"][0]["availableForPurchaseAt"]
)
@@ -782,7 +781,7 @@ def test_product_channel_listing_update_update_is_available_for_purchase_past_da
# given
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=pytz.utc)
+ available_for_purchase_date = datetime.datetime(2007, 1, 1, tzinfo=datetime.UTC)
variables = {
"id": product_id,
"input": {
@@ -827,7 +826,7 @@ def test_product_channel_listing_update_update_is_available_for_purchase_future_
# given
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- available_for_purchase_date = datetime.datetime.now(pytz.utc).replace(
+ available_for_purchase_date = datetime.datetime.now(tz=datetime.UTC).replace(
microsecond=0
) + datetime.timedelta(days=1)
variables = {
@@ -874,9 +873,9 @@ def test_product_channel_listing_update_update_is_available_for_purchase_false_a
# given
product_id = graphene.Node.to_global_id("Product", product.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
- available_for_purchase_date = datetime.datetime.now(pytz.utc) + datetime.timedelta(
- days=1
- )
+ available_for_purchase_date = datetime.datetime.now(
+ datetime.UTC
+ ) + datetime.timedelta(days=1)
variables = {
"id": product_id,
"input": {
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index 52d130cbb7..107e87373f 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -1,10 +1,9 @@
+import datetime
import json
-from datetime import datetime
from unittest.mock import ANY, patch
import graphene
import pytest
-import pytz
from django.conf import settings
from django.utils.text import slugify
from freezegun import freeze_time
@@ -746,7 +745,7 @@ def test_create_product_no_value_for_plain_text_attribute(
assert expected_attributes_data in data["product"]["attributes"]
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_product_with_date_time_attribute(
staff_api_client,
product_type,
@@ -764,7 +763,7 @@ def test_create_product_with_date_time_attribute(
date_time_attribute_id = graphene.Node.to_global_id(
"Attribute", date_time_attribute.id
)
- value = datetime.now(tz=pytz.utc)
+ value = datetime.datetime.now(tz=datetime.UTC)
# test creating root product
variables = {
@@ -810,7 +809,7 @@ def test_create_product_with_date_time_attribute(
assert expected_attributes_data in data["product"]["attributes"]
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_product_with_date_attribute(
staff_api_client,
product_type,
@@ -826,7 +825,7 @@ def test_create_product_with_date_attribute(
# Add second attribute
product_type.product_attributes.add(date_attribute)
date_attribute_id = graphene.Node.to_global_id("Attribute", date_attribute.id)
- value = datetime.now(tz=pytz.utc).date()
+ value = datetime.datetime.now(tz=datetime.UTC).date()
# test creating root product
variables = {
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index eeb4135406..5df8694ba0 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -1,10 +1,9 @@
+import datetime
import json
-from datetime import datetime, timedelta
from unittest.mock import ANY, patch
from uuid import uuid4
import graphene
-import pytz
from django.conf import settings
from freezegun import freeze_time
@@ -494,7 +493,7 @@ def test_product_variant_bulk_create_with_plain_text_attribute(
assert product_variant_count + 1 == ProductVariant.objects.count()
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_product_variant_bulk_create_with_date_attribute(
staff_api_client, product, date_attribute, permission_manage_products
):
@@ -504,7 +503,7 @@ def test_product_variant_bulk_create_with_date_attribute(
product_id = graphene.Node.to_global_id("Product", product.pk)
attribute_id = graphene.Node.to_global_id("Attribute", date_attribute.pk)
- date_time_value = datetime.now(tz=pytz.utc)
+ date_time_value = datetime.datetime.now(tz=datetime.UTC)
date_value = date_time_value.date()
sku = str(uuid4())[:12]
@@ -576,7 +575,7 @@ def test_product_variant_bulk_create_with_file_attribute(
assert product_variant_count + 1 == ProductVariant.objects.count()
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_product_variant_bulk_create_with_datetime_attribute(
staff_api_client,
product,
@@ -590,7 +589,7 @@ def test_product_variant_bulk_create_with_datetime_attribute(
product_id = graphene.Node.to_global_id("Product", product.pk)
attribute_id = graphene.Node.to_global_id("Attribute", date_time_attribute.pk)
- date_time_value = datetime.now(tz=pytz.utc)
+ date_time_value = datetime.datetime.now(tz=datetime.UTC)
sku = str(uuid4())[:12]
variants = [
@@ -1414,7 +1413,7 @@ def test_product_variant_bulk_create_preorder_channel_listings_input(
global_threshold = 10
end_date = (
- (datetime.now() + timedelta(days=3))
+ (datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=3))
.astimezone()
.replace(microsecond=0)
.isoformat()
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index d49da9b391..a1008d0771 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -1,10 +1,9 @@
+import datetime
import json
-from datetime import datetime, timedelta
from unittest.mock import ANY, patch
from uuid import uuid4
import graphene
-import pytz
from django.conf import settings
from django.utils.text import slugify
from freezegun import freeze_time
@@ -283,7 +282,7 @@ def test_create_variant_preorder(
variant_value = "test-value"
global_threshold = 10
end_date = (
- (datetime.now() + timedelta(days=3))
+ (datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=3))
.astimezone()
.replace(microsecond=0)
.isoformat()
@@ -1591,7 +1590,7 @@ def test_create_variant_with_plain_text_attribute(
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_variant_with_date_attribute(
created_webhook_mock,
permission_manage_products,
@@ -1609,7 +1608,7 @@ def test_create_variant_with_date_attribute(
sku = "1"
weight = 10.22
date_attribute_id = graphene.Node.to_global_id("Attribute", date_attribute.id)
- date_time_value = datetime.now(tz=pytz.utc)
+ date_time_value = datetime.datetime.now(tz=datetime.UTC)
date_value = date_time_value.date()
variables = {
@@ -1655,7 +1654,7 @@ def test_create_variant_with_date_attribute(
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
-@freeze_time(datetime(2020, 5, 5, 5, 5, 5, tzinfo=pytz.utc))
+@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_variant_with_date_time_attribute(
created_webhook_mock,
permission_manage_products,
@@ -1675,7 +1674,7 @@ def test_create_variant_with_date_time_attribute(
date_time_attribute_id = graphene.Node.to_global_id(
"Attribute", date_time_attribute.id
)
- date_time_value = datetime.now(tz=pytz.utc)
+ date_time_value = datetime.datetime.now(tz=datetime.UTC)
variables = {
"input": {
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index 54ced9559d..d5d6e7eaf3 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -1,11 +1,10 @@
+import datetime
import json
-from datetime import datetime, timedelta
from unittest.mock import ANY, patch
from uuid import uuid4
import graphene
import pytest
-import pytz
from django.conf import settings
from django.utils.text import slugify
@@ -1358,7 +1357,7 @@ def test_update_variant_with_date_attribute(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
sku = "123"
date_attribute_id = graphene.Node.to_global_id("Attribute", date_attribute.id)
- date_time_value = datetime(2025, 5, 5, 5, 5, 5, tzinfo=pytz.utc)
+ date_time_value = datetime.datetime(2025, 5, 5, 5, 5, 5, tzinfo=datetime.UTC)
date_value = date_time_value.date()
date_values_count = date_attribute.values.count()
@@ -1421,7 +1420,7 @@ def test_update_variant_with_date_time_attribute(
date_time_attribute_id = graphene.Node.to_global_id(
"Attribute", date_time_attribute.id
)
- date_time_value = datetime(2025, 5, 5, 5, 5, 5, tzinfo=pytz.utc)
+ date_time_value = datetime.datetime(2025, 5, 5, 5, 5, 5, tzinfo=datetime.UTC)
date_time_values_count = date_time_attribute.values.count()
variables = {
@@ -2275,7 +2274,7 @@ def test_update_product_variant_change_preorder_data(
new_global_threshold = variant.preorder_global_threshold + 5
assert variant.preorder_end_date is None
new_preorder_end_date = (
- (datetime.now() + timedelta(days=3))
+ (datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=3))
.astimezone()
.replace(microsecond=0)
.isoformat()
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.py
index 96d24b83b9..cf57acd382 100644
--- a/saleor/graphql/product/tests/queries/test_product_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_query.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import MagicMock
import graphene
@@ -1124,7 +1124,7 @@ def test_product_query_is_available_for_purchase_true(
user_api_client, product, channel_USD
):
# given
- available_for_purchase = timezone.now() - timedelta(days=1)
+ available_for_purchase = timezone.now() - datetime.timedelta(days=1)
product.channel_listings.update(available_for_purchase_at=available_for_purchase)
variables = {
@@ -1150,7 +1150,7 @@ def test_product_query_is_available_for_purchase_false(
user_api_client, product, channel_USD
):
# given
- available_for_purchase = timezone.now() + timedelta(days=1)
+ available_for_purchase = timezone.now() + datetime.timedelta(days=1)
product.channel_listings.update(available_for_purchase_at=available_for_purchase)
variables = {
diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.py
index 691942d2bb..2241b67887 100644
--- a/saleor/graphql/product/tests/queries/test_products_query.py
+++ b/saleor/graphql/product/tests/queries/test_products_query.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+import datetime
from decimal import Decimal
import graphene
@@ -562,12 +562,12 @@ SORT_PRODUCTS_QUERY = """
def test_sort_products(user_api_client, product, channel_USD):
- product.updated_at = datetime.utcnow()
+ product.updated_at = datetime.datetime.now(tz=datetime.UTC)
product.save()
product.pk = None
product.slug = "second-product"
- product.updated_at = datetime.utcnow()
+ product.updated_at = datetime.datetime.now(tz=datetime.UTC)
product.save()
ProductChannelListing.objects.create(
product=product,
@@ -586,7 +586,7 @@ def test_sort_products(user_api_client, product, channel_USD):
)
product.pk = None
product.slug = "third-product"
- product.updated_at = datetime.utcnow()
+ product.updated_at = datetime.datetime.now(tz=datetime.UTC)
product.save()
ProductChannelListing.objects.create(
product=product,
@@ -672,13 +672,13 @@ def test_sort_products(user_api_client, product, channel_USD):
def test_sort_products_by_price_as_staff(
staff_api_client, product, channel_USD, permission_manage_products
):
- product.updated_at = datetime.utcnow()
+ product.updated_at = datetime.datetime.now(tz=datetime.UTC)
product.save()
staff_api_client.user.user_permissions.add(permission_manage_products)
product.pk = None
product.slug = "second-product"
- product.updated_at = datetime.utcnow()
+ product.updated_at = datetime.datetime.now(tz=datetime.UTC)
product.save()
ProductChannelListing.objects.create(
product=product,
@@ -697,7 +697,7 @@ def test_sort_products_by_price_as_staff(
)
product.pk = None
product.slug = "third-product"
- product.updated_at = datetime.utcnow()
+ product.updated_at = datetime.datetime.now(tz=datetime.UTC)
product.save()
ProductChannelListing.objects.create(
product=product,
diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py b/saleor/graphql/product/tests/queries/test_products_query_with_filter.py
index fa773d194b..3ad077d6e6 100644
--- a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py
+++ b/saleor/graphql/product/tests/queries/test_products_query_with_filter.py
@@ -1,9 +1,8 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
import graphene
import pytest
-import pytz
from django.utils import timezone
from .....attribute import AttributeInputType, AttributeType
@@ -477,7 +476,7 @@ def test_products_query_with_filter_date_range_date_attributes(
attribute=date_attribute,
name="Third",
slug="third",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
associate_attribute_values_to_instance(
@@ -535,7 +534,7 @@ def test_products_query_with_filter_date_range_date_variant_attributes(
attribute=date_attribute,
name="First",
slug="first",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
attr_value_2 = AttributeValue.objects.create(
attribute=date_attribute, name="Second", slug="second", date_time=date_value
@@ -608,7 +607,7 @@ def test_products_query_with_filter_date_range_date_time_attributes(
attribute=date_time_attribute,
name="Third",
slug="third",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
associate_attribute_values_to_instance(
@@ -666,7 +665,7 @@ def test_products_query_with_filter_date_range_date_time_variant_attributes(
attribute=date_time_attribute,
name="First",
slug="first",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
attr_value_2 = AttributeValue.objects.create(
attribute=date_time_attribute,
@@ -727,26 +726,26 @@ def test_products_query_with_filter_date_time_range_date_time_attributes(
):
# given
product_type = product_list[0].product_type
- date_value = datetime.now(tz=pytz.utc)
+ date_value = datetime.datetime.now(tz=datetime.UTC)
product_type.product_attributes.add(date_time_attribute)
product_type.variant_attributes.add(date_time_attribute)
attr_value_1 = AttributeValue.objects.create(
attribute=date_time_attribute,
name="First",
slug="first",
- date_time=date_value - timedelta(hours=2),
+ date_time=date_value - datetime.timedelta(hours=2),
)
attr_value_2 = AttributeValue.objects.create(
attribute=date_time_attribute,
name="Second",
slug="second",
- date_time=date_value + timedelta(hours=3),
+ date_time=date_value + datetime.timedelta(hours=3),
)
attr_value_3 = AttributeValue.objects.create(
attribute=date_time_attribute,
name="Third",
slug="third",
- date_time=date_value - timedelta(hours=6),
+ date_time=date_value - datetime.timedelta(hours=6),
)
associate_attribute_values_to_instance(
@@ -768,8 +767,8 @@ def test_products_query_with_filter_date_time_range_date_time_attributes(
{
"slug": date_time_attribute.slug,
"dateTime": {
- "gte": date_value - timedelta(hours=4),
- "lte": date_value + timedelta(hours=4),
+ "gte": date_value - datetime.timedelta(hours=4),
+ "lte": date_value + datetime.timedelta(hours=4),
},
}
],
@@ -1433,7 +1432,7 @@ def test_products_query_with_filter_search_by_date_attribute_value(
product_type.product_attributes.add(date_attribute)
date_attr_value = date_attribute.values.first()
- date_attr_value.date_time = datetime(2020, 10, 10, tzinfo=pytz.utc)
+ date_attr_value.date_time = datetime.datetime(2020, 10, 10, tzinfo=datetime.UTC)
date_attr_value.save(update_fields=["date_time"])
associate_attribute_values_to_instance(
@@ -1482,7 +1481,9 @@ def test_products_query_with_filter_search_by_date_time_attribute_value(
product_type.product_attributes.add(date_time_attribute)
date_time_attr_value = date_time_attribute.values.first()
- date_time_attr_value.date_time = datetime(2020, 10, 10, 22, 20, tzinfo=pytz.utc)
+ date_time_attr_value.date_time = datetime.datetime(
+ 2020, 10, 10, 22, 20, tzinfo=datetime.UTC
+ )
date_time_attr_value.save(update_fields=["date_time"])
associate_attribute_values_to_instance(
@@ -1616,19 +1617,19 @@ def test_products_query_with_filter_stock_availability_including_reservations(
checkout_line=checkout_line,
stock=stocks[0],
quantity_reserved=50,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
),
Reservation(
checkout_line=checkout_line,
stock=stocks[1],
quantity_reserved=100,
- reserved_until=timezone.now() - timedelta(minutes=5),
+ reserved_until=timezone.now() - datetime.timedelta(minutes=5),
),
Reservation(
checkout_line=checkout_line,
stock=stocks[2],
quantity_reserved=50,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
),
]
)
@@ -1904,7 +1905,7 @@ def test_products_query_with_filter_has_preordered_variants_before_end_date(
permission_manage_products,
):
variant = preorder_variant_global_threshold
- variant.preorder_end_date = timezone.now() + timedelta(days=3)
+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=3)
variant.save(update_fields=["preorder_end_date"])
product = preorder_variant_global_threshold.product
@@ -1927,7 +1928,7 @@ def test_products_query_with_filter_has_preordered_variants_after_end_date(
permission_manage_products,
):
variant = preorder_variant_global_threshold
- variant.preorder_end_date = timezone.now() - timedelta(days=3)
+ variant.preorder_end_date = timezone.now() - datetime.timedelta(days=3)
variant.save(update_fields=["preorder_end_date"])
variables = {"filter": {"hasPreorderedVariants": True}}
diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_where.py b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
index 861bfda71f..be91a8ffd0 100644
--- a/saleor/graphql/product/tests/queries/test_products_query_with_where.py
+++ b/saleor/graphql/product/tests/queries/test_products_query_with_where.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import graphene
import pytest
@@ -374,7 +374,7 @@ def test_product_filter_by_is_available(
# given
ProductChannelListing.objects.filter(
product=product_list[1], channel=channel_USD
- ).update(available_for_purchase_at=timezone.now() + timedelta(days=1))
+ ).update(available_for_purchase_at=timezone.now() + datetime.timedelta(days=1))
variables = {
"channel": channel_USD.slug,
"where": where,
@@ -488,10 +488,10 @@ def test_product_filter_by_published_from(api_client, product_list, channel_USD)
timestamp = timezone.now()
ProductChannelListing.objects.filter(
product__in=product_list, channel=channel_USD
- ).update(published_at=timestamp + timedelta(days=1))
+ ).update(published_at=timestamp + datetime.timedelta(days=1))
ProductChannelListing.objects.filter(
product=product_list[0], channel=channel_USD
- ).update(published_at=timestamp - timedelta(days=1))
+ ).update(published_at=timestamp - datetime.timedelta(days=1))
variables = {
"channel": channel_USD.slug,
"where": {"publishedFrom": timestamp},
@@ -514,10 +514,10 @@ def test_product_filter_by_none_as_published_from(
timestamp = timezone.now()
ProductChannelListing.objects.filter(
product__in=product_list, channel=channel_USD
- ).update(published_at=timestamp + timedelta(days=1))
+ ).update(published_at=timestamp + datetime.timedelta(days=1))
ProductChannelListing.objects.filter(
product=product_list[0], channel=channel_USD
- ).update(published_at=timestamp - timedelta(days=1))
+ ).update(published_at=timestamp - datetime.timedelta(days=1))
variables = {
"channel": channel_USD.slug,
"where": {"publishedFrom": None},
@@ -537,10 +537,10 @@ def test_product_filter_by_available_from(api_client, product_list, channel_USD)
timestamp = timezone.now()
ProductChannelListing.objects.filter(
product__in=product_list, channel=channel_USD
- ).update(available_for_purchase_at=timestamp - timedelta(days=1))
+ ).update(available_for_purchase_at=timestamp - datetime.timedelta(days=1))
ProductChannelListing.objects.filter(
product=product_list[0], channel=channel_USD
- ).update(available_for_purchase_at=timestamp + timedelta(days=1))
+ ).update(available_for_purchase_at=timestamp + datetime.timedelta(days=1))
variables = {
"channel": channel_USD.slug,
"where": {"availableFrom": timestamp},
@@ -564,10 +564,10 @@ def test_product_filter_by_none_as_available_from(
timestamp = timezone.now()
ProductChannelListing.objects.filter(
product__in=product_list, channel=channel_USD
- ).update(available_for_purchase_at=timestamp - timedelta(days=1))
+ ).update(available_for_purchase_at=timestamp - datetime.timedelta(days=1))
ProductChannelListing.objects.filter(
product=product_list[0], channel=channel_USD
- ).update(available_for_purchase_at=timestamp + timedelta(days=1))
+ ).update(available_for_purchase_at=timestamp + datetime.timedelta(days=1))
variables = {
"channel": channel_USD.slug,
"where": {"availableFrom": None},
@@ -988,7 +988,7 @@ def test_products_filter_by_date_range_date_attributes(
attribute=date_attribute,
name="Third",
slug="third",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
associate_attribute_values_to_instance(
@@ -1043,7 +1043,7 @@ def test_products_filter_by_date_range_date_variant_attributes(
attribute=date_attribute,
name="First",
slug="first",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
attr_value_2 = AttributeValue.objects.create(
attribute=date_attribute, name="Second", slug="second", date_time=date_value
@@ -1113,7 +1113,7 @@ def test_products_filter_by_date_range_date_time_attributes(
attribute=date_time_attribute,
name="Third",
slug="third",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
associate_attribute_values_to_instance(
@@ -1168,7 +1168,7 @@ def test_products_filter_by_date_range_date_time_variant_attributes(
attribute=date_time_attribute,
name="First",
slug="first",
- date_time=date_value - timedelta(days=1),
+ date_time=date_value - datetime.timedelta(days=1),
)
attr_value_2 = AttributeValue.objects.create(
attribute=date_time_attribute,
@@ -1233,19 +1233,19 @@ def test_products_filter_by_date_time_range_date_time_attributes(
attribute=date_time_attribute,
name="First",
slug="first",
- date_time=date_value - timedelta(hours=2),
+ date_time=date_value - datetime.timedelta(hours=2),
)
attr_value_2 = AttributeValue.objects.create(
attribute=date_time_attribute,
name="Second",
slug="second",
- date_time=date_value + timedelta(hours=3),
+ date_time=date_value + datetime.timedelta(hours=3),
)
attr_value_3 = AttributeValue.objects.create(
attribute=date_time_attribute,
name="Third",
slug="third",
- date_time=date_value - timedelta(hours=6),
+ date_time=date_value - datetime.timedelta(hours=6),
)
associate_attribute_values_to_instance(
@@ -1268,8 +1268,8 @@ def test_products_filter_by_date_time_range_date_time_attributes(
{
"slug": date_time_attribute.slug,
"dateTime": {
- "gte": date_value - timedelta(hours=4),
- "lte": date_value + timedelta(hours=4),
+ "gte": date_value - datetime.timedelta(hours=4),
+ "lte": date_value + datetime.timedelta(hours=4),
},
}
],
@@ -1362,19 +1362,19 @@ def test_products_filter_by_stock_availability_including_reservations(
checkout_line=checkout_line,
stock=stocks[0],
quantity_reserved=50,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
),
Reservation(
checkout_line=checkout_line,
stock=stocks[1],
quantity_reserved=100,
- reserved_until=timezone.now() - timedelta(minutes=5),
+ reserved_until=timezone.now() - datetime.timedelta(minutes=5),
),
Reservation(
checkout_line=checkout_line,
stock=stocks[2],
quantity_reserved=50,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
),
]
)
@@ -1731,7 +1731,7 @@ def test_products_filter_by_has_preordered_variants_before_end_date(
):
# given
variant = preorder_variant_global_threshold
- variant.preorder_end_date = timezone.now() + timedelta(days=3)
+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=3)
variant.save(update_fields=["preorder_end_date"])
product = preorder_variant_global_threshold.product
@@ -1754,7 +1754,7 @@ def test_products_filter_by_has_preordered_variants_after_end_date(
):
# given
variant = preorder_variant_global_threshold
- variant.preorder_end_date = timezone.now() - timedelta(days=3)
+ variant.preorder_end_date = timezone.now() - datetime.timedelta(days=3)
variant.save(update_fields=["preorder_end_date"])
variables = {"channel": channel_USD.slug, "where": {"hasPreorderedVariants": True}}
@@ -1780,7 +1780,7 @@ def test_product_filter_by_updated_at(api_client, product_list, channel_USD):
"updatedAt": {
"range": {
"gte": timestamp,
- "lte": timezone.now() + timedelta(days=1),
+ "lte": timezone.now() + datetime.timedelta(days=1),
}
}
},
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index bf698959aa..489560bda9 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -1,10 +1,9 @@
+import datetime
import os
-from datetime import datetime, timedelta
from unittest.mock import MagicMock, Mock, patch
import graphene
import pytest
-import pytz
from django.core.files import File
from graphql_relay import to_global_id
@@ -2052,14 +2051,14 @@ def test_pagination_for_sorting_collections_by_published_at_date(
Collection(name="Coll3", slug="collection-3"),
]
)
- now = datetime.now(pytz.UTC)
+ now = datetime.datetime.now(tz=datetime.UTC)
CollectionChannelListing.objects.bulk_create(
[
CollectionChannelListing(
channel=channel_USD,
collection=collection,
is_published=True,
- published_at=now - timedelta(days=num),
+ published_at=now - datetime.timedelta(days=num),
)
for num, collection in enumerate(collections)
]
diff --git a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
index 0fe6058aa2..0bed794527 100644
--- a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
@@ -2,7 +2,6 @@ import datetime
import graphene
import pytest
-import pytz
from ....product.models import Collection, CollectionChannelListing
from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
@@ -35,13 +34,13 @@ def collections_for_sorting_with_channels(channel_USD, channel_PLN):
),
CollectionChannelListing(
collection=collections[2],
- published_at=datetime.datetime(2004, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2004, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_USD,
),
CollectionChannelListing(
collection=collections[3],
- published_at=datetime.datetime(2003, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2003, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_USD,
),
@@ -60,13 +59,13 @@ def collections_for_sorting_with_channels(channel_USD, channel_PLN):
),
CollectionChannelListing(
collection=collections[2],
- published_at=datetime.datetime(2002, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2002, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_PLN,
),
CollectionChannelListing(
collection=collections[4],
- published_at=datetime.datetime(2001, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2001, 1, 1, tzinfo=datetime.UTC),
is_published=False,
channel=channel_PLN,
),
diff --git a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
index d3b91f8f18..e4d3d890a9 100644
--- a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
@@ -3,7 +3,6 @@ import uuid
from decimal import Decimal
import pytest
-import pytz
from freezegun import freeze_time
from ....product import ProductTypeKind
@@ -65,7 +64,7 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
channel=channel_USD,
is_published=True,
discounted_price_amount=Decimal(5),
- published_at=datetime.datetime(2002, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2002, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=None,
),
ProductChannelListing(
@@ -73,9 +72,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
channel=channel_USD,
is_published=True,
discounted_price_amount=Decimal(15),
- published_at=datetime.datetime(2000, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2000, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=datetime.datetime(
- 2003, 1, 1, tzinfo=pytz.UTC
+ 2003, 1, 1, tzinfo=datetime.UTC
),
),
ProductChannelListing(
@@ -83,9 +82,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
channel=channel_USD,
is_published=False,
discounted_price_amount=Decimal(4),
- published_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=datetime.datetime(
- 2000, 1, 1, tzinfo=pytz.UTC
+ 2000, 1, 1, tzinfo=datetime.UTC
),
),
ProductChannelListing(
@@ -94,9 +93,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
is_published=True,
visible_in_listings=True,
discounted_price_amount=Decimal(7),
- published_at=datetime.datetime(2001, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2001, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=datetime.datetime(
- 2001, 1, 1, tzinfo=pytz.UTC
+ 2001, 1, 1, tzinfo=datetime.UTC
),
),
# Second channel
@@ -105,9 +104,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
channel=channel_PLN,
is_published=False,
discounted_price_amount=Decimal(15),
- published_at=datetime.datetime(2003, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2003, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=datetime.datetime(
- 2003, 1, 1, tzinfo=pytz.UTC
+ 2003, 1, 1, tzinfo=datetime.UTC
),
),
ProductChannelListing(
@@ -115,9 +114,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
channel=channel_PLN,
is_published=True,
discounted_price_amount=Decimal(4),
- published_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=datetime.datetime(
- 2002, 1, 1, tzinfo=pytz.UTC
+ 2002, 1, 1, tzinfo=datetime.UTC
),
),
ProductChannelListing(
@@ -125,7 +124,7 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
channel=channel_PLN,
is_published=True,
discounted_price_amount=Decimal(5),
- published_at=datetime.datetime(2000, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(2000, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=None,
),
ProductChannelListing(
@@ -134,9 +133,9 @@ def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
is_published=True,
visible_in_listings=True,
discounted_price_amount=Decimal(7),
- published_at=datetime.datetime(1998, 1, 1, tzinfo=pytz.UTC),
+ published_at=datetime.datetime(1998, 1, 1, tzinfo=datetime.UTC),
available_for_purchase_at=datetime.datetime(
- 2000, 1, 1, tzinfo=pytz.UTC
+ 2000, 1, 1, tzinfo=datetime.UTC
),
),
]
diff --git a/saleor/graphql/product/tests/test_product_sorting.py b/saleor/graphql/product/tests/test_product_sorting.py
index 07adc6cc8f..f0950117e2 100644
--- a/saleor/graphql/product/tests/test_product_sorting.py
+++ b/saleor/graphql/product/tests/test_product_sorting.py
@@ -1,9 +1,8 @@
+import datetime
import random
-from datetime import datetime, timedelta
import graphene
import pytest
-import pytz
from django.utils import timezone
from freezegun import freeze_time
@@ -170,7 +169,7 @@ def test_sort_products_by_published_at(
product_channel_listings = []
for iter_value, product in enumerate(product_list):
product_channel_listing = product.channel_listings.get(channel=channel_USD)
- product_channel_listing.published_at = timezone.now() - timedelta(
+ product_channel_listing.published_at = timezone.now() - datetime.timedelta(
days=iter_value
)
product_channel_listings.append(product_channel_listing)
@@ -282,7 +281,7 @@ def test_pagination_for_sorting_products_by_published_at_date(
listings_in_bulk = {listing.product_id: listing for listing in channel_listings}
for product in product_list:
listing = listings_in_bulk.get(product.id)
- listing.published_at = datetime.now(pytz.UTC)
+ listing.published_at = datetime.datetime.now(tz=datetime.UTC)
ProductChannelListing.objects.bulk_update(channel_listings, ["published_at"])
diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.py
index 491130b2ac..c921e3df8b 100644
--- a/saleor/graphql/product/tests/test_variant_availability.py
+++ b/saleor/graphql/product/tests/test_variant_availability.py
@@ -1,5 +1,5 @@
+import datetime
import warnings
-from datetime import timedelta
import graphene
import pytest
@@ -648,7 +648,9 @@ def test_variant_quantity_available_with_enabled_expired_reservations(
checkout_line_with_reservation_in_many_stocks,
channel_USD,
):
- Reservation.objects.update(reserved_until=timezone.now() - timedelta(minutes=2))
+ Reservation.objects.update(
+ reserved_until=timezone.now() - datetime.timedelta(minutes=2)
+ )
variant = checkout_line_with_reservation_in_many_stocks.variant
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant.pk),
diff --git a/saleor/graphql/product/tests/test_variant_with_filtering.py b/saleor/graphql/product/tests/test_variant_with_filtering.py
index d0dc655d08..0644bf04ab 100644
--- a/saleor/graphql/product/tests/test_variant_with_filtering.py
+++ b/saleor/graphql/product/tests/test_variant_with_filtering.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -105,13 +105,13 @@ def products_for_variant_filtering(product_type, category):
product=products[6],
sku="Preorder-V2",
is_preorder=True,
- preorder_end_date=timezone.now() + timedelta(days=1),
+ preorder_end_date=timezone.now() + datetime.timedelta(days=1),
),
ProductVariant(
product=products[6],
sku="Preorder-V3",
is_preorder=True,
- preorder_end_date=timezone.now() - timedelta(days=1),
+ preorder_end_date=timezone.now() - datetime.timedelta(days=1),
),
]
)
diff --git a/saleor/graphql/warehouse/tests/queries/test_stock.py b/saleor/graphql/warehouse/tests/queries/test_stock.py
index 3e12593d4b..dbb0db7da3 100644
--- a/saleor/graphql/warehouse/tests/queries/test_stock.py
+++ b/saleor/graphql/warehouse/tests/queries/test_stock.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import graphene
from django.utils import timezone
@@ -99,7 +99,9 @@ def test_query_stock_with_expired_reservations(
permission_manage_products,
):
# given
- Reservation.objects.update(reserved_until=timezone.now() - timedelta(minutes=2))
+ Reservation.objects.update(
+ reserved_until=timezone.now() - datetime.timedelta(minutes=2)
+ )
staff_api_client.user.user_permissions.add(permission_manage_products)
stock_id = graphene.Node.to_global_id("Stock", stock.pk)
diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.py
index 6f2aef1cd2..d77d85c4ef 100644
--- a/saleor/graphql/webhook/subscription_payload.py
+++ b/saleor/graphql/webhook/subscription_payload.py
@@ -1,5 +1,5 @@
+import datetime
from collections.abc import Iterable
-from datetime import datetime
from typing import Any, Optional, Union
from celery.utils.log import get_task_logger
@@ -28,7 +28,7 @@ def initialize_request(
sync_event=False,
allow_replica=False,
event_type: Optional[str] = None,
- request_time: Optional[datetime] = None,
+ request_time: Optional[datetime.datetime] = None,
dataloaders: Optional[dict] = None,
) -> SaleorContext:
"""Prepare a request object for webhook subscription.
@@ -234,7 +234,7 @@ def generate_pre_save_payloads(
instances: Iterable[models.Model],
event_type: str,
requestor: Union[User, App, None],
- request_time: datetime,
+ request_time: datetime.datetime,
):
if not settings.ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS:
return {}
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
index f761ac891a..0e1e2bd500 100644
--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest import mock
from django.test import override_settings
@@ -22,7 +22,7 @@ def test_checkout_total_price_use_pregenerated_payload(
tax_app,
):
# given
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -68,7 +68,7 @@ def test_checkout_subtotal_price_use_pregenerated_payload(
tax_app,
):
# given
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -114,7 +114,7 @@ def test_checkout_total_balance_use_pregenerated_payload(
tax_app,
):
# given
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -155,7 +155,7 @@ def test_checkout_shipping_price_use_pregenerated_payload(
tax_app,
):
# given
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -204,7 +204,7 @@ def test_checkout_authorize_status_use_pregenerated_payload(
tax_app,
):
# given
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -243,7 +243,7 @@ def test_checkout_charge_status_use_pregenerated_payload(
tax_app,
):
# given
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -282,7 +282,7 @@ def test_checkout_line_unit_price_use_pregenerated_payload(
tax_app,
):
# given
- checkout_with_item.price_expiration = timezone.now() - timedelta(days=1)
+ checkout_with_item.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout_with_item.save()
checkout_global_id = to_global_id_or_none(checkout_with_item)
checkout_total_price_query = """
@@ -333,7 +333,7 @@ def test_checkout_line_total_price_use_pregenerated_payload(
tax_app,
):
# given
- checkout_with_item.price_expiration = timezone.now() - timedelta(days=1)
+ checkout_with_item.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout_with_item.save()
checkout_global_id = to_global_id_or_none(checkout_with_item)
checkout_total_price_query = """
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
index 865ed55596..ae6c3d4ca3 100644
--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
@@ -1,5 +1,5 @@
+import datetime
from collections import defaultdict
-from datetime import timedelta
from unittest import mock
from django.test import override_settings
@@ -32,7 +32,7 @@ def test_pregenerated_payload_with_selected_tax_app_price_entered_with_tax(
tax_configuration.prices_entered_with_tax = True
tax_configuration.tax_app_id = tax_app_global_id
tax_configuration.save()
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -84,7 +84,7 @@ def test_pregenerated_payload_with_selected_tax_app_price_entered_without_tax(
tax_configuration.prices_entered_with_tax = False
tax_configuration.tax_app_id = tax_app_global_id
tax_configuration.save()
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -135,7 +135,7 @@ def test_pregenerated_payload_with_selected_external_tax_app_price_entered_witho
tax_configuration.prices_entered_with_tax = False
tax_configuration.tax_app_id = external_tax_app.identifier
tax_configuration.save()
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -186,7 +186,7 @@ def test_pregenerated_payload_with_selected_external_tax_app_price_entered_with_
tax_configuration.prices_entered_with_tax = True
tax_configuration.tax_app_id = external_tax_app.identifier
tax_configuration.save()
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -237,7 +237,7 @@ def test_pregenerated_payload_with_all_apps_price_entered_with_tax(
tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
tax_configuration.prices_entered_with_tax = True
tax_configuration.save()
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -289,7 +289,7 @@ def test_pregenerated_payload_with_all_apps_price_entered_without_tax(
tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
tax_configuration.prices_entered_with_tax = False
tax_configuration.save()
- checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
@@ -347,7 +347,7 @@ def test_pregenerated_payload_skipped_when_checkout_not_expired(
tax_configuration.prices_entered_with_tax = True
tax_configuration.tax_app_id = tax_app_global_id
tax_configuration.save()
- checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.price_expiration = timezone.now() + datetime.timedelta(days=1)
checkout.save()
checkout_global_id = to_global_id_or_none(checkout)
checkout_total_price_query = """
diff --git a/saleor/order/tasks.py b/saleor/order/tasks.py
index 36b43b4837..640e9100fc 100644
--- a/saleor/order/tasks.py
+++ b/saleor/order/tasks.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import timedelta
from django.conf import settings
from django.db.models import Exists, F, Func, OuterRef, Subquery, Value
@@ -181,7 +181,7 @@ def delete_expired_orders_task():
channel_qs = Channel.objects.using(
settings.DATABASE_CONNECTION_REPLICA_NAME
).filter(
- delete_expired_orders_after__gt=timedelta(),
+ delete_expired_orders_after__gt=datetime.timedelta(),
id=OuterRef("channel"),
)
diff --git a/saleor/order/tests/test_tasks.py b/saleor/order/tests/test_tasks.py
index 12aef32cec..821253c7c5 100644
--- a/saleor/order/tests/test_tasks.py
+++ b/saleor/order/tests/test_tasks.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import timedelta
from unittest import mock
from unittest.mock import call, patch
@@ -40,18 +40,18 @@ def test_expire_orders_task_check_voucher(
order_1 = order_list[0]
order_1.status = OrderStatus.UNCONFIRMED
- order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.created_at = now - datetime.timedelta(minutes=10)
order_1.voucher_code = code.code
order_1.save()
order_2 = order_list[1]
order_2.status = OrderStatus.UNCONFIRMED
- order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.created_at = now - datetime.timedelta(minutes=10)
order_2.voucher_code = code.code
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.created_at = now - datetime.timedelta(minutes=10)
order_3.status = OrderStatus.UNFULFILLED
order_3.voucher_code = code.code
order_3.save()
@@ -106,18 +106,18 @@ def test_expire_orders_task_check_multiple_vouchers(
order_1 = order_list[0]
order_1.status = OrderStatus.UNCONFIRMED
- order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.created_at = now - datetime.timedelta(minutes=10)
order_1.voucher_code = code.code
order_1.save()
order_2 = order_list[1]
order_2.status = OrderStatus.UNCONFIRMED
- order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.created_at = now - datetime.timedelta(minutes=10)
order_2.voucher_code = code_percentage.code
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.created_at = now - datetime.timedelta(minutes=10)
order_3.status = OrderStatus.UNFULFILLED
order_3.voucher_code = code.code
order_3.save()
@@ -160,12 +160,12 @@ def test_expire_orders_task_creates_order_events(order_list, allocations, channe
order_1.save()
order_2 = order_list[1]
- order_2.created_at = now - timezone.timedelta(minutes=120)
+ order_2.created_at = now - datetime.timedelta(minutes=120)
order_2.status = OrderStatus.UNCONFIRMED
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=120)
+ order_3.created_at = now - datetime.timedelta(minutes=120)
order_3.status = OrderStatus.UNFULFILLED
order_3.save()
@@ -207,16 +207,16 @@ def test_expire_orders_task_with_transaction_item(
order_1 = order_list[0]
order_1.status = OrderStatus.UNCONFIRMED
- order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.created_at = now - datetime.timedelta(minutes=10)
order_1.save()
order_2 = order_list[1]
order_2.status = OrderStatus.UNCONFIRMED
- order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.created_at = now - datetime.timedelta(minutes=10)
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.created_at = now - datetime.timedelta(minutes=10)
order_3.status = OrderStatus.UNFULFILLED
order_3.save()
@@ -258,16 +258,16 @@ def test_expire_orders_task_with_payment(
order_1 = order_list[0]
order_1.status = OrderStatus.UNCONFIRMED
- order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.created_at = now - datetime.timedelta(minutes=10)
order_1.save()
order_2 = order_list[1]
order_2.status = OrderStatus.UNCONFIRMED
- order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.created_at = now - datetime.timedelta(minutes=10)
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.created_at = now - datetime.timedelta(minutes=10)
order_3.status = OrderStatus.UNFULFILLED
order_3.save()
@@ -351,12 +351,12 @@ def test_expire_orders_task_after(order_list, allocations, channel_USD):
order_1.save()
order_2 = order_list[1]
- order_2.created_at = now - timezone.timedelta(minutes=120)
+ order_2.created_at = now - datetime.timedelta(minutes=120)
order_2.status = OrderStatus.UNCONFIRMED
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=120)
+ order_3.created_at = now - datetime.timedelta(minutes=120)
order_3.status = OrderStatus.UNFULFILLED
order_3.save()
@@ -422,12 +422,12 @@ def test_expire_orders_task_do_not_call_sync_webhooks(
order_1.save()
order_2 = order_list[1]
- order_2.created_at = now - timezone.timedelta(minutes=120)
+ order_2.created_at = now - datetime.timedelta(minutes=120)
order_2.status = OrderStatus.UNCONFIRMED
order_2.save()
order_3 = order_list[2]
- order_3.created_at = now - timezone.timedelta(minutes=120)
+ order_3.created_at = now - datetime.timedelta(minutes=120)
order_3.status = OrderStatus.UNFULFILLED
order_3.save()
@@ -467,7 +467,7 @@ def test_expire_orders_task_do_not_call_sync_webhooks(
@freeze_time("2020-03-18 12:00:00")
def test_delete_expired_orders_task(order_list, allocations, channel_USD):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=3)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
channel_USD.save()
now = timezone.now()
@@ -477,12 +477,12 @@ def test_delete_expired_orders_task(order_list, allocations, channel_USD):
order_1.save()
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.EXPIRED
order_2.save()
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.EXPIRED
order_3.save()
@@ -499,23 +499,23 @@ def test_delete_expired_orders_task_multiple_channels_one_without_delete(
order_list, allocations, channel_USD, channel_PLN
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=3)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
channel_USD.save()
now = timezone.now()
order_1 = order_list[0]
- order_1.expired_at = now - timedelta(days=5)
+ order_1.expired_at = now - datetime.timedelta(days=5)
order_1.status = OrderStatus.EXPIRED
order_1.channel = channel_PLN
order_1.save()
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.EXPIRED
order_2.save()
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.EXPIRED
order_3.save()
@@ -532,7 +532,7 @@ def test_delete_expired_orders_task_channel_without_delete(
order_list, allocations, channel_USD
):
# given
- channel_USD.delete_expired_orders_after = timedelta()
+ channel_USD.delete_expired_orders_after = datetime.timedelta()
channel_USD.save()
now = timezone.now()
@@ -542,12 +542,12 @@ def test_delete_expired_orders_task_channel_without_delete(
order_1.save()
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.EXPIRED
order_2.save()
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.EXPIRED
order_3.save()
@@ -563,25 +563,25 @@ def test_delete_expired_orders_task_multiple_channels_with_different_deletion_ti
order_list, allocations, channel_USD, channel_PLN
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=3)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
channel_USD.save()
- channel_PLN.delete_expired_orders_after = timedelta(days=5)
+ channel_PLN.delete_expired_orders_after = datetime.timedelta(days=5)
channel_PLN.save()
now = timezone.now()
order_1 = order_list[0]
- order_1.expired_at = now - timedelta(days=2)
+ order_1.expired_at = now - datetime.timedelta(days=2)
order_1.status = OrderStatus.EXPIRED
order_1.save()
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.EXPIRED
order_2.save()
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.EXPIRED
order_3.channel = channel_PLN
order_3.save()
@@ -589,7 +589,7 @@ def test_delete_expired_orders_task_multiple_channels_with_different_deletion_ti
order_4 = order_3
order_4.pk = None
order_4.number = get_order_number()
- order_4.expired_at = now - timedelta(days=4)
+ order_4.expired_at = now - datetime.timedelta(days=4)
order_4.status = OrderStatus.EXPIRED
order_4.channel = channel_PLN
order_4.save()
@@ -608,7 +608,7 @@ def test_delete_expired_orders_task_orders_with_different_status_than_expired(
order_list, allocations, channel_USD
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=3)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
channel_USD.save()
now = timezone.now()
@@ -618,12 +618,12 @@ def test_delete_expired_orders_task_orders_with_different_status_than_expired(
order_1.save()
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.FULFILLED
order_2.save()
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.RETURNED
order_3.save()
@@ -639,30 +639,30 @@ def test_delete_expired_orders_task_orders_with_payment_objects(
order_list, payment_dummy, transaction_item_generator, allocations, channel_USD
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=3)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
channel_USD.save()
now = timezone.now()
order_1 = order_list[0]
- order_1.expired_at = now - timedelta(days=2)
+ order_1.expired_at = now - datetime.timedelta(days=2)
order_1.status = OrderStatus.EXPIRED
order_1.save()
transaction_item_generator(order_id=order_1.pk)
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.EXPIRED
order_2.save()
transaction_item_generator(order_id=order_2.pk)
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.EXPIRED
order_3.save()
transaction_item_generator(order_id=order_3.pk)
order_4 = payment_dummy.order
- order_4.expired_at = now - timedelta(days=4)
+ order_4.expired_at = now - datetime.timedelta(days=4)
order_4.status = OrderStatus.EXPIRED
order_4.save()
@@ -679,7 +679,7 @@ def test_delete_expired_orders_task_schedule_itself(
mocked_delay, order_list, allocations, channel_USD
):
# given
- channel_USD.delete_expired_orders_after = timedelta(days=3)
+ channel_USD.delete_expired_orders_after = datetime.timedelta(days=3)
channel_USD.save()
now = timezone.now()
@@ -689,12 +689,12 @@ def test_delete_expired_orders_task_schedule_itself(
order_1.save()
order_2 = order_list[1]
- order_2.expired_at = now - timedelta(days=5)
+ order_2.expired_at = now - datetime.timedelta(days=5)
order_2.status = OrderStatus.EXPIRED
order_2.save()
order_3 = order_list[2]
- order_3.expired_at = now - timedelta(days=7)
+ order_3.expired_at = now - datetime.timedelta(days=7)
order_3.status = OrderStatus.EXPIRED
order_3.save()
@@ -754,13 +754,13 @@ def test_bulk_release_voucher_usage_voucher_usage_mismatch(
order_1 = order_list[0]
order_1.status = OrderStatus.UNCONFIRMED
- order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.created_at = now - datetime.timedelta(minutes=10)
order_1.voucher_code = code.code
order_1.save()
order_2 = order_list[1]
order_2.status = OrderStatus.UNCONFIRMED
- order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.created_at = now - datetime.timedelta(minutes=10)
order_2.voucher_code = code.code
order_2.save()
diff --git a/saleor/page/migrations/0013_update_publication_date.py b/saleor/page/migrations/0013_update_publication_date.py
index f493ac0413..7ff93dd702 100644
--- a/saleor/page/migrations/0013_update_publication_date.py
+++ b/saleor/page/migrations/0013_update_publication_date.py
@@ -1,4 +1,4 @@
-from datetime import date
+import datetime
from django.db import migrations
@@ -8,7 +8,9 @@ def set_missing_page_publication_date(apps, schema_editor):
published_page = Page.objects.filter(
publication_date__isnull=True, is_published=True
)
- published_page.update(publication_date=date.today())
+ published_page.update(
+ publication_date=datetime.datetime.now(tz=datetime.UTC).date()
+ )
class Migration(migrations.Migration):
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 932b119040..6e728e84d0 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -1,5 +1,5 @@
+import datetime
from dataclasses import InitVar, dataclass, field
-from datetime import datetime
from decimal import Decimal
from enum import Enum
from functools import cached_property
@@ -122,7 +122,7 @@ class TransactionRequestEventResponse:
psp_reference: Optional[str]
type: str
amount: Decimal
- time: Optional[datetime] = None
+ time: Optional[datetime.datetime] = None
external_url: Optional[str] = ""
message: Optional[str] = ""
diff --git a/saleor/payment/tasks.py b/saleor/payment/tasks.py
index 6d665e9e2a..9c264c7e05 100644
--- a/saleor/payment/tasks.py
+++ b/saleor/payment/tasks.py
@@ -1,8 +1,7 @@
+import datetime
import logging
import uuid
-from datetime import datetime
-import pytz
from django.conf import settings
from django.db.models import OuterRef, Q, Subquery
@@ -27,7 +26,8 @@ def checkouts_with_funds_to_release():
checkout doesn't have any processed funds.
"""
expired_checkouts_time = (
- datetime.now(pytz.UTC) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
)
return Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(
diff --git a/saleor/payment/tests/test_tasks.py b/saleor/payment/tests/test_tasks.py
index 2396992e1c..d21c136d72 100644
--- a/saleor/payment/tests/test_tasks.py
+++ b/saleor/payment/tests/test_tasks.py
@@ -1,8 +1,7 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest import mock
-import pytz
from freezegun import freeze_time
from ...checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
@@ -23,9 +22,12 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_last_chan
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_before_ttl = ttl_time + timedelta(seconds=1)
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_before_ttl = ttl_time + datetime.timedelta(seconds=1)
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -59,8 +61,11 @@ def test_transaction_release_funds_for_checkout_task_checkout_not_refundable(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -92,9 +97,12 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_new_tr_modifi
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_before_ttl = ttl_time + timedelta(seconds=1)
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_before_ttl = ttl_time + datetime.timedelta(seconds=1)
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_before_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -128,8 +136,11 @@ def test_transaction_release_funds_for_checkout_task_checkout_with_none_status(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -162,8 +173,11 @@ def test_transaction_release_funds_for_checkout_task_not_valid_checkout(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item_generator(
charged_value=Decimal(100),
@@ -189,8 +203,11 @@ def test_transaction_release_funds_for_checkout_task_transaction_for_order(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item_generator(
order_id=order.pk,
@@ -217,8 +234,11 @@ def test_transaction_release_funds_for_checkout_task_without_transaction(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
checkout.authorize_status = CheckoutAuthorizeStatus.FULL
checkout.charge_status = CheckoutChargeStatus.FULL
@@ -252,8 +272,11 @@ def test_transaction_release_funds_for_checkout_task_refund_already_requested(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -286,8 +309,11 @@ def test_transaction_release_funds_for_checkout_task_cancel_already_requested(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -320,8 +346,11 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_authorizat
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
@@ -366,8 +395,11 @@ def test_transaction_release_funds_for_checkout_task_transaction_with_charge(
plugins_manager,
):
# given
- ttl_time = datetime.now(tz=pytz.utc) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
- time_after_ttl = ttl_time - timedelta(seconds=1)
+ ttl_time = (
+ datetime.datetime.now(tz=datetime.UTC)
+ - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS
+ )
+ time_after_ttl = ttl_time - datetime.timedelta(seconds=1)
with freeze_time(time_after_ttl):
transaction_item = transaction_item_generator(
checkout_id=checkout.pk,
diff --git a/saleor/payment/tests/test_transaction_item_calculations.py b/saleor/payment/tests/test_transaction_item_calculations.py
index 709ffc5e77..012d3efe10 100644
--- a/saleor/payment/tests/test_transaction_item_calculations.py
+++ b/saleor/payment/tests/test_transaction_item_calculations.py
@@ -1,8 +1,6 @@
import datetime
-from datetime import timedelta
from decimal import Decimal
-import pytz
from django.utils import timezone
from freezegun import freeze_time
@@ -235,7 +233,7 @@ def test_with_authorize_success_and_older_failure_events(
)
failure_event = events[1]
assert failure_event.type == TransactionEventType.AUTHORIZATION_FAILURE
- failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.created_at = timezone.now() - datetime.timedelta(minutes=5)
failure_event.save()
# when
@@ -277,7 +275,7 @@ def test_with_authorize_adjustment(
# set the newest time for adjustment event
adjustment_event = events[2]
assert adjustment_event.type == TransactionEventType.AUTHORIZATION_ADJUSTMENT
- adjustment_event.created_at = timezone.now() + timedelta(minutes=5)
+ adjustment_event.created_at = timezone.now() + datetime.timedelta(minutes=5)
adjustment_event.save()
# when
@@ -502,7 +500,7 @@ def test_with_charge_success_and_older_failure_events(
)
failure_event = events[1]
assert failure_event.type == TransactionEventType.CHARGE_FAILURE
- failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.created_at = timezone.now() - datetime.timedelta(minutes=5)
failure_event.save()
# when
@@ -763,7 +761,7 @@ def test_with_refund_success_and_older_failure_events(
)
failure_event = events[1]
assert failure_event.type == TransactionEventType.REFUND_FAILURE
- failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.created_at = timezone.now() - datetime.timedelta(minutes=5)
failure_event.save()
# when
@@ -1030,7 +1028,7 @@ def test_with_cancel_success_and_older_failure_events(
)
failure_event = events[1]
assert failure_event.type == TransactionEventType.CANCEL_FAILURE
- failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.created_at = timezone.now() - datetime.timedelta(minutes=5)
failure_event.save()
# when
@@ -1660,7 +1658,7 @@ def test_recalculate_transaction_amounts_updates_transaction_modified_at(
)
# when
with freeze_time("2023-03-18 12:00:00"):
- calculation_time = datetime.datetime.now(pytz.UTC)
+ calculation_time = datetime.datetime.now(tz=datetime.UTC)
recalculate_transaction_amounts(transaction)
# then
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 385023fb66..9df3fc0382 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1,10 +1,8 @@
-from datetime import datetime, timedelta
+import datetime
from decimal import Decimal
from unittest.mock import patch
import pytest
-import pytz
-from django.utils import timezone
from freezegun import freeze_time
from ...checkout import CheckoutAuthorizeStatus
@@ -256,19 +254,37 @@ def test_parse_transaction_action_data_with_only_psp_reference():
[
(
"2023-10-17T10:18:28.111Z",
- datetime(2023, 10, 17, 10, 18, 28, 111000, tzinfo=pytz.UTC),
+ datetime.datetime(2023, 10, 17, 10, 18, 28, 111000, tzinfo=datetime.UTC),
+ ),
+ ("2011-11-04", datetime.datetime(2011, 11, 4, 0, 0, tzinfo=datetime.UTC)),
+ (
+ "2011-11-04T00:05:23",
+ datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.UTC),
+ ),
+ (
+ "2011-11-04T00:05:23Z",
+ datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.UTC),
+ ),
+ (
+ "20111104T000523",
+ datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.UTC),
+ ),
+ (
+ "2011-W01-2T00:05:23.283",
+ datetime.datetime(2011, 1, 4, 0, 5, 23, 283000, tzinfo=datetime.UTC),
+ ),
+ (
+ "2011-11-04 00:05:23.283",
+ datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.UTC),
),
- ("2011-11-04", datetime(2011, 11, 4, 0, 0)),
- ("2011-11-04T00:05:23", datetime(2011, 11, 4, 0, 5, 23)),
- ("2011-11-04T00:05:23Z", datetime(2011, 11, 4, 0, 5, 23, tzinfo=pytz.UTC)),
- ("20111104T000523", datetime(2011, 11, 4, 0, 5, 23)),
- ("2011-W01-2T00:05:23.283", datetime(2011, 1, 4, 0, 5, 23, 283000)),
- ("2011-11-04 00:05:23.283", datetime(2011, 11, 4, 0, 5, 23, 283000)),
(
"2011-11-04 00:05:23.283+00:00",
- datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=pytz.UTC),
+ datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.UTC),
+ ),
+ (
+ "1994-11-05T13:15:30Z",
+ datetime.datetime(1994, 11, 5, 13, 15, 30, tzinfo=datetime.UTC),
),
- ("1994-11-05T13:15:30Z", datetime(1994, 11, 5, 13, 15, 30, tzinfo=pytz.UTC)),
],
)
def test_parse_transaction_action_data_with_provided_time(
@@ -328,7 +344,7 @@ def test_parse_transaction_action_data_with_event_all_fields_provided():
assert isinstance(parsed_data.event, TransactionRequestEventResponse)
assert parsed_data.event.psp_reference == expected_psp_reference
assert parsed_data.event.amount == event_amount
- assert parsed_data.event.time == datetime.fromisoformat(event_time)
+ assert parsed_data.event.time == datetime.datetime.fromisoformat(event_time)
assert parsed_data.event.external_url == event_url
assert parsed_data.event.message == event_cause
assert parsed_data.event.type == event_type
@@ -386,7 +402,7 @@ def test_parse_transaction_action_data_with_event_only_mandatory_fields():
assert parsed_data.event.psp_reference == expected_psp_reference
assert parsed_data.event.type == TransactionEventType.CHARGE_SUCCESS
assert parsed_data.event.amount == expected_amount
- assert parsed_data.event.time == timezone.now()
+ assert parsed_data.event.time == datetime.datetime.now(tz=datetime.UTC)
assert parsed_data.event.external_url == ""
assert parsed_data.event.message == ""
@@ -623,7 +639,7 @@ def test_create_transaction_event_from_request_and_webhook_response_part_event(
assert event
assert event.psp_reference == expected_psp_reference
assert event.amount_value == amount
- assert event.created_at == timezone.now()
+ assert event.created_at == datetime.datetime.now(tz=datetime.UTC)
assert event.external_url == ""
assert event.message == ""
assert event.type == TransactionEventType.CHARGE_SUCCESS
@@ -986,7 +1002,7 @@ def test_create_transaction_event_from_request_and_webhook_response_full_event(
assert event
assert event.psp_reference == expected_psp_reference
assert event.amount_value == event_amount
- assert event.created_at == datetime.fromisoformat(event_time)
+ assert event.created_at == datetime.datetime.fromisoformat(event_time)
assert event.external_url == event_url
assert event.message == event_cause
assert event.type == event_type
@@ -2327,7 +2343,7 @@ def test_create_transaction_event_from_request_and_webhook_updates_modified_at(
# when
with freeze_time("2023-03-18 12:00:00"):
- calculation_time = datetime.now(pytz.UTC)
+ calculation_time = datetime.datetime.now(tz=datetime.UTC)
create_transaction_event_from_request_and_webhook_response(
request_event, app, response_data
)
@@ -2359,7 +2375,7 @@ def test_create_transaction_event_updates_transaction_modified_at(
# when
with freeze_time("2023-03-18 12:00:00"):
- calculation_time = datetime.now(pytz.UTC)
+ calculation_time = datetime.datetime.now(tz=datetime.UTC)
create_transaction_event_for_transaction_session(
request_event,
webhook_app,
@@ -2470,7 +2486,7 @@ def test_create_transaction_event_updates_transaction_modified_at_for_failure(
# when
with freeze_time("2023-03-18 12:00:00"):
- calculation_time = datetime.now(pytz.UTC)
+ calculation_time = datetime.datetime.now(tz=datetime.UTC)
create_transaction_event_for_transaction_session(
request_event,
webhook_app,
@@ -2913,7 +2929,7 @@ def test_get_transaction_event_amount_match_the_newest_event(
)
newest_event = events[-1]
for event in events[:-1]:
- event.created_at = newest_event.created_at - timedelta(minutes=10)
+ event.created_at = newest_event.created_at - datetime.timedelta(minutes=10)
TransactionEvent.objects.bulk_update(events[:-1], ["created_at"])
# when
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index d86197a76b..27c89ca0a4 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,7 +1,7 @@
+import datetime
import decimal
import json
import logging
-from datetime import datetime
from decimal import Decimal
from typing import Any, Optional, Union, cast, overload
@@ -892,16 +892,19 @@ def parse_transaction_event_data(
if event_time_data := event_data.get("time"):
try:
parsed_event_data["time"] = (
- datetime.fromisoformat(event_time_data) if event_time_data else None
+ datetime.datetime.fromisoformat(event_time_data).replace(
+ tzinfo=datetime.UTC
+ )
+ if event_time_data
+ else None
)
except ValueError:
try:
- # datetime.fromisoformat supports only formats of the objects that were
+ # datetime.datetime.fromisoformat supports only formats of the objects that were
# created by date.isoformat() or datetime.isoformat(). It is fixed in
# 3.11
# This try except block can be removed after moving to python 3.11
- # ref: https://docs.python.org/3/library/datetime.html#datetime.
- # datetime.fromisoformat
+ # ref: https://docs.python.org/3/library/datetime.html#datetime.datetime.datetime.fromisoformat
parsed_event_data["time"] = parse_datetime(event_time_data)
except ValueError:
logger.warning(invalid_msg, "time", event_time_data)
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index dea8979478..c425eb4629 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -1,8 +1,8 @@
+import datetime
import json
import logging
from collections.abc import Iterable
from dataclasses import dataclass
-from datetime import date
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional, Union, cast
from urllib.parse import urljoin
@@ -487,7 +487,7 @@ def generate_request_data(
"type": transaction_type,
"lines": lines,
"code": transaction_token,
- "date": str(date.today()),
+ "date": str(datetime.datetime.now(tz=datetime.UTC).date()),
# https://developer.avalara.com/avatax/dev-guide/transactions/simple-transaction/
"customerCode": 0,
# https://developer.avalara.com/avatax/dev-guide/discounts-and-overrides/discounts/
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 27f4f4120d..7597abf845 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -4559,7 +4559,7 @@ def test_order_confirmed(
}
],
"code": str(order.id),
- "date": datetime.date.today().strftime("%Y-%m-%d"),
+ "date": datetime.datetime.now(tz=datetime.UTC).date().strftime("%Y-%m-%d"),
"customerCode": 0,
"discount": None,
"addresses": {
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
index 0945ee9836..7692c4fbff 100644
--- a/saleor/plugins/openid_connect/tests/test_utils.py
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -1,16 +1,14 @@
+import datetime
import json
import time
import warnings
-from datetime import datetime, timedelta
from unittest import mock
from unittest.mock import MagicMock, Mock, call, patch
import pytest
-import pytz
import requests
from authlib.jose import JWTClaims
from django.core.exceptions import ValidationError
-from django.utils import timezone
from freezegun import freeze_time
from requests import Response
from requests_hardened import HTTPSession
@@ -460,10 +458,9 @@ def test_get_or_create_user_from_payload_different_email(
@mock.patch("saleor.plugins.openid_connect.utils.cache.set")
@mock.patch("saleor.plugins.openid_connect.utils.cache.get")
def test_get_or_create_user_from_payload_with_last_login(
- mocked_cache_get, mocked_cache_set, customer_user, settings
+ mocked_cache_get, mocked_cache_set, customer_user
):
# given
- settings.TIME_ZONE = "UTC"
current_ts = int(time.time())
oauth_url = "https://saleor.io/oauth"
@@ -471,8 +468,8 @@ def test_get_or_create_user_from_payload_with_last_login(
mocked_cache_get.side_effect = lambda cache_key: None
- customer_user.last_login = timezone.make_aware(
- datetime.fromtimestamp(current_ts - 10), timezone=pytz.timezone("UTC")
+ customer_user.last_login = datetime.datetime.fromtimestamp(
+ current_ts - 10, tz=datetime.UTC
)
customer_user.save()
@@ -490,8 +487,8 @@ def test_get_or_create_user_from_payload_with_last_login(
cache_key, customer_user.id, OIDC_CACHE_TIMEOUT
)
customer_user.refresh_from_db()
- assert customer_user.last_login == timezone.make_aware(
- datetime.fromtimestamp(current_ts), timezone=pytz.timezone("UTC")
+ assert customer_user.last_login == datetime.datetime.fromtimestamp(
+ current_ts, tz=datetime.UTC
)
assert user_from_payload.email == customer_user.email
assert user_from_payload.private_metadata[f"oidc:{oauth_url}"] == sub_id
@@ -565,7 +562,7 @@ def test_get_or_create_user_from_payload_last_login_stays_same(
mocked_cache_get, mocked_cache_set, customer_user
):
# given
- last_login = timezone.now() - timedelta(minutes=14)
+ last_login = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(minutes=14)
customer_user.last_login = last_login
customer_user.save()
oauth_url = "https://saleor.io/oauth"
@@ -590,7 +587,7 @@ def test_get_or_create_user_from_payload_last_login_modifies(
mocked_cache_get, mocked_cache_set, customer_user
):
# given
- last_login = timezone.now() - timedelta(minutes=16)
+ last_login = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(minutes=16)
customer_user.last_login = last_login
customer_user.save()
oauth_url = "https://saleor.io/oauth"
@@ -1073,7 +1070,7 @@ def test_update_user_details_nothing_changed(
customer_user,
):
# given
- last_login = timezone.now() - timedelta(minutes=14)
+ last_login = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(minutes=14)
customer_user.last_login = last_login
customer_user.search_document = "abc"
customer_user.save(update_fields=["search_document", "last_login"])
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 657dbf3ff9..87fc384405 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -1,6 +1,6 @@
+import datetime
import json
import logging
-from datetime import datetime
from typing import TYPE_CHECKING, Optional
import requests
@@ -111,7 +111,7 @@ def get_user_info_from_cache_or_fetch(
cache_time = USER_INFO_DEFAULT_CACHE_TIME
if exp_time:
- now_ts = int(datetime.now().timestamp())
+ now_ts = int(datetime.datetime.now(tz=datetime.UTC).timestamp())
exp_delta = exp_time - now_ts
cache_time = exp_delta if exp_delta > 0 else cache_time
@@ -490,7 +490,7 @@ def _update_user_details(
if last_login:
if not user.last_login or user.last_login.timestamp() < last_login:
- login_time = timezone.make_aware(datetime.fromtimestamp(last_login))
+ login_time = datetime.datetime.fromtimestamp(last_login, tz=datetime.UTC)
user.last_login = login_time
fields_to_save.add("last_login")
else:
diff --git a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
index 280f2455d9..271f1308b8 100644
--- a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
+++ b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
from unittest import mock
@@ -222,7 +222,7 @@ def test_ignore_selected_fields_on_generating_cache_key(
plugin = webhook_plugin()
# when
- checkout_with_item.last_change = timezone.now() + timedelta(seconds=30)
+ checkout_with_item.last_change = timezone.now() + datetime.timedelta(seconds=30)
checkout_with_item.save(update_fields=["last_change"])
new_payload = generate_checkout_payload(checkout_with_item)
new_key_data = get_cache_data_for_shipping_list_methods_for_checkout(new_payload)
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 1d3f3e3aec..f1482c8ff9 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import datetime
from decimal import Decimal
from functools import partial
from unittest import mock
@@ -14,7 +14,6 @@ from celery.exceptions import Retry as CeleryTaskRetryError
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.core.serializers import serialize
-from django.utils import timezone
from freezegun import freeze_time
from kombu.asynchronous.aws.sqs.connection import AsyncSQSConnection
from requests import RequestException
@@ -1670,9 +1669,7 @@ def test_notify_user(
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager(True, lambda: customer_user)
- timestamp = timezone.make_aware(
- datetime.strptime("2020-03-18 12:00", "%Y-%m-%d %H:%M"), timezone.utc
- ).isoformat()
+ timestamp = datetime.datetime(2020, 3, 18, 12, 0, tzinfo=datetime.UTC).isoformat()
redirect_url = "http://redirect.com/"
send_account_confirmation(customer_user, redirect_url, manager, channel_USD.slug)
diff --git a/saleor/product/managers.py b/saleor/product/managers.py
index dc72212923..fbf0d5e5d3 100644
--- a/saleor/product/managers.py
+++ b/saleor/product/managers.py
@@ -1,7 +1,6 @@
import datetime
from typing import Optional, Union
-import pytz
from django.contrib.postgres.aggregates import StringAgg
from django.db import models
from django.db.models import (
@@ -33,7 +32,7 @@ class ProductsQueryset(models.QuerySet):
if not channel.is_active:
return self.none()
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
channel_listings = (
ProductChannelListing.objects.using(self.db)
.filter(
@@ -46,7 +45,7 @@ class ProductsQueryset(models.QuerySet):
return self.filter(Exists(channel_listings.filter(product_id=OuterRef("pk"))))
def not_published(self, channel: Channel):
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
return self.annotate_publication_info(channel).filter(
Q(published_at__gt=today) & Q(is_published=True)
| Q(is_published=False)
@@ -348,7 +347,7 @@ class ProductVariantQueryset(models.QuerySet):
channel_listings__price_amount__isnull=False,
)
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
variants = variants.filter(
Q(product__channel_listings__published_at__lte=today)
| Q(product__channel_listings__published_at__isnull=True),
@@ -378,7 +377,7 @@ ProductVariantChannelListingManager = models.Manager.from_queryset(
class CollectionsQueryset(models.QuerySet):
def published(self, channel_slug: str):
- today = datetime.datetime.now(pytz.UTC)
+ today = datetime.datetime.now(tz=datetime.UTC)
return self.filter(
Q(channel_listings__published_at__lte=today)
| Q(channel_listings__published_at__isnull=True),
diff --git a/saleor/product/migrations/0122_auto_20200828_1135.py b/saleor/product/migrations/0122_auto_20200828_1135.py
index e062f568ca..05b89fd41c 100644
--- a/saleor/product/migrations/0122_auto_20200828_1135.py
+++ b/saleor/product/migrations/0122_auto_20200828_1135.py
@@ -9,7 +9,8 @@ def set_all_published_products_as_searchable_and_available_for_purchase(
):
Product = apps.get_model("product", "Product")
Product.objects.filter(is_published=True).update(
- visible_in_listings=True, available_for_purchase=datetime.datetime.today()
+ visible_in_listings=True,
+ available_for_purchase=datetime.datetime.now(tz=datetime.UTC).date(),
)
diff --git a/saleor/product/migrations/0128_update_publication_date.py b/saleor/product/migrations/0128_update_publication_date.py
index c40e0c6d59..a4b7c4d2c8 100644
--- a/saleor/product/migrations/0128_update_publication_date.py
+++ b/saleor/product/migrations/0128_update_publication_date.py
@@ -1,4 +1,4 @@
-from datetime import date
+import datetime
from django.db import migrations
@@ -8,7 +8,9 @@ def set_missing_product_publication_date(apps, schema_editor):
published_product = Product.objects.filter(
publication_date__isnull=True, is_published=True
)
- published_product.update(publication_date=date.today())
+ published_product.update(
+ publication_date=datetime.datetime.now(tz=datetime.UTC).date()
+ )
def set_missing_collection_publication_date(apps, schema_editor):
@@ -16,7 +18,9 @@ def set_missing_collection_publication_date(apps, schema_editor):
published_collection = Collection.objects.filter(
publication_date__isnull=True, is_published=True
)
- published_collection.update(publication_date=date.today())
+ published_collection.update(
+ publication_date=datetime.datetime.now(tz=datetime.UTC).date()
+ )
class Migration(migrations.Migration):
diff --git a/saleor/product/models.py b/saleor/product/models.py
index f34759ac8f..b6e40fe17d 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -5,7 +5,6 @@ from typing import Optional
from uuid import uuid4
import graphene
-import pytz
from django.conf import settings
from django.contrib.postgres.indexes import BTreeIndex, GinIndex
from django.contrib.postgres.search import SearchVectorField
@@ -342,7 +341,7 @@ class ProductChannelListing(PublishableModel):
def is_available_for_purchase(self):
return (
self.available_for_purchase_at is not None
- and datetime.datetime.now(pytz.UTC) >= self.available_for_purchase_at
+ and datetime.datetime.now(tz=datetime.UTC) >= self.available_for_purchase_at
)
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index 7c4e372a39..759b3722a3 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -1,12 +1,11 @@
+import datetime
import os
from collections import defaultdict
-from datetime import datetime, timezone
from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
-import pytz
from freezegun import freeze_time
from prices import Money
@@ -166,7 +165,7 @@ def test_clean_product_attributes_date_time_range_filter_input(
filter_value = [
(
date_attribute.slug,
- {"gte": datetime(2020, 10, 5, tzinfo=pytz.utc)},
+ {"gte": datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC)},
)
]
values_qs = _clean_product_attributes_date_time_range_filter_input(
@@ -178,7 +177,10 @@ def test_clean_product_attributes_date_time_range_filter_input(
filter_value = [
(
date_attribute.slug,
- {"gte": datetime(2020, 10, 5).date(), "lte": datetime(2020, 11, 4).date()},
+ {
+ "gte": datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC).date(),
+ "lte": datetime.datetime(2020, 11, 4, tzinfo=datetime.UTC).date(),
+ },
)
]
values_qs = _clean_product_attributes_date_time_range_filter_input(
@@ -193,7 +195,7 @@ def test_clean_product_attributes_date_time_range_filter_input(
filter_value = [
(
date_attribute.slug,
- {"lte": datetime(2020, 11, 4, tzinfo=timezone.utc)},
+ {"lte": datetime.datetime(2020, 11, 4, tzinfo=datetime.UTC)},
)
]
values_qs = _clean_product_attributes_date_time_range_filter_input(
@@ -207,7 +209,7 @@ def test_clean_product_attributes_date_time_range_filter_input(
filter_value = [
(
date_attribute.slug,
- {"lte": datetime(2020, 10, 4, tzinfo=timezone.utc)},
+ {"lte": datetime.datetime(2020, 10, 4, tzinfo=datetime.UTC)},
)
]
values_qs = _clean_product_attributes_date_time_range_filter_input(
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index 550bb3dd8a..a81eddef63 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -1,11 +1,10 @@
-from datetime import datetime
+import datetime
from decimal import Decimal
from unittest.mock import patch
import before_after
import graphene
import pytest
-import pytz
from django.core.management import call_command
from prices import Money
@@ -617,7 +616,7 @@ def test_update_discounted_prices_for_promotion_only_dirty_products(
discounted_price_amount=second_channel_discounted_price,
currency=channel_PLN.currency_code,
visible_in_listings=True,
- available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ available_for_purchase_at=(datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)),
discounted_price_dirty=False,
)
diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.py
index 5004c2fd01..4634080e53 100644
--- a/saleor/product/tests/test_tasks.py
+++ b/saleor/product/tests/test_tasks.py
@@ -1,5 +1,5 @@
+import datetime
import logging
-from datetime import timedelta
from decimal import Decimal
from unittest.mock import patch
@@ -31,7 +31,7 @@ def test_update_variant_relations_for_active_promotion_rules_task(
collection,
):
# given
- Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
+ Promotion.objects.update(start_date=timezone.now() - datetime.timedelta(days=1))
PromotionRule.objects.update(variants_dirty=True)
PromotionRuleVariant = PromotionRule.variants.through
PromotionRuleVariant.objects.all().delete()
@@ -73,7 +73,7 @@ def test_update_variant_relations_for_active_promotion_rules_task_when_not_valid
promotion = Promotion.objects.create(
name="Promotion",
type=PromotionType.CATALOGUE,
- end_date=timezone.now() + timedelta(days=30),
+ end_date=timezone.now() + datetime.timedelta(days=30),
)
rule = promotion.rules.create(
name="Percentage promotion rule",
@@ -107,7 +107,7 @@ def test_update_variant_relations_for_active_promotion_rules_task_with_order_pre
order_promotion_rule,
):
# given
- Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
+ Promotion.objects.update(start_date=timezone.now() - datetime.timedelta(days=1))
PromotionRule.objects.update(catalogue_predicate={})
# when
@@ -130,7 +130,7 @@ def test_update_variant_relations_for_active_promotion_rules_with_empty_reward_v
product_list,
):
# given
- Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
+ Promotion.objects.update(start_date=timezone.now() - datetime.timedelta(days=1))
PromotionRuleVariant = PromotionRule.variants.through
PromotionRuleVariant.objects.all().delete()
@@ -267,14 +267,14 @@ def test_get_preorder_variants_to_clean(
preorder_variant_global_and_channel_threshold,
):
preorder_variant_before_end_date = preorder_variant_channel_threshold
- preorder_variant_before_end_date.preorder_end_date = timezone.now() + timedelta(
- days=1
+ preorder_variant_before_end_date.preorder_end_date = (
+ timezone.now() + datetime.timedelta(days=1)
)
preorder_variant_before_end_date.save(update_fields=["preorder_end_date"])
preorder_variant_after_end_date = preorder_variant_global_and_channel_threshold
- preorder_variant_after_end_date.preorder_end_date = timezone.now() - timedelta(
- days=1
+ preorder_variant_after_end_date.preorder_end_date = (
+ timezone.now() - datetime.timedelta(days=1)
)
preorder_variant_after_end_date.save(update_fields=["preorder_end_date"])
diff --git a/saleor/product/tests/test_utils_product.py b/saleor/product/tests/test_utils_product.py
index 6aaf228619..44b683c5c6 100644
--- a/saleor/product/tests/test_utils_product.py
+++ b/saleor/product/tests/test_utils_product.py
@@ -1,8 +1,6 @@
-from datetime import datetime
+import datetime
from unittest.mock import patch
-import pytz
-
from ...discount.models import PromotionRule
from ..models import ProductChannelListing
from ..utils.product import (
@@ -53,7 +51,7 @@ def test_mark_products_in_channels_as_dirty_product_process_only_for_provided_ch
discounted_price_amount=20,
currency=channel_PLN.currency_code,
visible_in_listings=True,
- available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ available_for_purchase_at=(datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)),
discounted_price_dirty=False,
)
product_channel_listing = product.channel_listings.all()
@@ -87,7 +85,7 @@ def test_mark_products_in_channels_as_dirty_with_multiple_products_and_channels(
discounted_price_amount=20,
currency=channel_PLN.currency_code,
visible_in_listings=True,
- available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ available_for_purchase_at=(datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)),
discounted_price_dirty=False,
)
first_product_channel_listing = first_product.channel_listings.all()
@@ -99,7 +97,7 @@ def test_mark_products_in_channels_as_dirty_with_multiple_products_and_channels(
discounted_price_amount=20,
currency=channel_PLN.currency_code,
visible_in_listings=True,
- available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ available_for_purchase_at=(datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)),
discounted_price_dirty=False,
)
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 1c2d42acea..e887c24aa9 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -1,5 +1,7 @@
+import datetime
from collections.abc import Iterable
from typing import TYPE_CHECKING, Union
+from uuid import UUID
from ...core.taxes import TaxedMoney, zero_taxed_money
from ...core.tracing import traced_atomic_transaction
@@ -10,9 +12,6 @@ from ...webhook.utils import get_webhooks_for_event
from ..models import Product, ProductChannelListing
if TYPE_CHECKING:
- from datetime import date, datetime
- from uuid import UUID
-
from django.db.models.query import QuerySet
from ...order.models import Order, OrderLine
@@ -21,9 +20,9 @@ if TYPE_CHECKING:
def calculate_revenue_for_variant(
variant: "ProductVariant",
- start_date: Union["date", "datetime"],
+ start_date: Union[datetime.date, datetime.datetime],
order_lines: Iterable["OrderLine"],
- orders_dict: dict["UUID", "Order"],
+ orders_dict: dict[UUID, "Order"],
currency_code: str,
) -> TaxedMoney:
"""Calculate total revenue generated by a product variant."""
diff --git a/saleor/product/utils/digital_products.py b/saleor/product/utils/digital_products.py
index 913ed1ff0c..5f6d9c6f2a 100644
--- a/saleor/product/utils/digital_products.py
+++ b/saleor/product/utils/digital_products.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from django.contrib.sites.models import Site
from django.utils.timezone import now
@@ -33,7 +33,7 @@ def digital_content_url_is_valid(content_url: DigitalContentUrl) -> bool:
max_downloads = content_url.content.max_downloads
if url_valid_days is not None:
- valid_days = timedelta(days=url_valid_days)
+ valid_days = datetime.timedelta(days=url_valid_days)
valid_until = content_url.created_at + valid_days
if now() > valid_until:
return False
diff --git a/saleor/settings.py b/saleor/settings.py
index 9bb9d94648..4d99192d26 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -1,8 +1,8 @@
+import datetime
import logging
import os
import os.path
import warnings
-from datetime import timedelta
from typing import Optional
from urllib.parse import urlparse
@@ -500,7 +500,9 @@ GS_AUTO_CREATE_BUCKET = get_bool_from_env("GS_AUTO_CREATE_BUCKET", False)
GS_QUERYSTRING_AUTH = get_bool_from_env("GS_QUERYSTRING_AUTH", False)
GS_DEFAULT_ACL = os.environ.get("GS_DEFAULT_ACL", None)
GS_MEDIA_CUSTOM_ENDPOINT = os.environ.get("GS_MEDIA_CUSTOM_ENDPOINT", None)
-GS_EXPIRATION = timedelta(seconds=parse(os.environ.get("GS_EXPIRATION", "1 day")))
+GS_EXPIRATION = datetime.timedelta(
+ seconds=parse(os.environ.get("GS_EXPIRATION", "1 day"))
+)
GS_FILE_OVERWRITE = get_bool_from_env("GS_FILE_OVERWRITE", True)
# If GOOGLE_APPLICATION_CREDENTIALS is set there is no need to load OAuth token
@@ -554,18 +556,18 @@ AUTHENTICATION_BACKENDS = [
]
# Expired checkouts settings - defines after what time checkouts will be deleted
-ANONYMOUS_CHECKOUTS_TIMEDELTA = timedelta(
+ANONYMOUS_CHECKOUTS_TIMEDELTA = datetime.timedelta(
seconds=parse(os.environ.get("ANONYMOUS_CHECKOUTS_TIMEDELTA", "30 days"))
)
-USER_CHECKOUTS_TIMEDELTA = timedelta(
+USER_CHECKOUTS_TIMEDELTA = datetime.timedelta(
seconds=parse(os.environ.get("USER_CHECKOUTS_TIMEDELTA", "90 days"))
)
-EMPTY_CHECKOUTS_TIMEDELTA = timedelta(
+EMPTY_CHECKOUTS_TIMEDELTA = datetime.timedelta(
seconds=parse(os.environ.get("EMPTY_CHECKOUTS_TIMEDELTA", "6 hours"))
)
# Exports settings - defines after what time exported files will be deleted
-EXPORT_FILES_TIMEDELTA = timedelta(
+EXPORT_FILES_TIMEDELTA = datetime.timedelta(
seconds=parse(os.environ.get("EXPORT_FILES_TIMEDELTA", "30 days"))
)
@@ -584,7 +586,7 @@ CELERY_WORKER_PREFETCH_MULTIPLIER = int(
)
# Expire orders task setting
-BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA = timedelta(
+BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA = datetime.timedelta(
seconds=parse(os.environ.get("BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA", "5 minutes"))
)
@@ -609,15 +611,15 @@ BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC = BEAT_PRICE_RECALCULATION_SC
CELERY_BEAT_SCHEDULE = {
"delete-empty-allocations": {
"task": "saleor.warehouse.tasks.delete_empty_allocations_task",
- "schedule": timedelta(days=1),
+ "schedule": datetime.timedelta(days=1),
},
"deactivate-preorder-for-variants": {
"task": "saleor.product.tasks.deactivate_preorder_for_variants_task",
- "schedule": timedelta(hours=1),
+ "schedule": datetime.timedelta(hours=1),
},
"delete-expired-reservations": {
"task": "saleor.warehouse.tasks.delete_expired_reservations_task",
- "schedule": timedelta(days=1),
+ "schedule": datetime.timedelta(days=1),
},
"delete-expired-checkouts": {
"task": "saleor.checkout.tasks.delete_expired_checkouts",
@@ -629,7 +631,7 @@ CELERY_BEAT_SCHEDULE = {
},
"delete-outdated-event-data": {
"task": "saleor.core.tasks.delete_event_payloads_task",
- "schedule": timedelta(days=1),
+ "schedule": datetime.timedelta(days=1),
},
"deactivate-expired-gift-cards": {
"task": "saleor.giftcard.tasks.deactivate_expired_cards_task",
@@ -649,12 +651,12 @@ CELERY_BEAT_SCHEDULE = {
},
"update-products-search-vectors": {
"task": "saleor.product.tasks.update_products_search_vector_task",
- "schedule": timedelta(seconds=BEAT_UPDATE_SEARCH_SEC),
+ "schedule": datetime.timedelta(seconds=BEAT_UPDATE_SEARCH_SEC),
"options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},
},
"update-gift-cards-search-vectors": {
"task": "saleor.giftcard.tasks.update_gift_cards_search_vector_task",
- "schedule": timedelta(seconds=BEAT_UPDATE_SEARCH_SEC),
+ "schedule": datetime.timedelta(seconds=BEAT_UPDATE_SEARCH_SEC),
"options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},
},
"expire-orders": {
@@ -667,19 +669,19 @@ CELERY_BEAT_SCHEDULE = {
},
"release-funds-for-abandoned-checkouts": {
"task": "saleor.payment.tasks.transaction_release_funds_for_checkout_task",
- "schedule": timedelta(minutes=10),
+ "schedule": datetime.timedelta(minutes=10),
},
"recalculate-promotion-rules": {
"task": (
"saleor.product.tasks"
".update_variant_relations_for_active_promotion_rules_task"
),
- "schedule": timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),
+ "schedule": datetime.timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),
"options": {"expires": BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC},
},
"recalculate-discounted-price-for-products": {
"task": "saleor.product.tasks.recalculate_discounted_price_for_products_task",
- "schedule": timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),
+ "schedule": datetime.timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),
"options": {"expires": BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC},
},
}
@@ -689,17 +691,19 @@ CELERY_BEAT_SCHEDULE = {
# is_due() calls
CELERY_BEAT_MAX_LOOP_INTERVAL = 300 # 5 minutes
-EVENT_PAYLOAD_DELETE_PERIOD = timedelta(
+EVENT_PAYLOAD_DELETE_PERIOD = datetime.timedelta(
seconds=parse(os.environ.get("EVENT_PAYLOAD_DELETE_PERIOD", "14 days"))
)
-EVENT_PAYLOAD_DELETE_TASK_TIME_LIMIT = timedelta(
+EVENT_PAYLOAD_DELETE_TASK_TIME_LIMIT = datetime.timedelta(
seconds=parse(os.environ.get("EVENT_PAYLOAD_DELETE_TASK_TIME_LIMIT", "1 hour"))
)
# Time between marking app "to remove" and removing the app from the database.
# App is not visible for the user after removing, but it still exists in the database.
# Saleor needs time to process sending `APP_DELETED` webhook and possible retrying,
# so we need to wait for some time before removing the App from the database.
-DELETE_APP_TTL = timedelta(seconds=parse(os.environ.get("DELETE_APP_TTL", "1 day")))
+DELETE_APP_TTL = datetime.timedelta(
+ seconds=parse(os.environ.get("DELETE_APP_TTL", "1 day"))
+)
# Observability settings
@@ -717,10 +721,10 @@ OBSERVABILITY_BUFFER_SIZE_LIMIT = int(
OBSERVABILITY_BUFFER_BATCH_SIZE = int(
os.environ.get("OBSERVABILITY_BUFFER_BATCH_SIZE", 100)
)
-OBSERVABILITY_REPORT_PERIOD = timedelta(
+OBSERVABILITY_REPORT_PERIOD = datetime.timedelta(
seconds=parse(os.environ.get("OBSERVABILITY_REPORT_PERIOD", "20 seconds"))
)
-OBSERVABILITY_BUFFER_TIMEOUT = timedelta(
+OBSERVABILITY_BUFFER_TIMEOUT = datetime.timedelta(
seconds=parse(os.environ.get("OBSERVABILITY_BUFFER_TIMEOUT", "5 minutes"))
)
if OBSERVABILITY_ACTIVE:
@@ -862,22 +866,26 @@ CACHES = {"default": django_cache_url.config()}
CACHES["default"]["TIMEOUT"] = parse(os.environ.get("CACHE_TIMEOUT", "7 days"))
JWT_EXPIRE = True
-JWT_TTL_ACCESS = timedelta(seconds=parse(os.environ.get("JWT_TTL_ACCESS", "5 minutes")))
-JWT_TTL_APP_ACCESS = timedelta(
+JWT_TTL_ACCESS = datetime.timedelta(
+ seconds=parse(os.environ.get("JWT_TTL_ACCESS", "5 minutes"))
+)
+JWT_TTL_APP_ACCESS = datetime.timedelta(
seconds=parse(os.environ.get("JWT_TTL_APP_ACCESS", "5 minutes"))
)
-JWT_TTL_REFRESH = timedelta(seconds=parse(os.environ.get("JWT_TTL_REFRESH", "30 days")))
+JWT_TTL_REFRESH = datetime.timedelta(
+ seconds=parse(os.environ.get("JWT_TTL_REFRESH", "30 days"))
+)
-JWT_TTL_REQUEST_EMAIL_CHANGE = timedelta(
+JWT_TTL_REQUEST_EMAIL_CHANGE = datetime.timedelta(
seconds=parse(os.environ.get("JWT_TTL_REQUEST_EMAIL_CHANGE", "1 hour")),
)
-CHECKOUT_PRICES_TTL = timedelta(
+CHECKOUT_PRICES_TTL = datetime.timedelta(
seconds=parse(os.environ.get("CHECKOUT_PRICES_TTL", "1 hour"))
)
-CHECKOUT_TTL_BEFORE_RELEASING_FUNDS = timedelta(
+CHECKOUT_TTL_BEFORE_RELEASING_FUNDS = datetime.timedelta(
seconds=parse(os.environ.get("CHECKOUT_TTL_BEFORE_RELEASING_FUNDS", "6 hours"))
)
CHECKOUT_BATCH_FOR_RELEASING_FUNDS = os.environ.get(
diff --git a/saleor/shipping/tests/test_tasks.py b/saleor/shipping/tests/test_tasks.py
index 6bd944b201..e3d16684cd 100644
--- a/saleor/shipping/tests/test_tasks.py
+++ b/saleor/shipping/tests/test_tasks.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from django.utils import timezone
from freezegun import freeze_time
@@ -20,7 +20,7 @@ def test_drop_invalid_shipping_method_relations(
channel_PLN,
):
# given
- valid_time = timezone.now() + timedelta(hours=24)
+ valid_time = timezone.now() + datetime.timedelta(hours=24)
checkout_PLN = checkouts_list[0]
checkout_PLN.shipping_method = shipping_method
diff --git a/saleor/site/migrations/0018_sitesettings_homepage_collection.py b/saleor/site/migrations/0018_sitesettings_homepage_collection.py
index 1f4044e569..b769133868 100644
--- a/saleor/site/migrations/0018_sitesettings_homepage_collection.py
+++ b/saleor/site/migrations/0018_sitesettings_homepage_collection.py
@@ -13,7 +13,7 @@ def copy_featured_products_to_homepade_collection(apps, schema_editor):
Collection = apps.get_model("product", "Collection")
Product = apps.get_model("product", "Product")
- today = datetime.date.today()
+ today = datetime.datetime.now(tz=datetime.UTC).date()
homepage_products = list(
Product.objects.filter(
Q(available_on__lte=today) | Q(available_on__isnull=True),
diff --git a/saleor/tests/e2e/account/test_login_throttling.py b/saleor/tests/e2e/account/test_login_throttling.py
index b7b69c2acc..e1b6a7d313 100644
--- a/saleor/tests/e2e/account/test_login_throttling.py
+++ b/saleor/tests/e2e/account/test_login_throttling.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
import graphene
@@ -95,7 +95,7 @@ def test_customer_should_not_be_able_to_perform_credential_guessing_attacks_core
attempt_ip_counter = 1
attempt_ip_user_counter = 1
delay = get_delay_time(attempt_ip_counter, attempt_ip_user_counter)
- next_attempt = now + timedelta(seconds=delay)
+ next_attempt = now + datetime.timedelta(seconds=delay)
assert mocked_cache.get(block_key) == next_attempt
assert mocked_cache.get(ip_key) == attempt_ip_counter
@@ -128,7 +128,7 @@ def test_customer_should_not_be_able_to_perform_credential_guessing_attacks_core
attempt_ip_user_counter += 1
new_delay = get_delay_time(attempt_ip_counter, attempt_ip_user_counter)
assert new_delay != delay
- next_attempt = now + timedelta(seconds=new_delay)
+ next_attempt = now + datetime.timedelta(seconds=new_delay)
assert mocked_cache.get(block_key) == next_attempt
assert mocked_cache.get(ip_key) == attempt_ip_counter
diff --git a/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py b/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
index 1499d2c169..e70a77538b 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -38,8 +38,8 @@ def test_order_promotion_not_applied_when_not_within_time_range_CORE_2110(
discount_type = "FIXED"
promotion_rule_name = "rule for product"
today = timezone.now()
- tomorrow = today + timedelta(days=1)
- month_after = today + timedelta(days=30)
+ tomorrow = today + datetime.timedelta(days=1)
+ month_after = today + datetime.timedelta(days=30)
shop_data = prepare_default_shop(e2e_staff_api_client)
channel_id = shop_data["channel"]["id"]
diff --git a/saleor/tests/e2e/pages/test_create_page_with_all_attributes_types.py b/saleor/tests/e2e/pages/test_create_page_with_all_attributes_types.py
index e2a27b33d0..376def4789 100644
--- a/saleor/tests/e2e/pages/test_create_page_with_all_attributes_types.py
+++ b/saleor/tests/e2e/pages/test_create_page_with_all_attributes_types.py
@@ -2,7 +2,6 @@ import datetime
import json
import pytest
-import pytz
from django.conf import settings
from ....tests.utils import dummy_editorjs
@@ -97,7 +96,7 @@ def test_create_page_with_each_of_attribute_types_core_0701(
{"id": attr_date_id, "date": "2021-01-01"},
{
"id": attr_date_time_id,
- "dateTime": datetime.datetime(2023, 1, 1, tzinfo=pytz.utc),
+ "dateTime": datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC),
},
{"id": attr_plain_text_id, "plainText": "test plain text"},
{"id": attr_rich_text_id, "richText": expected_rich_text},
diff --git a/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py b/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py
index ae2aa0f15f..aa086d7bdc 100644
--- a/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py
+++ b/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py
@@ -2,7 +2,6 @@ import datetime
import json
import pytest
-import pytz
from django.conf import settings
from ....tests.utils import dummy_editorjs
@@ -93,7 +92,7 @@ def test_create_product_with_attributes_created_in_bulk_core_0704(
{"id": attr_date_id, "date": "2021-01-01"},
{
"id": attr_date_time_id,
- "dateTime": datetime.datetime(2023, 1, 1, tzinfo=pytz.utc),
+ "dateTime": datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC),
},
{"id": attr_plain_text_id, "plainText": "test plain text"},
{"id": attr_rich_text_id, "richText": expected_rich_text},
diff --git a/saleor/tests/e2e/product/utils/product_channel_listing.py b/saleor/tests/e2e/product/utils/product_channel_listing.py
index ee50c459ad..549fe90a1b 100644
--- a/saleor/tests/e2e/product/utils/product_channel_listing.py
+++ b/saleor/tests/e2e/product/utils/product_channel_listing.py
@@ -1,7 +1,5 @@
import datetime
-import pytz
-
from ...utils import get_graphql_content
PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION = """
@@ -78,7 +76,7 @@ def create_product_channel_listing(
publication_date=datetime.date(2007, 1, 1),
is_published=True,
visible_in_listings=True,
- available_for_purchase_datetime=datetime.datetime(2007, 1, 1, tzinfo=pytz.utc),
+ available_for_purchase_datetime=datetime.datetime(2007, 1, 1, tzinfo=datetime.UTC),
is_available_for_purchase=True,
):
response = raw_create_product_channel_listing(
diff --git a/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py b/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py
index 2255353bbc..f4847c31da 100644
--- a/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py
+++ b/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+import datetime
import pytest
from freezegun import freeze_time
@@ -64,8 +64,10 @@ def test_step_2_query_promotions_first_10_created_at_CORE_2118(
prev_promotion = promotions_list[i - 1]["node"]
current_promotion = promotions_list[i]["node"]
- prev_promo_created_at = datetime.fromisoformat(prev_promotion["createdAt"])
- current_promo_created_at = datetime.fromisoformat(
+ prev_promo_created_at = datetime.datetime.fromisoformat(
+ prev_promotion["createdAt"]
+ )
+ current_promo_created_at = datetime.datetime.fromisoformat(
current_promotion["createdAt"]
)
assert current_promotion["id"] != promotion_dnm["id"]
@@ -88,13 +90,13 @@ def test_step_3_query_promotions_first_10_start_date_before_CORE_2118(
e2e_staff_api_client, "Promotion does not match", promotion_type
)
- base_date = datetime(2023, 1, 1, 14, 1, 34, 61119)
+ base_date = datetime.datetime(2023, 1, 1, 14, 1, 34, 61119, tzinfo=datetime.UTC)
with freeze_time(base_date):
e2e_staff_api_client.regenerate_access_token()
for i in range(10):
promotion_name = f"Promotion start date before {i + 1}"
- start_date = (base_date - timedelta(days=i + 1)).isoformat() + "+00:00"
+ start_date = (base_date - datetime.timedelta(days=i + 1)).isoformat()
promotion = create_promotion(
e2e_staff_api_client,
promotion_name,
@@ -120,8 +122,10 @@ def test_step_3_query_promotions_first_10_start_date_before_CORE_2118(
prev_promotion = promotions_list[i - 1]["node"]
current_promotion = promotions_list[i]["node"]
- prev_promo_start_date = datetime.fromisoformat(prev_promotion["startDate"])
- current_promo_start_date = datetime.fromisoformat(
+ prev_promo_start_date = datetime.datetime.fromisoformat(
+ prev_promotion["startDate"]
+ )
+ current_promo_start_date = datetime.datetime.fromisoformat(
current_promotion["startDate"]
)
assert prev_promo_start_date >= current_promo_start_date
@@ -345,7 +349,7 @@ def test_step_10_promotions_with_end_date_after_CORE_2118(
e2e_staff_api_client,
[permission_manage_discounts],
)
- base_date = datetime(2023, 1, 1, 14, 1, 34, 61119)
+ base_date = datetime.datetime(2023, 1, 1, 14, 1, 34, 61119, tzinfo=datetime.UTC)
now = base_date.isoformat()
promotion_type = "CATALOGUE"
@@ -354,8 +358,8 @@ def test_step_10_promotions_with_end_date_after_CORE_2118(
for i in range(10):
promotion_name = f"Promotion end date after {i + 1}"
end_date = (
- datetime.fromisoformat("2023-10-08T10:19:50.812975+00:00")
- + timedelta(days=i + 1)
+ datetime.datetime.fromisoformat("2023-10-08T10:19:50.812975+00:00")
+ + datetime.timedelta(days=i + 1)
).isoformat()
promotion = create_promotion(
e2e_staff_api_client,
@@ -396,8 +400,10 @@ def test_step_10_promotions_with_end_date_after_CORE_2118(
for i in range(1, len(promotions_list)):
prev_promotion = promotions_list[i - 1]["node"]
current_promotion = promotions_list[i]["node"]
- prev_promo_end_date = datetime.fromisoformat(prev_promotion["endDate"])
- current_promo_end_date = datetime.fromisoformat(current_promotion["endDate"])
+ prev_promo_end_date = datetime.datetime.fromisoformat(prev_promotion["endDate"])
+ current_promo_end_date = datetime.datetime.fromisoformat(
+ current_promotion["endDate"]
+ )
assert prev_promo_end_date > current_promo_end_date
assert current_promotion["id"] != promotion_dnm["id"]
@@ -420,12 +426,12 @@ def test_step_11_promotions_with_no_date_CORE_2118(
)
assert promotion["endDate"] is None
- base_date = datetime(2023, 1, 1, 14, 1, 34, 61119)
+ base_date = datetime.datetime(2023, 1, 1, 14, 1, 34, 61119, tzinfo=datetime.UTC)
now = base_date.isoformat()
with freeze_time(now):
e2e_staff_api_client.regenerate_access_token()
- end_date = datetime.fromisoformat(
+ end_date = datetime.datetime.fromisoformat(
"2023-10-08T10:19:50.812975+00:00"
).isoformat()
promotion_dnm = create_promotion(
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 572f688df5..4be4601c63 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -4,7 +4,6 @@ import random
import uuid
from collections import namedtuple
from contextlib import contextmanager
-from datetime import timedelta
from decimal import Decimal
from functools import partial
from io import BytesIO
@@ -13,7 +12,6 @@ from unittest.mock import MagicMock
import graphene
import pytest
-import pytz
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.files import File
@@ -1132,7 +1130,7 @@ def checkout_with_problems(
second_line = checkout_with_items.lines.last()
- available_at = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=5)
+ available_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(days=5)
product = second_line.variant.product
product.channel_listings.update(
available_for_purchase_at=available_at, is_published=False
@@ -2094,8 +2092,8 @@ def date_attribute(db):
date_time=value,
)
for value in [
- datetime.datetime(2020, 10, 5, tzinfo=pytz.utc),
- datetime.datetime(2020, 11, 5, tzinfo=pytz.utc),
+ datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC),
+ datetime.datetime(2020, 11, 5, tzinfo=datetime.UTC),
]
]
)
@@ -2124,8 +2122,8 @@ def date_time_attribute(db):
date_time=value,
)
for value in [
- datetime.datetime(2020, 10, 5, tzinfo=pytz.utc),
- datetime.datetime(2020, 11, 5, tzinfo=pytz.utc),
+ datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC),
+ datetime.datetime(2020, 11, 5, tzinfo=datetime.UTC),
]
]
)
@@ -2723,7 +2721,7 @@ def categories_tree_with_published_products(
ProductChannelListing(
product=product,
channel=channel_USD,
- published_at=datetime.datetime.now(pytz.UTC),
+ published_at=datetime.datetime.now(tz=datetime.UTC),
is_published=True,
)
)
@@ -2731,7 +2729,7 @@ def categories_tree_with_published_products(
ProductChannelListing(
product=product,
channel=channel_PLN,
- published_at=datetime.datetime.now(pytz.UTC),
+ published_at=datetime.datetime.now(tz=datetime.UTC),
is_published=True,
)
)
@@ -2907,7 +2905,7 @@ def product(product_type, category, warehouse, channel_USD, default_tax_class):
discounted_price_amount="10.00",
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
associate_attribute_values_to_instance(
@@ -2962,7 +2960,7 @@ def shippable_gift_card_product(
discounted_price_amount="100.00",
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(
@@ -3000,7 +2998,7 @@ def product_price_0(category, warehouse, channel_USD):
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(product=product, sku="SKU_C")
ProductVariantChannelListing.objects.create(
@@ -3024,7 +3022,7 @@ def product_in_channel_JPY(product, channel_JPY, warehouse_JPY):
discounted_price_amount="1200",
currency=channel_JPY.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = product.variants.get()
ProductVariantChannelListing.objects.create(
@@ -3058,7 +3056,7 @@ def non_shippable_gift_card_product(
discounted_price_amount="200.00",
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(
@@ -3097,7 +3095,7 @@ def product_with_rich_text_attribute(
discounted_price_amount="10.00",
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
associate_attribute_values_to_instance(
@@ -3164,7 +3162,7 @@ def product_with_single_variant(product_type, category, warehouse, channel_USD):
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(product=product, sku="SKU_SINGLE_VARIANT")
ProductVariantChannelListing.objects.create(
@@ -3193,7 +3191,7 @@ def product_with_two_variants(product_type, category, warehouse, channel_USD):
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variants = [
@@ -3260,7 +3258,7 @@ def product_with_variant_with_two_attributes(
is_published=True,
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(product=product, sku="prodVar1")
@@ -3322,7 +3320,7 @@ def product_with_variant_with_external_media(
is_published=True,
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(product=product, sku="prodVar1")
@@ -3371,7 +3369,7 @@ def product_with_variant_with_file_attribute(
is_published=True,
currency=channel_USD.currency_code,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(
@@ -3434,7 +3432,7 @@ def product_with_default_variant(
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(
product=product, sku="1234", track_inventory=True
@@ -3472,7 +3470,7 @@ def variant_without_inventory_tracking(
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime.now(pytz.UTC),
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC),
)
variant = ProductVariant.objects.create(
product=product,
@@ -3781,7 +3779,7 @@ def product_without_shipping(category, warehouse, channel_USD):
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
variant = ProductVariant.objects.create(product=product, sku="SKU_E")
ProductVariantChannelListing.objects.create(
@@ -3851,7 +3849,7 @@ def product_list(
currency=channel_USD.currency_code,
visible_in_listings=True,
available_for_purchase_at=(
- datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC)
+ datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)
),
),
ProductChannelListing(
@@ -3862,7 +3860,7 @@ def product_list(
currency=channel_USD.currency_code,
visible_in_listings=True,
available_for_purchase_at=(
- datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC)
+ datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)
),
),
ProductChannelListing(
@@ -3873,7 +3871,7 @@ def product_list(
currency=channel_USD.currency_code,
visible_in_listings=True,
available_for_purchase_at=(
- datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC)
+ datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC)
),
),
]
@@ -4697,7 +4695,7 @@ def checkout_line_with_reservation_in_many_stocks(
quantity=3,
)
- reserved_until = timezone.now() + timedelta(minutes=5)
+ reserved_until = timezone.now() + datetime.timedelta(minutes=5)
Reservation.objects.bulk_create(
[
@@ -4730,7 +4728,7 @@ def checkout_line_with_one_reservation(
quantity=2,
)
- reserved_until = timezone.now() + timedelta(minutes=5)
+ reserved_until = timezone.now() + datetime.timedelta(minutes=5)
Reservation.objects.create(
checkout_line=checkout_line,
@@ -4763,7 +4761,7 @@ def checkout_line_with_reserved_preorder_item(
add_variant_to_checkout(checkout_info, preorder_variant_channel_threshold, 2)
checkout_line = checkout.lines.last()
- reserved_until = timezone.now() + timedelta(minutes=5)
+ reserved_until = timezone.now() + datetime.timedelta(minutes=5)
PreorderReservation.objects.create(
checkout_line=checkout_line,
@@ -4815,7 +4813,8 @@ def gift_card_expiry_date(customer_user):
created_by_email=customer_user.email,
initial_balance=Money(20, "USD"),
current_balance=Money(20, "USD"),
- expiry_date=datetime.date.today() + datetime.timedelta(days=100),
+ expiry_date=datetime.datetime.now(tz=datetime.UTC).date()
+ + datetime.timedelta(days=100),
)
tag = GiftCardTag.objects.create(name="another-tag")
gift_card.tags.add(tag)
@@ -4987,7 +4986,7 @@ def order_with_lines(
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime.now(pytz.UTC),
+ available_for_purchase_at=datetime.datetime.now(tz=datetime.UTC),
)
variant = ProductVariant.objects.create(product=product, sku="SKU_AA")
channel_listing = ProductVariantChannelListing.objects.create(
@@ -5637,7 +5636,7 @@ def fulfilled_order(order_with_lines):
order.invoices.create(
url="http://www.example.com/invoice.pdf",
number="01/12/2020/TEST",
- created_at=datetime.datetime.now(tz=pytz.utc),
+ created_at=datetime.datetime.now(tz=datetime.UTC),
status=JobStatus.SUCCESS,
)
fulfillment = order.fulfillments.create(tracking_number="123")
@@ -6009,7 +6008,7 @@ def catalogue_promotion(channel_USD, product, collection):
name="Promotion",
type=PromotionType.CATALOGUE,
description=dummy_editorjs("Test description."),
- end_date=timezone.now() + timedelta(days=30),
+ end_date=timezone.now() + datetime.timedelta(days=30),
)
rules = PromotionRule.objects.bulk_create(
[
@@ -6054,7 +6053,7 @@ def catalogue_promotion_without_rules(db):
promotion = Promotion.objects.create(
name="Promotion",
description=dummy_editorjs("Test description."),
- end_date=timezone.now() + timedelta(days=30),
+ end_date=timezone.now() + datetime.timedelta(days=30),
type=PromotionType.CATALOGUE,
)
return promotion
@@ -6065,7 +6064,7 @@ def order_promotion_without_rules(db):
promotion = Promotion.objects.create(
name="Promotion",
description=dummy_editorjs("Test description."),
- end_date=timezone.now() + timedelta(days=30),
+ end_date=timezone.now() + datetime.timedelta(days=30),
type=PromotionType.ORDER,
)
return promotion
@@ -6115,22 +6114,22 @@ def promotion_list(channel_USD, product, collection):
name="Promotion 1",
type=PromotionType.CATALOGUE,
description=dummy_editorjs("Promotion 1 description."),
- start_date=timezone.now() + timedelta(days=1),
- end_date=timezone.now() + timedelta(days=10),
+ start_date=timezone.now() + datetime.timedelta(days=1),
+ end_date=timezone.now() + datetime.timedelta(days=10),
),
Promotion(
name="Promotion 2",
type=PromotionType.CATALOGUE,
description=dummy_editorjs("Promotion 2 description."),
- start_date=timezone.now() + timedelta(days=5),
- end_date=timezone.now() + timedelta(days=20),
+ start_date=timezone.now() + datetime.timedelta(days=5),
+ end_date=timezone.now() + datetime.timedelta(days=20),
),
Promotion(
name="Promotion 3",
type=PromotionType.CATALOGUE,
description=dummy_editorjs("TePromotion 3 description."),
- start_date=timezone.now() + timedelta(days=15),
- end_date=timezone.now() + timedelta(days=30),
+ start_date=timezone.now() + datetime.timedelta(days=15),
+ end_date=timezone.now() + datetime.timedelta(days=30),
),
]
)
@@ -6660,9 +6659,7 @@ def published_collections(db, channel_USD):
channel=channel_USD,
collection=collection,
is_published=True,
- published_at=datetime.datetime(
- 2019, 4, 10, tzinfo=timezone.get_current_timezone()
- ),
+ published_at=datetime.datetime(2019, 4, 10, tzinfo=datetime.UTC),
)
for collection in collections
]
@@ -7316,7 +7313,7 @@ def digital_content(category, media_root, warehouse, channel_USD) -> DigitalCont
channel=channel_USD,
is_published=True,
visible_in_listings=True,
- available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=pytz.UTC),
+ available_for_purchase_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.UTC),
)
product_variant = ProductVariant.objects.create(product=product, sku="SKU_554")
ProductVariantChannelListing.objects.create(
@@ -8518,12 +8515,8 @@ def export_file_list(staff_user):
)
)
- updated_date = datetime.datetime(
- 2019, 4, 18, tzinfo=timezone.get_current_timezone()
- )
- created_date = datetime.datetime(
- 2019, 4, 10, tzinfo=timezone.get_current_timezone()
- )
+ updated_date = datetime.datetime(2019, 4, 18, tzinfo=datetime.UTC)
+ created_date = datetime.datetime(2019, 4, 10, tzinfo=datetime.UTC)
new_created_and_updated_dates = [
(created_date, updated_date),
(created_date, updated_date + datetime.timedelta(hours=2)),
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index 4ef7a013e1..f539cf7fc8 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -34,10 +34,6 @@ SECRET_KEY = "NOTREALLY"
ALLOWED_CLIENT_HOSTS = ["www.example.com"]
-TIME_ZONE = "America/Chicago"
-LANGUAGE_CODE = "en"
-
-
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
COUNTRIES_ONLY = None
diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.py
index 052cfc456e..8937f86b5d 100644
--- a/saleor/warehouse/reservations.py
+++ b/saleor/warehouse/reservations.py
@@ -1,6 +1,6 @@
+import datetime
from collections import defaultdict, namedtuple
from collections.abc import Iterable
-from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Optional
from django.conf import settings
@@ -47,7 +47,7 @@ def reserve_stocks_and_preorders(
else:
stock_lines.append(line)
- reserved_until = timezone.now() + timedelta(minutes=length_in_minutes)
+ reserved_until = timezone.now() + datetime.timedelta(minutes=length_in_minutes)
if stock_lines:
reserve_stocks(
@@ -87,7 +87,7 @@ def reserve_stocks(
variants: Iterable["ProductVariant"],
country_code: str,
channel: "Channel",
- reserved_until: datetime,
+ reserved_until: datetime.datetime,
*,
replace: bool = True,
):
@@ -183,7 +183,7 @@ def _create_stock_reservations(
quantity_allocation_for_stocks: dict,
quantity_reservation_for_stocks: dict,
insufficient_stocks: list[InsufficientStockData],
- reserved_until: datetime,
+ reserved_until: datetime.datetime,
) -> tuple[list[InsufficientStockData], list[Reservation]]:
quantity = line.quantity
quantity_reserved = 0
@@ -237,7 +237,7 @@ def reserve_preorders(
variants: Iterable["ProductVariant"],
country_code: str,
channel_slug: str,
- reserved_until: datetime,
+ reserved_until: datetime.datetime,
*,
replace: bool = True,
):
@@ -324,7 +324,7 @@ def _create_preorder_reservation(
global_allocations: int,
listings_reservations: dict[int, int],
insufficient_stocks: list[InsufficientStockData],
- reserved_until: datetime,
+ reserved_until: datetime.datetime,
):
if listing.preorder_quantity_threshold is not None:
available_channel_quantity = listing.available_preorder_quantity # type: ignore
diff --git a/saleor/warehouse/tests/test_preorder_availability.py b/saleor/warehouse/tests/test_preorder_availability.py
index ada54d60fd..d11906d215 100644
--- a/saleor/warehouse/tests/test_preorder_availability.py
+++ b/saleor/warehouse/tests/test_preorder_availability.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest.mock import patch
import pytest
@@ -56,7 +56,7 @@ def test_check_stock_and_preorder_quantity_bulk(
global_quantity_limit = 50
with freeze_time(
- preorder_variant_with_end_date.preorder_end_date + timedelta(days=3)
+ preorder_variant_with_end_date.preorder_end_date + datetime.timedelta(days=3)
):
check_stock_and_preorder_quantity_bulk(
[
@@ -174,7 +174,7 @@ def test_check_preorder_reserved_threshold_bulk_channel_threshold(
# Check excludes expired reservations
PreorderReservation.objects.update(
- reserved_until=timezone.now() - timedelta(minutes=1)
+ reserved_until=timezone.now() - datetime.timedelta(minutes=1)
)
check_preorder_threshold_bulk(
@@ -246,7 +246,7 @@ def test_check_preorder_reserved_threshold_bulk_global_threshold(
# Check excludes expired reservations
PreorderReservation.objects.update(
- reserved_until=timezone.now() - timedelta(minutes=1)
+ reserved_until=timezone.now() - datetime.timedelta(minutes=1)
)
check_preorder_threshold_bulk(
diff --git a/saleor/warehouse/tests/test_preorder_reservations_management.py b/saleor/warehouse/tests/test_preorder_reservations_management.py
index cd6e49abfb..238396b180 100644
--- a/saleor/warehouse/tests/test_preorder_reservations_management.py
+++ b/saleor/warehouse/tests/test_preorder_reservations_management.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from decimal import Decimal
import pytest
@@ -24,12 +24,12 @@ def test_reserve_preorders(checkout_line_with_preorder_item, channel_USD):
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
reservation = PreorderReservation.objects.get(checkout_line=checkout_line)
assert reservation.quantity_reserved == 5
- assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+ assert reservation.reserved_until > timezone.now() + datetime.timedelta(minutes=1)
def test_preorder_reservation_skips_prev_reservation_delete_if_replace_is_disabled(
@@ -43,7 +43,7 @@ def test_preorder_reservation_skips_prev_reservation_delete_if_replace_is_disabl
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
replace=False,
)
@@ -53,7 +53,7 @@ def test_preorder_reservation_skips_prev_reservation_delete_if_replace_is_disabl
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -68,7 +68,7 @@ def test_preorder_reservation_removes_previous_reservations_for_checkout(
checkout_line=checkout_line,
product_variant_channel_listing=checkout_line.variant.channel_listings.first(),
quantity_reserved=5,
- reserved_until=timezone.now() + timedelta(hours=1),
+ reserved_until=timezone.now() + datetime.timedelta(hours=1),
)
reserve_preorders(
@@ -76,7 +76,7 @@ def test_preorder_reservation_removes_previous_reservations_for_checkout(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
with pytest.raises(PreorderReservation.DoesNotExist):
@@ -100,7 +100,7 @@ def test_preorder_reservation_fails_if_there_is_not_enough_channel_threshold_ava
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -132,7 +132,7 @@ def test_preorder_reservation_fails_if_channel_threshold_was_allocated(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -160,7 +160,7 @@ def test_preorder_reservation_fails_if_channel_threshold_was_reserved(
checkout_line=other_checkout_line,
product_variant_channel_listing=product_variant_channel_listing,
quantity_reserved=other_checkout_line.quantity,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
with pytest.raises(InsufficientStock):
@@ -169,7 +169,7 @@ def test_preorder_reservation_fails_if_channel_threshold_was_reserved(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -209,7 +209,7 @@ def test_preorder_reservation_fails_if_global_threshold_was_allocated(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -246,7 +246,7 @@ def test_preorder_reservation_fails_if_global_threshold_was_reserved(
checkout_line=other_checkout_line,
product_variant_channel_listing=product_variant_channel_listing,
quantity_reserved=other_checkout_line.quantity,
- reserved_until=timezone.now() + timedelta(minutes=5),
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
)
with pytest.raises(InsufficientStock):
@@ -255,7 +255,7 @@ def test_preorder_reservation_fails_if_global_threshold_was_reserved(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -275,5 +275,5 @@ def test_preorder_reservation_fails_if_there_is_not_enough_global_threshold_avai
[checkout_line.variant],
COUNTRY_CODE,
channel_USD.slug,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
diff --git a/saleor/warehouse/tests/test_stock_reservations_management.py b/saleor/warehouse/tests/test_stock_reservations_management.py
index 4e62221801..497613aaba 100644
--- a/saleor/warehouse/tests/test_stock_reservations_management.py
+++ b/saleor/warehouse/tests/test_stock_reservations_management.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -26,14 +26,14 @@ def test_reserve_stocks(checkout_line, channel_USD):
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
stock.refresh_from_db()
assert stock.quantity == 10
reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)
assert reservation.quantity_reserved == 5
- assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+ assert reservation.reserved_until > timezone.now() + datetime.timedelta(minutes=1)
def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled(
@@ -45,7 +45,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
replace=False,
)
@@ -55,7 +55,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -88,7 +88,7 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_highest_stock_st
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
stock.refresh_from_db()
@@ -96,13 +96,15 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_highest_stock_st
reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)
assert reservation.quantity_reserved == 3
- assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+ assert reservation.reserved_until > timezone.now() + datetime.timedelta(minutes=1)
second_reservation = Reservation.objects.get(
checkout_line=checkout_line, stock=secondary_stock
)
assert second_reservation.quantity_reserved == 2
- assert second_reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+ assert second_reservation.reserved_until > timezone.now() + datetime.timedelta(
+ minutes=1
+ )
def test_multiple_stocks_reserved_if_single_stock_is_not_enough_sorting_order_strategy(
@@ -155,7 +157,7 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_sorting_order_st
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
# then
@@ -166,11 +168,13 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_sorting_order_st
checkout_line=checkout_line, stock=secondary_stock
)
assert second_reservation.quantity_reserved == secondary_stock_quantity
- assert second_reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+ assert second_reservation.reserved_until > timezone.now() + datetime.timedelta(
+ minutes=1
+ )
reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)
assert reservation.quantity_reserved == quantity - secondary_stock_quantity
- assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+ assert reservation.reserved_until > timezone.now() + datetime.timedelta(minutes=1)
def test_stocks_reservation_removes_previous_reservations_for_checkout(
@@ -187,7 +191,7 @@ def test_stocks_reservation_removes_previous_reservations_for_checkout(
checkout_line=checkout_line,
stock=stock,
quantity_reserved=5,
- reserved_until=timezone.now() + timedelta(hours=1),
+ reserved_until=timezone.now() + datetime.timedelta(hours=1),
)
reserve_stocks(
@@ -195,7 +199,7 @@ def test_stocks_reservation_removes_previous_reservations_for_checkout(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
with pytest.raises(Reservation.DoesNotExist):
@@ -218,7 +222,7 @@ def test_stock_reservation_fails_if_there_is_not_enough_stock_available(
[checkout_line.variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -255,7 +259,7 @@ def test_stock_reservation_accounts_for_order_allocations(
[variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
@@ -278,7 +282,7 @@ def test_stock_reservation_accounts_for_order_allocations_and_reservations(
checkout_line=other_checkout_line,
stock=variant.stocks.order_by("pk").last(),
quantity_reserved=2,
- reserved_until=timezone.now() + timedelta(hours=1),
+ reserved_until=timezone.now() + datetime.timedelta(hours=1),
)
checkout_line = checkout.lines.create(
@@ -292,5 +296,5 @@ def test_stock_reservation_accounts_for_order_allocations_and_reservations(
[variant],
COUNTRY_CODE,
channel_USD,
- timezone.now() + timedelta(minutes=RESERVATION_LENGTH),
+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
)
diff --git a/saleor/warehouse/tests/test_tasks.py b/saleor/warehouse/tests/test_tasks.py
index 0e22b9a91d..ed4b4af59f 100644
--- a/saleor/warehouse/tests/test_tasks.py
+++ b/saleor/warehouse/tests/test_tasks.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -13,7 +13,9 @@ from ..tasks import (
def test_delete_expired_reservations_task_deletes_expired_stock_reservations(
checkout_line_with_reservation_in_many_stocks,
):
- Reservation.objects.update(reserved_until=timezone.now() - timedelta(seconds=1))
+ Reservation.objects.update(
+ reserved_until=timezone.now() - datetime.timedelta(seconds=1)
+ )
delete_expired_reservations_task()
assert not Reservation.objects.exists()
@@ -22,7 +24,9 @@ def test_delete_expired_reservations_task_skips_active_stock_reservations(
checkout_line_with_reservation_in_many_stocks,
):
reservations_count = Reservation.objects.count()
- Reservation.objects.update(reserved_until=timezone.now() + timedelta(seconds=1))
+ Reservation.objects.update(
+ reserved_until=timezone.now() + datetime.timedelta(seconds=1)
+ )
delete_expired_reservations_task()
assert Reservation.objects.count() == reservations_count
@@ -31,7 +35,7 @@ def test_delete_expired_reservations_task_deletes_expired_preorder_reservations(
checkout_line_with_reserved_preorder_item,
):
PreorderReservation.objects.update(
- reserved_until=timezone.now() - timedelta(seconds=1)
+ reserved_until=timezone.now() - datetime.timedelta(seconds=1)
)
delete_expired_reservations_task()
assert not PreorderReservation.objects.exists()
@@ -42,7 +46,7 @@ def test_delete_expired_reservations_task_skips_active_preorder_reservations(
):
reservations_count = PreorderReservation.objects.count()
PreorderReservation.objects.update(
- reserved_until=timezone.now() + timedelta(seconds=1)
+ reserved_until=timezone.now() + datetime.timedelta(seconds=1)
)
delete_expired_reservations_task()
assert PreorderReservation.objects.count() == reservations_count
diff --git a/saleor/webhook/observability/payload_schema.py b/saleor/webhook/observability/payload_schema.py
index ae9ed18484..a4dfeaba43 100644
--- a/saleor/webhook/observability/payload_schema.py
+++ b/saleor/webhook/observability/payload_schema.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+import datetime
from enum import Enum
from json.encoder import ESCAPE_ASCII, ESCAPE_DCT
from typing import Optional, TypedDict
@@ -140,10 +140,10 @@ class EventDeliveryAttemptResponse(TypedDict):
class EventDeliveryAttemptPayload(ObservabilityEventBase):
id: str
- time: datetime
+ time: datetime.datetime
duration: Optional[float]
status: str
- next_retry: Optional[datetime]
+ next_retry: Optional[datetime.datetime]
request: EventDeliveryAttemptRequest
response: EventDeliveryAttemptResponse
event_delivery: EventDelivery
diff --git a/saleor/webhook/observability/payloads.py b/saleor/webhook/observability/payloads.py
index 880fac6f39..4cae585e52 100644
--- a/saleor/webhook/observability/payloads.py
+++ b/saleor/webhook/observability/payloads.py
@@ -1,3 +1,4 @@
+import datetime
import json
import uuid
from collections.abc import Mapping
@@ -39,8 +40,6 @@ from .payload_schema import (
from .sensitive_data import SENSITIVE_GQL_FIELDS
if TYPE_CHECKING:
- from datetime import datetime
-
from ...core.models import EventDeliveryAttempt
from .utils import GraphQLOperationResponse
@@ -194,7 +193,7 @@ def generate_api_call_payload(
@traced_payload_generator
def generate_event_delivery_attempt_payload(
attempt: "EventDeliveryAttempt",
- next_retry: Optional["datetime"],
+ next_retry: Optional[datetime.datetime],
bytes_limit: int,
) -> bytes:
if not attempt.delivery:
diff --git a/saleor/webhook/observability/tests/test_buffer.py b/saleor/webhook/observability/tests/test_buffer.py
index 51bcd95681..1d7ac64368 100644
--- a/saleor/webhook/observability/tests/test_buffer.py
+++ b/saleor/webhook/observability/tests/test_buffer.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
import pytest
from django.utils import timezone
@@ -153,6 +153,6 @@ def test_pop_expired_events(buffer):
with freeze_time(push_time):
events = [f"event-data-{i}".encode() for i in range(MAX_SIZE)]
buffer.put_events(events)
- with freeze_time(push_time + timedelta(seconds=buffer.timeout + 1)):
+ with freeze_time(push_time + datetime.timedelta(seconds=buffer.timeout + 1)):
popped_events = buffer.pop_events()
assert popped_events == []
diff --git a/saleor/webhook/observability/tests/test_payloads.py b/saleor/webhook/observability/tests/test_payloads.py
index b85ef0d3f9..d269bcf672 100644
--- a/saleor/webhook/observability/tests/test_payloads.py
+++ b/saleor/webhook/observability/tests/test_payloads.py
@@ -1,12 +1,11 @@
+import datetime
import json
-from datetime import datetime
from unittest.mock import patch
from uuid import UUID
import graphene
import pytest
from django.http import JsonResponse
-from django.utils import timezone
from ....core import EventDeliveryStatus
from ....webhook.event_types import WebhookEventAsyncType
@@ -250,7 +249,7 @@ def test_generate_api_call_payload(app, rf, gql_operation_factory, site_settings
request = rf.post(
"/graphql", data={"request": "data"}, content_type="application/json"
)
- request.request_time = datetime(1914, 6, 28, 10, 50, tzinfo=timezone.utc)
+ request.request_time = datetime.datetime(1914, 6, 28, 10, 50, tzinfo=datetime.UTC)
request.app = app
response = JsonResponse({"response": "data"})
query_a = "query FirstQuery { shop { name } }"
@@ -328,7 +327,7 @@ def test_generate_api_call_payload_skip_operations_when_size_limit_too_low(
request = rf.post(
"/graphql", data={"request": "data"}, content_type="application/json"
)
- request.request_time = datetime(1914, 6, 28, 10, 50, tzinfo=timezone.utc)
+ request.request_time = datetime.datetime(1914, 6, 28, 10, 50, tzinfo=datetime.UTC)
request.app = app
response = JsonResponse({"response": "data"})
query = "query FirstQuery { shop { name } } query SecondQuery { shop { name } }"
@@ -356,7 +355,7 @@ def test_generate_api_call_payload_when_too_low_bytes_limit(app, rf):
request = rf.post(
"/graphql", data={"request": "data"}, content_type="application/json"
)
- request.request_time = datetime(1914, 6, 28, 10, 50, tzinfo=timezone.utc)
+ request.request_time = datetime.datetime(1914, 6, 28, 10, 50, tzinfo=datetime.UTC)
request.app = app
response = JsonResponse({"response": "data"})
payload = generate_api_call_payload(request, response, [], 1024)
@@ -366,7 +365,7 @@ def test_generate_api_call_payload_when_too_low_bytes_limit(app, rf):
def test_generate_event_delivery_attempt_payload(event_attempt):
- created_at = datetime(1914, 6, 28, 10, 50, tzinfo=timezone.utc)
+ created_at = datetime.datetime(1914, 6, 28, 10, 50, tzinfo=datetime.UTC)
event_attempt.created_at = created_at
delivery = event_attempt.delivery
webhook = delivery.webhook
@@ -443,7 +442,7 @@ def test_generate_event_delivery_attempt_payload_raises_error_when_no_payload(
def test_generate_event_delivery_attempt_payload_with_next_retry_date(
event_attempt,
):
- next_retry_date = datetime(2004, 5, 1, 0, 0, tzinfo=timezone.utc)
+ next_retry_date = datetime.datetime(2004, 5, 1, 0, 0, tzinfo=datetime.UTC)
payload = generate_event_delivery_attempt_payload(
event_attempt, next_retry_date, 1024
)
diff --git a/saleor/webhook/observability/tests/test_utils.py b/saleor/webhook/observability/tests/test_utils.py
index 77662e5686..f73c545e2d 100644
--- a/saleor/webhook/observability/tests/test_utils.py
+++ b/saleor/webhook/observability/tests/test_utils.py
@@ -1,5 +1,5 @@
+import datetime
import json
-from datetime import datetime, timezone
from unittest.mock import patch
import pytest
@@ -131,8 +131,14 @@ def test_json_truncate_text_comparison():
("retry", "next_retry_date"),
[
(Retry(), None),
- (Retry(when=60 * 10), datetime(2004, 5, 1, 0, 10, tzinfo=timezone.utc)),
- (Retry(when=datetime(2004, 5, 1, 12)), datetime(2004, 5, 1, 12)),
+ (
+ Retry(when=60 * 10),
+ datetime.datetime(2004, 5, 1, 0, 10, tzinfo=datetime.UTC),
+ ),
+ (
+ Retry(when=datetime.datetime(2004, 5, 1, 12, tzinfo=datetime.UTC)),
+ datetime.datetime(2004, 5, 1, 12, tzinfo=datetime.UTC),
+ ),
],
)
@freeze_time("2004-05-01 0:00")
diff --git a/saleor/webhook/observability/utils.py b/saleor/webhook/observability/utils.py
index 95c6d620b3..4f97c8d49c 100644
--- a/saleor/webhook/observability/utils.py
+++ b/saleor/webhook/observability/utils.py
@@ -1,9 +1,9 @@
+import datetime
import functools
import logging
from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass
-from datetime import datetime, timedelta
from functools import partial
from time import monotonic
from typing import TYPE_CHECKING, Callable, Optional
@@ -82,10 +82,10 @@ def get_webhooks(timeout=CACHE_TIMEOUT) -> list[WebhookData]:
return webhooks_data
-def task_next_retry_date(retry_error: "Retry") -> Optional[datetime]:
+def task_next_retry_date(retry_error: "Retry") -> Optional[datetime.datetime]:
if isinstance(retry_error.when, (int, float)):
- return timezone.now() + timedelta(seconds=retry_error.when)
- if isinstance(retry_error.when, datetime):
+ return timezone.now() + datetime.timedelta(seconds=retry_error.when)
+ if isinstance(retry_error.when, datetime.datetime):
return retry_error.when
return None
@@ -188,7 +188,7 @@ def report_view(method):
def report_event_delivery_attempt(
- attempt: "EventDeliveryAttempt", next_retry: Optional["datetime"] = None
+ attempt: "EventDeliveryAttempt", next_retry: Optional[datetime.datetime] = None
):
if not settings.OBSERVABILITY_ACTIVE:
return
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index baf02095b5..15a926db26 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -1,6 +1,6 @@
+import datetime
from collections import defaultdict
from collections.abc import Iterable
-from datetime import date, datetime
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional, Union
@@ -140,7 +140,10 @@ def serialize_product_attributes(product: "Product") -> list[dict]:
for attr_value in values_map[attribute.pk]:
attr_slug = attr_value.slug
value: dict[
- str, Optional[Union[str, datetime, date, bool, dict[str, Any]]]
+ str,
+ Optional[
+ Union[str, datetime.datetime, datetime.date, bool, dict[str, Any]]
+ ],
] = {
"name": attr_value.name,
"slug": attr_slug,
@@ -197,7 +200,10 @@ def serialize_variant_attributes(variant: "ProductVariant") -> list[dict]:
for attr_value in attr.values.all():
attr_slug = attr_value.slug
value: dict[
- str, Optional[Union[str, datetime, date, bool, dict[str, Any]]]
+ str,
+ Optional[
+ Union[str, datetime.datetime, datetime.date, bool, dict[str, Any]]
+ ],
] = {
"name": attr_value.name,
"slug": attr_slug,
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index b0a7022031..7cfa023ffc 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -1,6 +1,6 @@
+import datetime
import json
from dataclasses import asdict
-from datetime import datetime, timedelta
from decimal import Decimal
from itertools import chain
from unittest import mock
@@ -8,7 +8,6 @@ from unittest.mock import ANY, patch, sentinel
import graphene
import pytest
-import pytz
from django.core.serializers.json import DjangoJSONEncoder
from freezegun import freeze_time
from measurement.measures import Weight
@@ -100,7 +99,9 @@ def order_for_payload(fulfilled_order, voucher_percentage):
voucher=voucher_percentage,
)
- discount.created_at = datetime.now(pytz.utc) + timedelta(days=1)
+ discount.created_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ days=1
+ )
discount.save(update_fields=["created_at"])
line_without_sku = order.lines.last()
diff --git a/saleor/webhook/tests/test_webhook_protocols.py b/saleor/webhook/tests/test_webhook_protocols.py
index 075959cbb3..96c185884a 100644
--- a/saleor/webhook/tests/test_webhook_protocols.py
+++ b/saleor/webhook/tests/test_webhook_protocols.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+import datetime
from unittest import mock
from unittest.mock import MagicMock, patch
@@ -240,7 +240,7 @@ def test_trigger_webhooks_with_http(
mock_request.return_value = MagicMock(
text="{response: body}",
headers={"response": "header"},
- elapsed=timedelta(seconds=2),
+ elapsed=datetime.timedelta(seconds=2),
status_code=200,
ok=True,
)
@@ -289,7 +289,7 @@ def test_trigger_webhooks_with_http_and_secret_key(
mock_request.return_value = MagicMock(
text="{response: body}",
headers={"response": "header"},
- elapsed=timedelta(seconds=2),
+ elapsed=datetime.timedelta(seconds=2),
status_code=200,
ok=True,
)
@@ -338,7 +338,7 @@ def test_trigger_webhooks_with_http_and_secret_key_as_empty_string(
mock_request.return_value = MagicMock(
text="{response: body}",
headers={"response": "header"},
- elapsed=timedelta(seconds=2),
+ elapsed=datetime.timedelta(seconds=2),
status_code=200,
ok=True,
)
diff --git a/saleor/webhook/transport/tests/test_utils.py b/saleor/webhook/transport/tests/test_utils.py
index 375675b1ed..b6e610cce7 100644
--- a/saleor/webhook/transport/tests/test_utils.py
+++ b/saleor/webhook/transport/tests/test_utils.py
@@ -48,7 +48,7 @@ def test_webhook_retry(webhook, event_delivery):
# given
attempt = EventDeliveryAttempt(
id=1,
- created_at=datetime.datetime.utcnow(),
+ created_at=datetime.datetime.now(tz=datetime.UTC),
delivery=event_delivery,
request_headers="",
task_id="123",
@@ -68,7 +68,7 @@ def test_webhook_retry_404(webhook, event_delivery):
# given
attempt = EventDeliveryAttempt(
id=1,
- created_at=datetime.datetime.utcnow(),
+ created_at=datetime.datetime.now(tz=datetime.UTC),
delivery=event_delivery,
request_headers="",
task_id="123",
@@ -88,7 +88,7 @@ def test_webhook_retry_redirect(webhook, event_delivery):
# given
attempt = EventDeliveryAttempt(
id=1,
- created_at=datetime.datetime.utcnow(),
+ created_at=datetime.datetime.now(tz=datetime.UTC),
delivery=event_delivery,
request_headers="",
task_id="123",