Use '__getinitargs__' to provide unpickling-only defaults.

This commit is contained in:
Tres Seaver
2013-05-17 17:04:13 -04:00
parent ad49324573
commit 6df3254d83
3 changed files with 32 additions and 11 deletions

View File

@@ -30,3 +30,8 @@ try:
except NameError: # pragma: no cover
xrange = range
try:
from cPickle import loads, dumps, HIGHEST_PROTOCOL
except ImportError: # pragma: no cover
from pickle import loads, dumps, HIGHEST_PROTOCOL

View File

@@ -69,10 +69,15 @@ class FixedOffset(tzinfo):
"""Fixed offset in hours and minutes from UTC
"""
def __init__(self, offset_hours=0, offset_minutes=0, name='unknown'):
def __init__(self, offset_hours, offset_minutes, name):
self.__offset = timedelta(hours=offset_hours, minutes=offset_minutes)
self.__name = name
def __getinitargs__(self):
# tzinfo.__reduce__ returns the type as the factory: supply
# defaults here, rather than in __init__.
return 0, 0, 'unknown'
def utcoffset(self, dt):
return self.__offset

View File

@@ -23,21 +23,21 @@ class Test_Utc(unittest.TestCase):
result = inst.dst(None)
self.assertEqual(result, ZERO)
def test_picklability(self):
from ..iso8601 import ZERO
from ..compat import loads, dumps, HIGHEST_PROTOCOL
inst = self._makeOne()
for protocol in range(HIGHEST_PROTOCOL + 1):
inst2 = loads(dumps(inst, protocol))
self.assertEqual(inst2.utcoffset(None), ZERO)
self.assertEqual(inst2.tzname(None), 'UTC')
self.assertEqual(inst2.dst(None), ZERO)
class Test_FixedOffset(unittest.TestCase):
def _makeOne(self):
from ..iso8601 import FixedOffset
return FixedOffset(1, 30, 'oneandahalf')
def test_ctor_defaults(self):
# Ensure that instances can be unpickled on Py3k
from ..iso8601 import FixedOffset
NOW = datetime.datetime.now()
ZULU = datetime.timedelta(0, 0)
inst = FixedOffset()
self.assertEqual(inst.tzname(NOW), 'unknown')
self.assertEqual(inst.utcoffset(NOW), ZULU)
self.assertEqual(inst.dst(NOW), ZULU)
def test_utcoffset(self):
inst = self._makeOne()
result = inst.utcoffset(None)
@@ -54,6 +54,17 @@ class Test_FixedOffset(unittest.TestCase):
result = inst.dst(None)
self.assertEqual(result, ZERO)
def test_picklability(self):
from ..iso8601 import ZERO
from ..compat import loads, dumps, HIGHEST_PROTOCOL
inst = self._makeOne()
for protocol in range(HIGHEST_PROTOCOL + 1):
inst2 = loads(dumps(inst, protocol))
self.assertEqual(inst2.utcoffset(None),
datetime.timedelta(hours=1, minutes=30))
self.assertEqual(inst2.tzname(None), 'oneandahalf')
self.assertEqual(inst2.dst(None), ZERO)
def test___repr__(self):
inst = self._makeOne()
result = inst.__repr__()