A simple cache of values in the property decorator. Read only. Note that it keeps caching until the object is deleted.
def cached_ro_property(f):
cache = [None]
def _cached_ro_property(*args, **kargs):
if cache[0]:
return cache[0]
cache[0] = f(*args, **kargs)
return cache[0]
return property(_cached_ro_property)
from django.test import TestCase
import mox
class TestCachedRoProperty(TestCase):
"""Test for cached_ro_property decorator."""
def setUp(self):
self.m = mox.Mox()
def tearDown(self):
self.m.UnsetStubs()
self.m = None
def test_call_1(self):
"""Simple call."""
from decorators import cached_ro_property
# Procuder function that should be called once.
producer = self.m.CreateMockAnything()
producer().AndReturn(30)
class C(object):
@cached_ro_property
def f(self):
return producer()
self.m.ReplayAll()
c = C()
self.assertEqual(c.f, 30)
self.assertEqual(c.f, 30)
self.m.VerifyAll()
def test_call_2(self):
"""Check that property function reference self."""
from decorators import cached_ro_property
# Procuder function that should be called once.
producer = self.m.CreateMockAnything()
producer().AndReturn(30)
class C(object):
@cached_ro_property
def f(self):
return self.g()
def g(self):
return producer()
self.m.ReplayAll()
c = C()
self.assertEqual(c.f, 30)
self.assertEqual(c.f, 30)
self.m.VerifyAll()