diff --git a/cachetools/ttl.py b/cachetools/ttl.py index 73c545a..b41593e 100644 --- a/cachetools/ttl.py +++ b/cachetools/ttl.py @@ -49,9 +49,14 @@ def __call__(self): return self.__time def __getattr__(self, name): - # FIXME: for unittests timer.tick() return getattr(self.__timer, name) + def __getstate__(self): + return (self.__timer, self.__nesting) + + def __setstate__(self, state): + self.__timer, self.__nesting = state + class TTLCache(Cache): """LRU Cache implementation with per-item time-to-live (TTL) value.""" diff --git a/tests/__init__.py b/tests/__init__.py index 2026b27..4aa41c3 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -202,6 +202,20 @@ def test_cache_getsizeof(self): self.assertEqual(3, cache.currsize) self.assertEqual(3, cache[3]) + def test_cache_pickle(self): + import pickle + import sys + + cache = self.cache(maxsize=2) + cache.update({1: 1, 2: 2}) + if sys.version_info < (3, 0): + cache = pickle.loads(pickle.dumps(cache, -1)) + else: + cache = pickle.loads(pickle.dumps(cache)) + self.assertEqual(2, len(cache)) + self.assertEqual(1, cache[1]) + self.assertEqual(2, cache[2]) + class DecoratorTestMixin(object): diff --git a/tests/test_rr.py b/tests/test_rr.py index b6d2f2c..229a433 100644 --- a/tests/test_rr.py +++ b/tests/test_rr.py @@ -1,4 +1,5 @@ import random +import sys import unittest from cachetools import RRCache, rr_cache @@ -40,3 +41,8 @@ def test_choice(self): self.assertEqual(3, cache[3]) self.assertEqual(4, cache[4]) self.assertNotIn(0, cache) + + # random.choice cannot be pickled... + @unittest.skipIf(sys.version_info < (3, 0), 'not supported for Python < 3') + def test_cache_pickle(self): + CacheTestMixin.test_cache_pickle(self)