Coverage for /home/runner/work/viur-core/viur-core/viur/src/viur/core/bones/select.py: 23%

66 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-27 07:59 +0000

1import enum 

2import typing as t 

3from collections import OrderedDict 

4from numbers import Number 

5from viur.core.config import conf 

6from viur.core.bones.base import BaseBone, ReadFromClientError, ReadFromClientErrorSeverity 

7from viur.core.i18n import translate 

8 

9if t.TYPE_CHECKING: 9 ↛ 10line 9 didn't jump to line 10 because the condition on line 9 was never true

10 from viur.core.skeleton import SkeletonInstance 

11 

12SelectBoneValue = t.Union[str, Number, enum.Enum] 

13""" 

14Type alias of possible values in a SelectBone. SelectBoneValue can be either a string (str) or a number (Number) 

15""" 

16 

17SelectBoneMultiple = list[SelectBoneValue] 

18"""Type alias for values of a multiple SelectBone.""" 

19 

20 

21def translation_key_prefix_skeleton_bonename(bones_instance: BaseBone) -> str: 

22 """Generate a translation key prefix based on the skeleton and bone name""" 

23 return f'skeleton.{bones_instance.skel_cls.__name__.lower().removesuffix("skel")}.{bones_instance.name}.' 

24 

25 

26def translation_key_prefix_bonename(bones_instance: BaseBone) -> str: 

27 """Generate a translation key prefix based on the bone name""" 

28 return f'bone.{bones_instance.name}.' 

29 

30 

31class SelectBone(BaseBone): 

32 """ 

33 A SelectBone is a bone which can take a value from a certain list of values. 

34 Inherits from the BaseBone class. The `type` attribute is set to "select". 

35 """ 

36 type = "select" 

37 

38 def __init__( 

39 self, 

40 *, 

41 defaultValue: t.Union[ 

42 SelectBoneValue, 

43 SelectBoneMultiple, 

44 t.Dict[str, t.Union[SelectBoneMultiple, SelectBoneValue]], 

45 t.Callable[["SkeletonInstance", t.Self], t.Any], 

46 ] = None, 

47 values: dict | list | tuple | t.Callable | enum.EnumMeta = (), 

48 translation_key_prefix: str | t.Callable[[t.Self], str] = "", 

49 **kwargs 

50 ): 

51 """ 

52 Initializes a new SelectBone. 

53 

54 :param defaultValue: key(s) of the values which will be checked by default. 

55 :param values: dict of key->value pairs from which the user can choose from 

56 -- or a callable that returns a dict. 

57 :param translation_key_prefix: A prefix for the key of the translation object. 

58 It is empty by default, so that only the label (dict value) from the values is used. 

59 A static string or dynamic method can be used (like `translation_key_prefix_bonename`). 

60 :param kwargs: Additional keyword arguments that will be passed to the superclass' __init__ method. 

61 """ 

62 super().__init__(defaultValue=defaultValue, **kwargs) 

63 self.translation_key_prefix = translation_key_prefix 

64 

65 # handle list/tuple as dicts 

66 if isinstance(values, (list, tuple)): 

67 values = {value: value for value in values} 

68 

69 assert isinstance(values, (dict, OrderedDict)) or callable(values) 

70 self._values = values 

71 

72 def __getattribute__(self, item): 

73 """ 

74 Overrides the default __getattribute__ method to handle the 'values' attribute dynamically. If the '_values' 

75 attribute is callable, it will be called and the result will be stored in the 'values' attribute. 

76 

77 :param str item: The attribute name. 

78 :return: The value of the specified attribute. 

79 

80 :raises AssertionError: If the resulting values are not of type dict or OrderedDict. 

81 """ 

82 if item == "values": 

83 values = self._values 

84 if isinstance(values, enum.EnumMeta): 

85 values = {value.value: value.name for value in values} 

86 elif callable(values): 

87 values = values() 

88 

89 # handle list/tuple as dicts 

90 if isinstance(values, (list, tuple)): 

91 values = {value: value for value in values} 

92 

93 assert isinstance(values, (dict, OrderedDict)) 

94 

95 prefix = self.translation_key_prefix 

96 if callable(prefix): 

97 prefix = prefix(self) 

98 

99 values = { 

100 key: label if isinstance(label, translate) else translate( 

101 f"{prefix}{label}", str(label), 

102 f"value {key} for {self.name}<{type(self).__name__}> in {self.skel_cls.__name__} in {self.skel_cls}" 

103 ) 

104 for key, label in values.items() 

105 } 

106 

107 return values 

108 

109 return super().__getattribute__(item) 

110 

111 def singleValueUnserialize(self, val): 

112 if isinstance(self._values, enum.EnumMeta): 

113 for value in self._values: 

114 if value.value == val: 

115 return value 

116 return val 

117 

118 def singleValueSerialize(self, val, skel: 'SkeletonInstance', name: str, parentIndexed: bool): 

119 if isinstance(self._values, enum.EnumMeta) and isinstance(val, self._values): 

120 return val.value 

121 return val 

122 

123 def singleValueFromClient(self, value, skel, bone_name, client_data): 

124 if isinstance(self._values, enum.EnumMeta) and isinstance(value, self._values): 

125 return value, None 

126 

127 value = str(value) 

128 if not value: 

129 return self.getEmptyValue(), [ReadFromClientError(ReadFromClientErrorSeverity.Empty, "No value selected")] 

130 

131 for key in self.values.keys(): 

132 if str(key) == value: 

133 if isinstance(self._values, enum.EnumMeta): 

134 return self._values(key), None 

135 

136 return key, None 

137 

138 return self.getEmptyValue(), [ 

139 ReadFromClientError(ReadFromClientErrorSeverity.Invalid, "Invalid value selected") 

140 ] 

141 

142 def structure(self) -> dict: 

143 return super().structure() | { 

144 "values": 

145 {k: str(v) for k, v in self.values.items()} # new-style dict 

146 if "bone.select.structure.values.keytuple" not in conf.compatibility 

147 else [(k, str(v)) for k, v in self.values.items()] # old-style key-tuple 

148 }