Add a fixture to let tests manage the lazy flag

We do not want to expose the stored lazy flag, but we do want to allow
applications to force it to a certain state and then restore it to its
original test for testing. This new fixture provides a way to do that.

Change-Id: Ica05fd8fc7e687da69d61ea84bf1ceae65db93ce
This commit is contained in:
Doug Hellmann 2015-01-06 17:18:37 -05:00
parent 0ce52c22b6
commit 118aeb0ceb
2 changed files with 62 additions and 2 deletions

View File

@ -16,6 +16,7 @@
import fixtures
import six
from oslo_i18n import _lazy
from oslo_i18n import _message
@ -63,3 +64,26 @@ class Translation(fixtures.Fixture):
"""
return six.text_type(msg)
class ToggleLazy(fixtures.Fixture):
"""Fixture to toggle lazy translation on or off for a test."""
def __init__(self, enabled):
"""Force lazy translation on or off.
:param enabled: Flag controlling whether to enable or disable
lazy translation, passed to :func:`~oslo_i18n.enable_lazy`.
:type enabled: bool
"""
super(ToggleLazy, self).__init__()
self._enabled = enabled
self._original_value = _lazy.USE_LAZY
def setUp(self):
super(ToggleLazy, self).setUp()
self.addCleanup(self._restore_original)
_lazy.enable_lazy(self._enabled)
def _restore_original(self):
_lazy.enable_lazy(self._original_value)

View File

@ -15,14 +15,15 @@
from oslotest import base as test_base
import six
from oslo_i18n import _lazy
from oslo_i18n import _message
from oslo_i18n import fixture
class FixtureTest(test_base.BaseTestCase):
class TranslationFixtureTest(test_base.BaseTestCase):
def setUp(self):
super(FixtureTest, self).setUp()
super(TranslationFixtureTest, self).setUp()
self.trans_fixture = self.useFixture(fixture.Translation())
def test_lazy(self):
@ -36,3 +37,38 @@ class FixtureTest(test_base.BaseTestCase):
self.assertFalse(isinstance(msg, _message.Message))
self.assertIsInstance(msg, six.text_type)
self.assertEqual(msg, u'this is a lazy message')
class ToggleLazyFixtureText(test_base.BaseTestCase):
def test_on_on(self):
_lazy.USE_LAZY = True
f = fixture.ToggleLazy(True)
f.setUp()
self.assertTrue(_lazy.USE_LAZY)
f._restore_original()
self.assertTrue(_lazy.USE_LAZY)
def test_on_off(self):
_lazy.USE_LAZY = True
f = fixture.ToggleLazy(False)
f.setUp()
self.assertFalse(_lazy.USE_LAZY)
f._restore_original()
self.assertTrue(_lazy.USE_LAZY)
def test_off_on(self):
_lazy.USE_LAZY = False
f = fixture.ToggleLazy(True)
f.setUp()
self.assertTrue(_lazy.USE_LAZY)
f._restore_original()
self.assertFalse(_lazy.USE_LAZY)
def test_off_off(self):
_lazy.USE_LAZY = False
f = fixture.ToggleLazy(False)
f.setUp()
self.assertFalse(_lazy.USE_LAZY)
f._restore_original()
self.assertFalse(_lazy.USE_LAZY)