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)