1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
"""
test_memoized_property
----------------------
Tests of the `memoized_property` module.
"""
import unittest
from memoized_property import memoized_property
class C(object):
"""Example class for testing ``@memoized_property``"""
load_name_count = 0
@memoized_property
def name(self):
"name's docstring"
self.load_name_count += 1
return "the name"
class TestMemoizedProperty(unittest.TestCase):
"""
Tests of the ``memoized_property`` decorator.
"""
def setUp(self):
self.instance = C()
def test_property_not_accessed_not_loaded(self):
"""
When a memoized property has not been accessed, the decorated loading function should not
have been called.
"""
self.assertEqual(0, self.instance.load_name_count)
def test_property_not_accessed_no_private_attribute(self):
"""
When a memoized property has not been accessed, it should not have a private attribute for
storing the result of a load.
"""
self.assertFalse(hasattr(self.instance, '_name'))
def test_property_accessed_loaded(self):
"""
When a memoized property has been accessed, the decorated loading function should have been
called once.
"""
self.instance.name
self.assertEqual(1, self.instance.load_name_count)
def test_property_accessed_private_attribute(self):
"""
When a memoized property has been accessed, it should have a private attribute for storing
the result of a load.
"""
self.instance.name
self.assertTrue(hasattr(self.instance, '_name'))
def test_property_multiple_accesses_one_load(self):
"""
When a memoized property has been accessed multiple times, the decorated loading function
should have been called only once.
"""
self.instance.name
self.instance.name
self.assertEqual(1, self.instance.load_name_count)
def test_property_docstring(self):
"""
A memoized property should expose the docstring of the underlying load function (the fget).
"""
self.assertEqual("name's docstring", C.name.__doc__)
if __name__ == '__main__':
unittest.main()
|