Self hosted FLOSS fitness/workout, nutrition and weight tracker
Stamp body weight entries with the unit they were written in
Roland Geider952b4a6e3dfd
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex 32cfa28a8..6c061be53 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -424,6 +424,23 @@ class MeasurementSerializer(serializers.ModelSerializer):unit = (self.instance.extra_data or {}).get('unit')return limits_for(category.metric_type, unit or category.unit)+ def create(self, validated_data):+ """+ Stamps a body weight entry with the unit it was written in.++ The unit of that category is switchable and an entry without a stamp+ reads through to it, so a switch would change what the stored number+ means. Body weight is the only type this applies to, its values are+ the only ones converted on read.+ """+ category = validated_data.get('category')+ if category is not None and category.metric_type == MetricType.BODY_WEIGHT:+ extra_data = dict(validated_data.get('extra_data') or {})+ extra_data.setdefault('unit', category.unit)+ validated_data['extra_data'] = extra_data++ return super().create(validated_data)+class DynamicTypeSerializer(serializers.Serializer):"""diff --git a/wger/measurements/tests/test_measurements.py b/wger/measurements/tests/test_measurements.pyindex fc5934094..33cdde0fc 100644--- a/wger/measurements/tests/test_measurements.py+++ b/wger/measurements/tests/test_measurements.py@@ -413,6 +413,41 @@ class MeasurementExtraDataApiTestCase(WgerTestCase):self.assertEqual(response.data['extra_data'], {'unit': 'lb'})self.assertEqual(Measurement.objects.get(pk=response.data['id']).unit, 'lb')+ def test_body_weight_entry_is_stamped_with_the_category_unit(self):+ """+ Test that a body weight entry written without a unit gets one+ """+ response = self.client.post(+ self.url,+ {+ 'category': 'cccccccc-cccc-cccc-cccc-0000000000b0',+ 'date': '2023-05-01T12:00:00Z',+ 'value': 77,+ },+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 201)+ self.assertEqual(response.data['extra_data'], {'unit': 'kg'})++ def test_entry_of_another_type_is_not_stamped(self):+ """+ Test that only body weight is stamped, elsewhere an absent unit means+ the category unit applies+ """+ response = self.client.post(+ self.url,+ {+ 'category': 'cccccccc-cccc-cccc-cccc-000000000001',+ 'date': '2023-05-01T12:00:00Z',+ 'value': 42,+ },+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 201)+ self.assertEqual(response.data['extra_data'], {})+def test_extra_data_size_bound(self):"""Test that an oversized extra_data blob is refused