Coverage for Users/vladimirpavlov/PycharmProjects/parameterizable/tests/test_cacheable_properties_mixin_get_single.py: 96%

1 from functools import cached_property

2 from mixinforge import CacheablePropertiesMixin

3 import pytest

4

5 class A(CacheablePropertiesMixin):

6 @cached_property

7 def x(self):

8 return 1

9

10 @cached_property

11 def y(self):

12 return 2

13

14 @property

15 def z(self):

16 return 3

17

18 def regular_method(self):

19 pass

20

21 def test_get_cached_property_basic():

22 """Test that _get_cached_property() retrieves cached values by name."""

23 a = A()

24 _ = a.x

25 _ = a.y

26

27 assert a._get_cached_property("x") == 1

28 assert a._get_cached_property("y") == 2

29

30 def test_get_cached_property_not_cached_yet():

31 """Test that _get_cached_property() raises KeyError for uncached properties."""

32 a = A()

33 # x exists as a cached_property but hasn't been accessed yet

34 with pytest.raises(KeyError, match="has not been computed yet"):

35 a._get_cached_property("x")

36

37 # After caching, it should work

38 _ = a.x

39 assert a._get_cached_property("x") == 1

40

41 def test_get_cached_property_invalid_name():

42 """Test that _get_cached_property() raises ValueError for invalid names."""

43 a = A()

44

45 # Non-existent property

46 with pytest.raises(ValueError, match="not a cached property"):

47 a._get_cached_property("invalid_name")

48

49 # Regular @property (not cached_property)

50 with pytest.raises(ValueError, match="not a cached property"):

51 a._get_cached_property("z")

52

53 def test_get_cached_property_inheritance():

54 """Test that _get_cached_property() works with inherited properties."""

55 class Base(CacheablePropertiesMixin):

56 @cached_property

57 def base_prop(self):

58 return "base"

59

60 class Child(Base):

61 @cached_property

62 def child_prop(self):

63 return "child"

64

65 c = Child()

66 _ = c.base_prop

67 _ = c.child_prop

68

69 assert c._get_cached_property("base_prop") == "base"

70 assert c._get_cached_property("child_prop") == "child"

71

72 def test_get_cached_property_after_set():

73 """Test that _get_cached_property() retrieves values set via _set_cached_properties()."""

74 a = A()

75 a._set_cached_properties(x=100, y=200)

76

77 assert a._get_cached_property("x") == 100

78 assert a._get_cached_property("y") == 200