Self hosted FLOSS fitness/workout, nutrition and weight tracker
Reject negative and non-finite ingredient nutrients
Luke Gabriel R. Arrietaa5cb14be4b72
diff --git a/wger/nutrition/dataclasses.py b/wger/nutrition/dataclasses.pyindex 08cafab8a..938f8a9d8 100644--- a/wger/nutrition/dataclasses.py+++ b/wger/nutrition/dataclasses.py@@ -18,6 +18,7 @@ from dataclasses import (dataclass,)from decimal import Decimal+from math import isfinite# wgerfrom wger.nutrition.consts import (@@ -93,8 +94,16 @@ class IngredientData:# TypeError escape and abort the whole import run.for field in ['energy'] + macros:value = getattr(self, field)- if value is not None and not isinstance(value, (int, float, Decimal)):+ if value is None:+ continue+ if not isinstance(value, (int, float, Decimal)):raise ValueError(f'Value for {field} is not a number: {value!r}')+ if (isinstance(value, float) and not isfinite(value)) or (+ isinstance(value, Decimal) and not value.is_finite()+ ):+ raise ValueError(f'Value for {field} is not finite: {value}')+ if value < 0:+ raise ValueError(f'Value for {field} is negative: {value}')for macro in macros:value = getattr(self, macro)diff --git a/wger/nutrition/tests/test_dataclass.py b/wger/nutrition/tests/test_dataclass.pyindex edcc0def4..5cb300732 100644--- a/wger/nutrition/tests/test_dataclass.py+++ b/wger/nutrition/tests/test_dataclass.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+from dataclasses import replace+from decimal import Decimal+# Djangofrom django.test import SimpleTestCase@@ -21,6 +25,18 @@ from wger.nutrition.dataclasses import IngredientDatafrom wger.utils.constants import CC_0_LICENSE_ID+NUTRIENT_FIELDS = (+ 'energy',+ 'protein',+ 'carbohydrates',+ 'carbohydrates_sugar',+ 'fat',+ 'fat_saturated',+ 'fiber',+ 'sodium',+)++class IngredientDataclassTestCase(SimpleTestCase):"""Test validation rules@@ -56,6 +72,45 @@ class IngredientDataclassTestCase(SimpleTestCase):"""Test that the validation proceeds with correct data"""self.assertEqual(self.ingredient_data.sanity_checks(), None)+ def test_validation_negative_nutrients(self):+ """Reject negatives even when the energy plausibility check is skipped."""+ baseline = replace(self.ingredient_data, **dict.fromkeys(NUTRIENT_FIELDS, 0))+ for field in NUTRIENT_FIELDS:+ for value in (-1, -1.0, Decimal('-1')):+ with self.subTest(field=field, value=value, number_type=type(value)):+ ingredient = replace(baseline, **{field: value})+ with self.assertRaisesRegex(ValueError, field):+ ingredient.sanity_checks()++ def test_validation_non_finite_nutrients(self):+ """Reject NaN and infinities before comparisons or energy calculations."""+ values = (+ float('nan'),+ float('inf'),+ float('-inf'),+ Decimal('NaN'),+ Decimal('sNaN'),+ Decimal('Infinity'),+ Decimal('-Infinity'),+ )+ baseline = replace(self.ingredient_data, **dict.fromkeys(NUTRIENT_FIELDS, 0))+ for field in NUTRIENT_FIELDS:+ for value in values:+ with self.subTest(field=field, value=value, number_type=type(value)):+ ingredient = replace(baseline, **{field: value})+ with self.assertRaisesRegex(ValueError, field):+ ingredient.sanity_checks()++ def test_validation_zero_nutrients(self):+ """Zero remains valid for every supported numeric type."""+ for number_type in (int, float, Decimal):+ with self.subTest(number_type=number_type):+ ingredient = replace(+ self.ingredient_data,+ **dict.fromkeys(NUTRIENT_FIELDS, number_type(0)),+ )+ self.assertIsNone(ingredient.sanity_checks())+def test_validation_bigger_100(self):"""Test the validation for values bigger than 100diff --git a/wger/nutrition/tests/test_sync_bulk.py b/wger/nutrition/tests/test_sync_bulk.pyindex fb1721090..1d36562da 100644--- a/wger/nutrition/tests/test_sync_bulk.py+++ b/wger/nutrition/tests/test_sync_bulk.py@@ -281,6 +281,40 @@ class TestSyncIngredientsFromDump(WgerTestCase):finally:Path(file_path).unlink()+ def test_insert_mode_skips_negative_nutrients(self):+ """Invalid nutrients do not enter the bulk insert or block valid records."""+ bad_entry = {+ **SAMPLE_INGREDIENTS[0],+ 'uuid': 'baaaaaad-0000-0000-0000-000000000001',+ 'sodium': '-1.000',+ }+ file_path = self._create_dump_file([bad_entry, SAMPLE_INGREDIENTS[1]])+ self.addCleanup(Path(file_path).unlink)++ count = sync_ingredients_from_dump(lambda x: x, file_path, mode=SyncMode.INSERT)++ self.assertEqual(count, 1)+ self.assertFalse(Ingredient.objects.filter(uuid=bad_entry['uuid']).exists())+ valid_ingredient = Ingredient.objects.get(uuid=SAMPLE_INGREDIENTS[1]['uuid'])+ self.assertEqual(valid_ingredient.sodium, Decimal('0.820'))++ def test_update_mode_skips_negative_nutrients(self):+ """An invalid update preserves existing data and the next record imports."""+ ingredient = Ingredient.objects.get(uuid=SAMPLE_INGREDIENTS[0]['uuid'])+ original_name, original_sodium = ingredient.name, ingredient.sodium+ bad_entry = {**SAMPLE_INGREDIENTS[0], 'sodium': '-1.000'}+ file_path = self._create_dump_file([bad_entry, SAMPLE_INGREDIENTS[1]])+ self.addCleanup(Path(file_path).unlink)++ count = sync_ingredients_from_dump(lambda x: x, file_path, mode=SyncMode.UPDATE)++ self.assertEqual(count, 1)+ ingredient.refresh_from_db()+ self.assertEqual(ingredient.name, original_name)+ self.assertEqual(ingredient.sodium, original_sodium)+ valid_ingredient = Ingredient.objects.get(uuid=SAMPLE_INGREDIENTS[1]['uuid'])+ self.assertEqual(valid_ingredient.sodium, Decimal('0.820'))+def test_handles_plain_jsonl(self):"""Test that import works with plain (non-gzipped) JSONL files."""file_path = self._create_dump_file(use_gzip=False)