]> git.ipfire.org Git - thirdparty/patchwork.git/commitdiff
Replace use of datetime.datetime.utcnow()
authorStephen Finucane <stephen@that.guru>
Tue, 16 Jan 2024 19:14:10 +0000 (19:14 +0000)
committerStephen Finucane <stephen@that.guru>
Tue, 16 Jan 2024 21:58:30 +0000 (21:58 +0000)
This is deprecated in Python 3.12.

Signed-off-by: Stephen Finucane <stephen@that.guru>
14 files changed:
patchwork/migrations/0001_squashed_0040_add_related_patches.py
patchwork/migrations/0023_timezone_unify.py
patchwork/migrations/0041_python3.py
patchwork/migrations/0042_add_cover_model.py
patchwork/models.py
patchwork/notifications.py
patchwork/parser.py
patchwork/signals.py
patchwork/tests/test_checks.py
patchwork/tests/test_expiry.py
patchwork/tests/test_notifications.py
patchwork/tests/utils.py
patchwork/tests/views/test_patch.py
patchwork/tests/views/test_utils.py

index 2fa8d6ba739c1a138153087715a137ae76be582f..270ad348b8172fc21c857a087eec08dbe8631978 100644 (file)
@@ -1,9 +1,8 @@
-import datetime
-
 from django.conf import settings
 from django.db import migrations, models
 import django.db.migrations.operations.special
 import django.db.models.deletion
+from django.utils import timezone as tz_utils
 
 import patchwork.fields
 import patchwork.models
@@ -99,7 +98,7 @@ class Migration(migrations.Migration):
                 ),
                 (
                     'date',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
                 (
                     'state',
@@ -364,7 +363,7 @@ class Migration(migrations.Migration):
                 ('msgid', models.CharField(max_length=255)),
                 (
                     'date',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
                 ('headers', models.TextField(blank=True)),
                 ('content', models.TextField(blank=True, null=True)),
@@ -638,7 +637,7 @@ class Migration(migrations.Migration):
                 (
                     'date',
                     models.DateTimeField(
-                        default=datetime.datetime.utcnow,
+                        default=tz_utils.now,
                         help_text=b'The time this event was created.',
                     ),
                 ),
@@ -774,7 +773,7 @@ class Migration(migrations.Migration):
                 ('key', patchwork.fields.HashField(max_length=40)),
                 (
                     'date',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
                 ('active', models.BooleanField(default=True)),
                 (
@@ -849,7 +848,7 @@ class Migration(migrations.Migration):
                 ('msgid', models.CharField(max_length=255)),
                 (
                     'date',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
                 ('headers', models.TextField(blank=True)),
                 ('content', models.TextField(blank=True, null=True)),
@@ -917,7 +916,7 @@ class Migration(migrations.Migration):
                 ),
                 (
                     'last_modified',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
             ],
         ),
index 50a70c3b17037f1dd00de8e3b21d01288ad6d39e..6adafe5e0534c7e08e21ce23ca7ece0b9ecdaac8 100644 (file)
@@ -1,6 +1,5 @@
-import datetime
-
 from django.db import migrations, models
+from django.utils import timezone as tz_utils
 
 
 class Migration(migrations.Migration):
@@ -12,34 +11,34 @@ class Migration(migrations.Migration):
         migrations.AlterField(
             model_name='check',
             name='date',
-            field=models.DateTimeField(default=datetime.datetime.utcnow),
+            field=models.DateTimeField(default=tz_utils.now),
         ),
         migrations.AlterField(
             model_name='comment',
             name='date',
-            field=models.DateTimeField(default=datetime.datetime.utcnow),
+            field=models.DateTimeField(default=tz_utils.now),
         ),
         migrations.AlterField(
             model_name='emailconfirmation',
             name='date',
-            field=models.DateTimeField(default=datetime.datetime.utcnow),
+            field=models.DateTimeField(default=tz_utils.now),
         ),
         migrations.AlterField(
             model_name='event',
             name='date',
             field=models.DateTimeField(
-                default=datetime.datetime.utcnow,
+                default=tz_utils.now,
                 help_text=b'The time this event was created.',
             ),
         ),
         migrations.AlterField(
             model_name='patchchangenotification',
             name='last_modified',
-            field=models.DateTimeField(default=datetime.datetime.utcnow),
+            field=models.DateTimeField(default=tz_utils.now),
         ),
         migrations.AlterField(
             model_name='submission',
             name='date',
-            field=models.DateTimeField(default=datetime.datetime.utcnow),
+            field=models.DateTimeField(default=tz_utils.now),
         ),
     ]
index 09098c839acddc920feec7b48e2302ce3d1f46fb..874fea8ad20f7f3dcdc8c45b7a89767e86cdb6fa 100644 (file)
@@ -6,11 +6,10 @@
 #
 # flake8: noqa
 
-import datetime
-
 from django.conf import settings
 from django.db import migrations, models
 import django.db.models.deletion
+from django.utils import timezone as tz_utils
 
 import patchwork.models
 
@@ -167,7 +166,7 @@ class Migration(migrations.Migration):
                     model_name='event',
                     name='date',
                     field=models.DateTimeField(
-                        default=datetime.datetime.utcnow,
+                        default=tz_utils.now,
                         help_text='The time this event was created.',
                     ),
                 ),
index d8cffd6a0df13cffcab668791aff06f0f0300256..b8702f1c15c1aec56f647c5eb5dfa819df928504 100644 (file)
@@ -1,7 +1,7 @@
-import datetime
-
 from django.db import connection, migrations, models
 import django.db.models.deletion
+from django.utils import timezone as tz_utils
+
 import patchwork.models
 
 
@@ -53,7 +53,7 @@ class Migration(migrations.Migration):
                 ('msgid', models.CharField(max_length=255)),
                 (
                     'date',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
                 ('headers', models.TextField(blank=True)),
                 ('content', models.TextField(blank=True, null=True)),
@@ -103,7 +103,7 @@ class Migration(migrations.Migration):
                 ('msgid', models.CharField(max_length=255)),
                 (
                     'date',
-                    models.DateTimeField(default=datetime.datetime.utcnow),
+                    models.DateTimeField(default=tz_utils.now),
                 ),
                 ('headers', models.TextField(blank=True)),
                 ('content', models.TextField(blank=True, null=True)),
index 67408b00f84611ab25c80077d485635a59d7933f..422ac51d7e56145369157c2e573b6486dd5b47e0 100644 (file)
@@ -13,10 +13,11 @@ import re
 from django.conf import settings
 from django.contrib.auth.models import User
 from django.core.exceptions import ValidationError
+from django.core.validators import validate_unicode_slug
 from django.db import models
 from django.urls import reverse
 from django.utils.functional import cached_property
-from django.core.validators import validate_unicode_slug
+from django.utils import timezone as tz_utils
 
 from patchwork.fields import HashField
 from patchwork.hasher import hash_diff
@@ -342,7 +343,7 @@ class EmailMixin(models.Model):
     # email metadata
 
     msgid = models.CharField(max_length=255)
-    date = models.DateTimeField(default=datetime.datetime.utcnow)
+    date = models.DateTimeField(default=tz_utils.now)
     headers = models.TextField(blank=True)
 
     # content
@@ -1079,7 +1080,7 @@ class Check(models.Model):
 
     patch = models.ForeignKey(Patch, on_delete=models.CASCADE)
     user = models.ForeignKey(User, on_delete=models.CASCADE)
-    date = models.DateTimeField(default=datetime.datetime.utcnow)
+    date = models.DateTimeField(default=tz_utils.now)
 
     state = models.SmallIntegerField(
         choices=STATE_CHOICES,
@@ -1172,7 +1173,7 @@ class Event(models.Model):
         help_text='The category of the event.',
     )
     date = models.DateTimeField(
-        default=datetime.datetime.utcnow,
+        default=tz_utils.now,
         help_text='The time this event was created.',
     )
     actor = models.ForeignKey(
@@ -1310,7 +1311,7 @@ class EmailConfirmation(models.Model):
     email = models.CharField(max_length=200)
     user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
     key = HashField()
-    date = models.DateTimeField(default=datetime.datetime.utcnow)
+    date = models.DateTimeField(default=tz_utils.now)
     active = models.BooleanField(default=True)
 
     def deactivate(self):
@@ -1318,7 +1319,7 @@ class EmailConfirmation(models.Model):
         self.save()
 
     def is_valid(self):
-        return self.date + self.validity > datetime.datetime.utcnow()
+        return self.date + self.validity > tz_utils.now()
 
     def save(self, *args, **kwargs):
         limit = 1 << 32
@@ -1346,5 +1347,5 @@ class PatchChangeNotification(models.Model):
         primary_key=True,
         on_delete=models.CASCADE,
     )
-    last_modified = models.DateTimeField(default=datetime.datetime.utcnow)
+    last_modified = models.DateTimeField(default=tz_utils.now)
     orig_state = models.ForeignKey(State, on_delete=models.CASCADE)
index 50d047434ed0d6eaa59a5cf2477d571e0c317840..6f33f8992fa2b4c5cd7d74697270d788c3679d6e 100644 (file)
@@ -14,6 +14,7 @@ from django.core.mail import EmailMessage
 from django.db.models import Count
 from django.db.models import Q
 from django.template.loader import render_to_string
+from django.utils import timezone as tz_utils
 
 from patchwork.models import EmailConfirmation
 from patchwork.models import EmailOptout
@@ -21,7 +22,7 @@ from patchwork.models import PatchChangeNotification
 
 
 def send_notifications():
-    date_limit = datetime.datetime.utcnow() - datetime.timedelta(
+    date_limit = tz_utils.now() - datetime.timedelta(
         minutes=settings.NOTIFICATION_DELAY_MINUTES
     )
 
@@ -97,9 +98,9 @@ def expire_notifications():
     Users whose registration confirmation has expired are removed.
     """
     # expire any invalid confirmations
-    q = Q(
-        date__lt=datetime.datetime.utcnow() - EmailConfirmation.validity
-    ) | Q(active=False)
+    q = Q(date__lt=tz_utils.now() - EmailConfirmation.validity) | Q(
+        active=False
+    )
     EmailConfirmation.objects.filter(q).delete()
 
     # remove inactive users with no pending confirmation
index 2c863a519215e47e23e3ec3f2fb9638611fbfbe6..729e19b4c1eaef23d79c42edb174742a307ae223 100644 (file)
@@ -17,6 +17,7 @@ import re
 from django.contrib.auth.models import User
 from django.db.utils import IntegrityError
 from django.db import transaction
+from django.utils import timezone as tz_utils
 
 from patchwork.models import Cover
 from patchwork.models import CoverComment
@@ -460,11 +461,11 @@ def get_or_create_author(mail, project=None):
 def find_date(mail):
     h = clean_header(mail.get('Date', ''))
     if not h:
-        return datetime.datetime.utcnow()
+        return tz_utils.now()
 
     t = parsedate_tz(h)
     if not t:
-        return datetime.datetime.utcnow()
+        return tz_utils.now()
 
     try:
         d = datetime.datetime.utcfromtimestamp(mktime_tz(t))
@@ -476,7 +477,7 @@ def find_date(mail):
         #   -> ValueError
         # - Date:, 11 Sep 2016 407080403080105:04 +0100
         #   -> OSError (Python 3)
-        d = datetime.datetime.utcnow()
+        d = tz_utils.now()
 
     return d
 
index 8e31080b1caa9365a7d8cb14d693ae8fdd444085..d7dd3463de0a51fd181621ed23e71a0b35b8d981 100644 (file)
@@ -3,11 +3,10 @@
 #
 # SPDX-License-Identifier: GPL-2.0-or-later
 
-from datetime import datetime as dt
-
 from django.db.models.signals import post_save
 from django.db.models.signals import pre_save
 from django.dispatch import receiver
+from django.utils import timezone as tz_utils
 
 from patchwork.models import Check
 from patchwork.models import Cover
@@ -53,7 +52,7 @@ def patch_change_callback(sender, instance, raw, **kwargs):
         notification.delete()
         return
 
-    notification.last_modified = dt.utcnow()
+    notification.last_modified = tz_utils.now()
     notification.save()
 
 
index eb59c7d20c0d3fa7abd23cf425c1d84141df5145..bf5dc75723f74fe636006239a871a14fd797e1ba 100644 (file)
@@ -3,10 +3,10 @@
 #
 # SPDX-License-Identifier: GPL-2.0-or-later
 
-from datetime import datetime as dt
 from datetime import timedelta
 
 from django.test import TransactionTestCase
+from django.utils import timezone as tz_utils
 
 from patchwork.models import Check
 from patchwork.tests.utils import create_check
@@ -73,12 +73,12 @@ class PatchChecksTest(TransactionTestCase):
         self.assertChecksEqual(self.patch, [check_a, check_b])
 
     def test_checks__duplicate_checks(self):
-        self._create_check(date=(dt.utcnow() - timedelta(days=1)))
+        self._create_check(date=(tz_utils.now() - timedelta(days=1)))
         check = self._create_check()
         # this isn't a realistic scenario (dates shouldn't be set by user so
         # they will always increment), but it's useful to verify the removal
         # of older duplicates by the function
-        self._create_check(date=(dt.utcnow() - timedelta(days=2)))
+        self._create_check(date=(tz_utils.now() - timedelta(days=2)))
         self.assertChecksEqual(self.patch, [check])
 
     def test_checks__nultiple_users(self):
@@ -94,7 +94,7 @@ class PatchChecksTest(TransactionTestCase):
         self.assertCheckCountEqual(self.patch, 1, {Check.STATE_SUCCESS: 1})
 
     def test_check_count__multiple_checks(self):
-        self._create_check(date=(dt.utcnow() - timedelta(days=1)))
+        self._create_check(date=(tz_utils.now() - timedelta(days=1)))
         self._create_check(context='new/test1')
         self.assertCheckCountEqual(self.patch, 2, {Check.STATE_SUCCESS: 2})
 
@@ -104,14 +104,14 @@ class PatchChecksTest(TransactionTestCase):
         self.assertCheckCountEqual(self.patch, 2, {Check.STATE_SUCCESS: 2})
 
     def test_check_count__duplicate_check_same_state(self):
-        self._create_check(date=(dt.utcnow() - timedelta(days=1)))
+        self._create_check(date=(tz_utils.now() - timedelta(days=1)))
         self.assertCheckCountEqual(self.patch, 1, {Check.STATE_SUCCESS: 1})
 
         self._create_check()
         self.assertCheckCountEqual(self.patch, 2, {Check.STATE_SUCCESS: 1})
 
     def test_check_count__duplicate_check_new_state(self):
-        self._create_check(date=(dt.utcnow() - timedelta(days=1)))
+        self._create_check(date=(tz_utils.now() - timedelta(days=1)))
         self.assertCheckCountEqual(self.patch, 1, {Check.STATE_SUCCESS: 1})
 
         self._create_check(state=Check.STATE_FAIL)
index f7c810ab5aa07834b29ae23f723c87176e64c1d8..e31f44c4a6feb7427736d5b9bc543c86053eabd4 100644 (file)
@@ -7,6 +7,7 @@ import datetime
 
 from django.contrib.auth.models import User
 from django.test import TestCase
+from django.utils import timezone as tz_utils
 
 from patchwork.models import EmailConfirmation
 from patchwork.models import Patch
@@ -33,7 +34,7 @@ class TestRegistrationExpiry(TestCase):
 
     def test_old_registration_expiry(self):
         date = (
-            datetime.datetime.utcnow() - EmailConfirmation.validity
+            tz_utils.now() - EmailConfirmation.validity
         ) - datetime.timedelta(hours=1)
         user, conf = self.register(date)
 
@@ -44,7 +45,7 @@ class TestRegistrationExpiry(TestCase):
 
     def test_recent_registration_expiry(self):
         date = (
-            datetime.datetime.utcnow() - EmailConfirmation.validity
+            tz_utils.now() - EmailConfirmation.validity
         ) + datetime.timedelta(hours=1)
         user, conf = self.register(date)
 
@@ -54,7 +55,7 @@ class TestRegistrationExpiry(TestCase):
         self.assertTrue(EmailConfirmation.objects.filter(pk=conf.pk).exists())
 
     def test_inactive_registration_expiry(self):
-        user, conf = self.register(datetime.datetime.utcnow())
+        user, conf = self.register(tz_utils.now())
 
         # confirm registration
         conf.user.is_active = True
@@ -73,7 +74,7 @@ class TestRegistrationExpiry(TestCase):
 
         # ... then starts registration...
         date = (
-            datetime.datetime.utcnow() - EmailConfirmation.validity
+            tz_utils.now() - EmailConfirmation.validity
         ) - datetime.timedelta(hours=1)
         user = create_user(link_person=False, email=submitter.email)
         user.is_active = False
index b2fd004911f76b15a345d3179c81e1a4e8f164e9..70d25da36a399650b9b0a288e1a391898b1d3e24 100644 (file)
@@ -8,6 +8,7 @@ import datetime
 from django.conf import settings
 from django.core import mail
 from django.test import TestCase
+from django.utils import timezone as tz_utils
 
 from patchwork.models import EmailOptout
 from patchwork.models import PatchChangeNotification
@@ -105,7 +106,7 @@ class PatchNotificationEmailTest(TestCase):
         self.project = create_project(send_notifications=True)
 
     def _expire_notifications(self, **kwargs):
-        timestamp = datetime.datetime.utcnow() - datetime.timedelta(
+        timestamp = tz_utils.now() - datetime.timedelta(
             minutes=settings.NOTIFICATION_DELAY_MINUTES + 1
         )
 
index f379270c94b101bc85a72b9b336fbeaa5404281e..4f40489126f0f63a8803b2c32f3321f1ce2216a2 100644 (file)
@@ -4,12 +4,12 @@
 # SPDX-License-Identifier: GPL-2.0-or-later
 
 import codecs
-from datetime import datetime as dt
 from datetime import timedelta
 from email.utils import make_msgid
 import os
 
 from django.contrib.auth.models import User
+from django.utils import timezone as tz_utils
 
 from patchwork.models import Bundle
 from patchwork.models import Check
@@ -275,7 +275,7 @@ def create_check(**kwargs):
     values = {
         'patch': create_patch() if 'patch' not in kwargs else None,
         'user': create_user() if 'user' not in kwargs else None,
-        'date': dt.utcnow(),
+        'date': tz_utils.now(),
         'state': Check.STATE_SUCCESS,
         'target_url': 'http://example.com/',
         'description': '',
@@ -290,7 +290,7 @@ def create_series(**kwargs):
     """Create 'Series' object."""
     values = {
         'project': create_project() if 'project' not in kwargs else None,
-        'date': dt.utcnow(),
+        'date': tz_utils.now(),
         'submitter': create_person() if 'submitter' not in kwargs else None,
         'total': 1,
     }
@@ -331,7 +331,7 @@ def _create_submissions(create_func, count=1, **kwargs):
         'submitter': create_person() if 'submitter' not in kwargs else None,
     }
     values.update(kwargs)
-    date = dt.utcnow()
+    date = tz_utils.now()
 
     objects = []
     for i in range(0, count):
index 46247c162401f82fabeed31ec82bca29b532bbae..b34d4ed1aab11ede09906f9b28e5791847bbf74f 100644 (file)
@@ -12,6 +12,7 @@ import django
 from django.conf import settings
 from django.test import TestCase
 from django.urls import reverse
+from django.utils import timezone as tz_utils
 
 from patchwork.models import Check
 from patchwork.models import Patch
@@ -345,7 +346,7 @@ class PatchViewTest(TestCase):
             user=user,
             context='foo',
             state=Check.STATE_FAIL,
-            date=(dt.utcnow() - timedelta(days=1)),
+            date=(tz_utils.now() - timedelta(days=1)),
         )
         create_check(
             patch=patch, user=user, context='foo', state=Check.STATE_SUCCESS
index 8b795815aed0b3098df746161b99e63499c45597..2b44cfdaf8599c30f1befdc22f1bf4e121395e68 100644 (file)
@@ -12,6 +12,7 @@ import email
 
 from django.http import Http404
 from django.test import TestCase
+from django.utils import timezone as tz_utils
 
 from patchwork.tests.utils import create_patch
 from patchwork.tests.utils import create_patch_comment
@@ -210,7 +211,7 @@ class MboxPatchResponseTest(TestCase):
         patch = create_patch()
         offset = 3 * 60 * 60  # 3 (hours) * 60 (minutes) * 60 (seconds)
         tz = dateutil.tz.tzoffset(None, offset)
-        date = datetime.datetime.utcnow() - datetime.timedelta(days=1)
+        date = tz_utils.now() - datetime.timedelta(days=1)
         date = date.replace(tzinfo=tz, microsecond=0)
 
         patch.headers = 'Date: %s\n' % date.strftime("%a, %d %b %Y %T %z")