diff --git a/django/utils/timezone.py b/django/utils/timezone.py index 68c214d26f..a56ff0b6ab 100644 --- a/django/utils/timezone.py +++ b/django/utils/timezone.py @@ -111,6 +111,7 @@ def get_default_timezone(): if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None: _localtime = pytz.timezone(settings.TIME_ZONE) else: + # This relies on os.environ['TZ'] being set to settings.TIME_ZONE. _localtime = LocalTimezone() return _localtime @@ -198,10 +199,10 @@ class override(object): activate(self.timezone) def __exit__(self, exc_type, exc_value, traceback): - if self.old_timezone is not None: - _active.value = self.old_timezone + if self.old_timezone is None: + deactivate() else: - del _active.value + _active.value = self.old_timezone # Templates diff --git a/tests/regressiontests/utils/timezone.py b/tests/regressiontests/utils/timezone.py index 991600c8b9..650198e8ff 100644 --- a/tests/regressiontests/utils/timezone.py +++ b/tests/regressiontests/utils/timezone.py @@ -3,9 +3,14 @@ import datetime import pickle from django.test.utils import override_settings from django.utils import timezone +from django.utils.tzinfo import FixedOffset from django.utils import unittest +EAT = FixedOffset(180) # Africa/Nairobi +ICT = FixedOffset(420) # Asia/Bangkok + + class TimezoneTests(unittest.TestCase): def test_localtime(self): @@ -20,6 +25,31 @@ class TimezoneTests(unittest.TestCase): with override_settings(USE_TZ=False): self.assertTrue(timezone.is_naive(timezone.now())) + def test_override(self): + default = timezone.get_default_timezone() + try: + timezone.activate(ICT) + + with timezone.override(EAT): + self.assertIs(EAT, timezone.get_current_timezone()) + self.assertIs(ICT, timezone.get_current_timezone()) + + with timezone.override(None): + self.assertIs(default, timezone.get_current_timezone()) + self.assertIs(ICT, timezone.get_current_timezone()) + + timezone.deactivate() + + with timezone.override(EAT): + self.assertIs(EAT, timezone.get_current_timezone()) + self.assertIs(default, timezone.get_current_timezone()) + + with timezone.override(None): + self.assertIs(default, timezone.get_current_timezone()) + self.assertIs(default, timezone.get_current_timezone()) + finally: + timezone.deactivate() + def test_copy(self): self.assertIsInstance(copy.copy(timezone.UTC()), timezone.UTC) self.assertIsInstance(copy.copy(timezone.LocalTimezone()), timezone.LocalTimezone)