Skip to content

Commit

Permalink
Add support for special method get_cache_key on objects
Browse files Browse the repository at this point in the history
  • Loading branch information
rcmachado committed Sep 17, 2012
1 parent a27716f commit a52ab7c
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
Empty file added tests/cache/__init__.py
Empty file.
66 changes: 66 additions & 0 deletions tests/cache/test_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# coding: utf-8
from torneira.cache.util import cache_key, cached

from tests.util import unittest


class MySimpleObject(object):
@cached
def do_something(self, a, b):
return a + b


class MyModel(object):
id = None

def __init__(self, id_):
self.id = id_

@cached
def do_something(self, a, b):
return a + b


class ObjectWithSpecialMethod(object):
# just to ensure that cache_key will not use this value
id = 'should-not-be-used'
_my_value = None

def __init__(self, value):
self._my_value = value

def get_cache_key(self):
return self._my_value

@cached
def do_something(a, b):
return a + b


class GenerateCacheKeyTestCase(unittest.TestCase):
def test_generate_cache_key_for_simple_object(self):
my_instance = MySimpleObject()

fn_kwargs = {'a': 1, 'b': 2}
_, generated_key = cache_key(my_instance, 'do_something', **fn_kwargs)
expected_key = 'tests.cache.test_extension.MySimpleObject().do_something(a=1,b=2)'

self.assertEqual(generated_key, expected_key)

def test_generate_cache_key_for_model_object(self):
my_instance = MyModel("unique-id-1")

fn_kwargs = {'a': 1, 'b': 2}
_, generated_key = cache_key(my_instance, 'do_something', **fn_kwargs)
expected_key = 'tests.cache.test_extension.MyModel(unique-id-1).do_something(a=1,b=2)'

self.assertEqual(generated_key, expected_key)

def test_generate_cache_key_for_object_with_special_method(self):
my_instance = ObjectWithSpecialMethod('unique-value')

fn_kwargs = {'a': 1, 'b': 2}
_, generated_key = cache_key(my_instance, 'do_something', **fn_kwargs)
expected_key = 'tests.cache.test_extension.ObjectWithSpecialMethod(unique-value).do_something(a=1,b=2)'

self.assertEqual(generated_key, expected_key)
4 changes: 3 additions & 1 deletion torneira/cache/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ def cache_key(instance, method, **kwarguments):
cachekey = cachekey.replace("{classe}", instance.__class__.__name__)
cachekey = cachekey.replace("{method}", method)

if hasattr(instance, "id") and instance.id:
if hasattr(instance, "get_cache_key"):
cachekey = cachekey.replace("{instanceid}", str(instance.get_cache_key()))
elif hasattr(instance, "id") and instance.id:
cachekey = cachekey.replace("{instanceid}", "%s" % instance.id)
else:
cachekey = cachekey.replace("{instanceid}", "")
Expand Down

0 comments on commit a52ab7c

Please sign in to comment.