From fa89acf1d0a4adbf0802c1275494f5159a912c9e Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Fri, 16 May 2014 22:52:10 +0200 Subject: [PATCH] Fixed #22625 -- Normalized make_aware/naive errors. Also added tests for is/make_aware/naive. Thanks Tom Michaelis for the report. --- django/utils/timezone.py | 4 ++++ tests/utils_tests/test_timezone.py | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/django/utils/timezone.py b/django/utils/timezone.py index 9c70a11a7d..8138767fb2 100644 --- a/django/utils/timezone.py +++ b/django/utils/timezone.py @@ -351,6 +351,8 @@ def make_aware(value, timezone): """ Makes a naive datetime.datetime in a given time zone aware. """ + if is_aware(value): + raise ValueError("make_aware expects a naive value, got %s" % value) if hasattr(timezone, 'localize'): # available for pytz time zones return timezone.localize(value, is_dst=None) @@ -363,6 +365,8 @@ def make_naive(value, timezone): """ Makes an aware datetime.datetime naive in a given time zone. """ + if is_naive(value): + raise ValueError("make_naive expects an aware value, got %s" % value) value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # available for pytz time zones diff --git a/tests/utils_tests/test_timezone.py b/tests/utils_tests/test_timezone.py index 1d608d0951..4b5a39a928 100644 --- a/tests/utils_tests/test_timezone.py +++ b/tests/utils_tests/test_timezone.py @@ -71,3 +71,28 @@ class TimezoneTests(unittest.TestCase): def test_pickling_unpickling(self): self.assertIsInstance(pickle.loads(pickle.dumps(timezone.UTC())), timezone.UTC) self.assertIsInstance(pickle.loads(pickle.dumps(timezone.LocalTimezone())), timezone.LocalTimezone) + + def test_is_aware(self): + self.assertTrue(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))) + self.assertFalse(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30))) + + def test_is_naive(self): + self.assertFalse(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))) + self.assertTrue(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30))) + + def test_make_aware(self): + self.assertEqual( + timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT), + datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) + with self.assertRaises(ValueError): + timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT) + + def test_make_naive(self): + self.assertEqual( + timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT), + datetime.datetime(2011, 9, 1, 13, 20, 30)) + self.assertEqual( + timezone.make_naive(datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), EAT), + datetime.datetime(2011, 9, 1, 13, 20, 30)) + with self.assertRaises(ValueError): + timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT)