Coverage for backend/django/Economics/shared/serializer_base.py: 94%

25 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2026-07-22 05:22 +0000

1from rest_framework import serializers 

2 

3from core.serializer_base import StateOwnedModelSerializer 

4from core.validation import get_current_flowsheet 

5 

6 

7def _current_flowsheet_id() -> int | None: 

8 context = get_current_flowsheet() or {} 

9 flowsheet_id = context.get("flowsheet") 

10 return int(flowsheet_id) if flowsheet_id is not None else None 

11 

12 

13def _current_flowsheet_state_id() -> int | None: 

14 context = get_current_flowsheet() or {} 

15 state_id = context.get("flowsheet_state") 

16 return int(state_id) if state_id is not None else None 

17 

18 

19def _validate_same_flowsheet_state( 

20 instance, 

21 field_name: str, 

22 flowsheet_state_id: int | None, 

23) -> None: 

24 if ( 24 ↛ 29line 24 didn't jump to line 29 because the condition on line 24 was never true

25 instance is not None 

26 and flowsheet_state_id is not None 

27 and instance.flowsheet_state_id != flowsheet_state_id 

28 ): 

29 raise serializers.ValidationError( 

30 {field_name: "Referenced row must belong to the active flowsheet state."} 

31 ) 

32 

33 

34class FlowsheetScopedSerializer(StateOwnedModelSerializer): 

35 """Serializer base that validates user-provided relations against request flowsheet context.""" 

36 

37 same_flowsheet_fields: tuple[str, ...] = () 

38 

39 def validate(self, attrs): 

40 attrs = super().validate(attrs) 

41 flowsheet_state_id = _current_flowsheet_state_id() 

42 for field_name in self.same_flowsheet_fields: 

43 value = attrs.get(field_name) 

44 if value is None and self.instance is not None: 

45 value = getattr(self.instance, field_name, None) 

46 _validate_same_flowsheet_state(value, field_name, flowsheet_state_id) 

47 return attrs