MCPcopy Create free account
hub / github.com/dateutil/dateutil / TZContextBase

Class TZContextBase

tests/_common.py:169–229  ·  view source on GitHub ↗

Base class for a context manager which allows changing of time zones. Subclasses may define a guard variable to either block or or allow time zone changes by redefining ``_guard_var_name`` and ``_guard_allows_change``. The default is that the guard variable must be affirmatively se

Source from the content-addressed store, hash-verified

167
168
169class TZContextBase:
170 """
171 Base class for a context manager which allows changing of time zones.
172
173 Subclasses may define a guard variable to either block or or allow time
174 zone changes by redefining ``_guard_var_name`` and ``_guard_allows_change``.
175 The default is that the guard variable must be affirmatively set.
176
177 Subclasses must define ``get_current_tz`` and ``set_current_tz``.
178 """
179 _guard_var_name = "DATEUTIL_MAY_CHANGE_TZ"
180 _guard_allows_change = True
181
182 def __init__(self, tzval):
183 self.tzval = tzval
184 self._old_tz = None
185
186 @classmethod
187 def tz_change_allowed(cls):
188 """
189 Class method used to query whether or not this class allows time zone
190 changes.
191 """
192 guard = bool(os.environ.get(cls._guard_var_name, False))
193
194 # _guard_allows_change gives the "default" behavior - if True, the
195 # guard is overcoming a block. If false, the guard is causing a block.
196 # Whether tz_change is allowed is therefore the XNOR of the two.
197 return guard == cls._guard_allows_change
198
199 @classmethod
200 def tz_change_disallowed_message(cls):
201 """ Generate instructions on how to allow tz changes """
202 msg = ('Changing time zone not allowed. Set {envar} to {gval} '
203 'if you would like to allow this behavior')
204
205 return msg.format(envar=cls._guard_var_name,
206 gval=cls._guard_allows_change)
207
208 def __enter__(self):
209 if not self.tz_change_allowed():
210 msg = self.tz_change_disallowed_message()
211 pytest.skip(msg)
212
213 # If this is used outside of a test suite, we still want an error.
214 raise ValueError(msg) # pragma: no cover
215
216 self._old_tz = self.get_current_tz()
217 self.set_current_tz(self.tzval)
218
219 def __exit__(self, type, value, traceback):
220 if self._old_tz is not None:
221 self.set_current_tz(self._old_tz)
222
223 self._old_tz = None
224
225 def get_current_tz(self):
226 raise NotImplementedError

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected