def test_cached_property_slot_wrong_type_set(self): """apply a cached property from one type to another""" class C: __slots__ = ("abc", ) class D: pass D.abc = cached_property(lambda self: 42, C.abc) a = D() with self.assertRaises(TypeError): print(a.abc)
def test_cached_property_slot(self): class C: __slots__ = ("f", "calls") def __init__(self): self.calls = 0 def f(self): self.calls += 1 return 42 C.f = cached_property(f, C.f) a = C() self.assertEqual(a.f, 42) self.assertEqual(a.calls, 1) self.assertEqual(a.f, 42) self.assertEqual(a.calls, 1)
def test_cached_property_slot_set_del(self): class C: __slots__ = ("f", "calls") def __init__(self): self.calls = 0 def f(self): self.calls += 1 return 42 C.f = cached_property(f, C.f) a = C() a.f = 100 self.assertEqual(a.f, 100) self.assertEqual(a.calls, 0) del a.f with self.assertRaises(AttributeError): del a.f self.assertEqual(a.f, 42) self.assertEqual(a.calls, 1)
def test_cached_property_readonly_descriptor(self): with self.assertRaises(TypeError): cached_property(lambda self: 42, range.start)
def test_cached_property_incompatible_descriptor(self): with self.assertRaises(TypeError): cached_property(lambda self: 42, GeneratorType.gi_frame)
def test_cached_property_non_descriptor(self): with self.assertRaises(TypeError): cached_property(lambda self: 42, 42)