Self hosted FLOSS fitness/workout, nutrition and weight tracker
Only convert between kg and lb
Roland Geidere2efe122acd5
diff --git a/wger/measurements/models/measurement.py b/wger/measurements/models/measurement.pyindex 0dd603928..59b32d290 100644--- a/wger/measurements/models/measurement.py+++ b/wger/measurements/models/measurement.py@@ -123,10 +123,15 @@ class Measurement(models.Model):def value_in(self, unit: str) -> Decimal:"""- Returns the value converted to the given weight unit ('kg' or 'lb')+ Returns the value converted to the given weight unit ('kg' or 'lb').++ Only body weight entries carry convertible units, all other metric+ types have a fixed unit."""if self.unit == unit:return self.value+ if unit not in ('kg', 'lb') or self.unit not in ('kg', 'lb'):+ raise ValueError(f'Cannot convert between {self.unit} and {unit}')weight = AbstractWeight(self.value, self.unit)return (weight.kg if unit == 'kg' else weight.lb).quantize(TWOPLACES)diff --git a/wger/measurements/powersync.py b/wger/measurements/powersync.pyindex d0f2d7988..e4f20e540 100644--- a/wger/measurements/powersync.py+++ b/wger/measurements/powersync.py@@ -13,6 +13,10 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+# Standard Library+import json+from typing import Any+# wgerfrom wger.measurements.api.serializers import (CategorySerializer,@@ -62,6 +66,18 @@ class MeasurementHandler(PowerSyncHandler):viewset_class = MeasurementViewSetuser_filter = 'category__user_id'+ def preprocess_payload(self, payload: dict[str, Any]) -> dict[str, Any]:+ # PowerSync clients store JSON columns as text; decode before+ # validation. Malformed JSON is passed through unchanged so the+ # serializer rejects it visibly.+ extra_data = payload.get('extra_data')+ if isinstance(extra_data, str):+ try:+ payload['extra_data'] = json.loads(extra_data) if extra_data else {}+ except ValueError:+ pass+ return payload+def create_save_kwargs(self, payload, user_id):# Ownership is enforced through the category FK, not via a direct# user_id on the Measurement row.diff --git a/wger/measurements/tests/test_measurements.py b/wger/measurements/tests/test_measurements.pyindex 33ca7a928..a824e4c58 100644--- a/wger/measurements/tests/test_measurements.py+++ b/wger/measurements/tests/test_measurements.py@@ -154,6 +154,17 @@ class MeasurementUnitTestCase(WgerTestCase):entry.extra_data = {'unit': 'lb'}self.assertEqual(entry.value_in('kg'), Decimal('34.93'))+ def test_value_in_rejects_other_units(self):+ """+ Test that only weight units can be converted+ """+ # a measurement in the 'Biceps' category of user 'test', unit cm+ entry = Measurement.objects.get(pk='dddddddd-dddd-dddd-dddd-000000000001')++ self.assertEqual(entry.value_in('cm'), entry.value)+ with self.assertRaises(ValueError):+ entry.value_in('kg')+class MeasurementExtraDataApiTestCase(WgerTestCase):"""diff --git a/wger/measurements/tests/test_powersync.py b/wger/measurements/tests/test_powersync.pyindex eb1c72de9..2640b4c5d 100644--- a/wger/measurements/tests/test_powersync.py+++ b/wger/measurements/tests/test_powersync.py@@ -12,6 +12,9 @@## You should have received a copy of the GNU Affero General Public License+# Third Party+from rest_framework import status+# wgerfrom wger.core.tests import powersync_base_testfrom wger.measurements.models import (@@ -75,3 +78,30 @@ class MeasurementPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase}fk_ownership = (('category', CATEGORY_OTHER_UUID),)++ def test_create_decodes_extra_data_string(self):+ """+ PowerSync clients store JSON columns as text; the handler decodes the+ string before validation+ """+ self.authenticate()+ payload = {**self.create_payload, 'extra_data': '{"unit": "kg"}'}+ response = self.push('PUT', payload)++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.json(), {'status': 'ok!'})+ measurement = Measurement.objects.get(pk=payload['id'])+ self.assertEqual(measurement.extra_data, {'unit': 'kg'})++ def test_create_rejects_malformed_extra_data(self):+ """+ A malformed JSON string passes through undecoded and is rejected by the+ serializer instead of crashing the handler+ """+ self.authenticate()+ payload = {**self.create_payload, 'extra_data': '{not json'}+ response = self.push('PUT', payload)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json().get('error'), response.content)+ self.assertFalse(Measurement.objects.filter(pk=payload['id']).exists())