Skip to content

Commit

Permalink
Fix #40: Allow pickling of simple cache instances.
Browse files Browse the repository at this point in the history
  • Loading branch information
tkem committed Jun 17, 2015
1 parent 7bc51c6 commit 70faa29
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
7 changes: 6 additions & 1 deletion cachetools/ttl.py
Expand Up @@ -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."""
Expand Down
14 changes: 14 additions & 0 deletions tests/__init__.py
Expand Up @@ -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):

Expand Down
6 changes: 6 additions & 0 deletions tests/test_rr.py
@@ -1,4 +1,5 @@
import random
import sys
import unittest

from cachetools import RRCache, rr_cache
Expand Down Expand Up @@ -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)

0 comments on commit 70faa29

Please sign in to comment.