Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add bmi tests

Dylan Smithba75480f924f
diff --git a/wger/measurements/api/views.py b/wger/measurements/api/views.py
index b628458d4..4ab4d4f19 100644
--- a/wger/measurements/api/views.py
+++ b/wger/measurements/api/views.py
@@ -37,33 +37,12 @@ from wger.measurements.models import (
Category,
Measurement,
)
+from wger.measurements.utils.bmi import calculate_bmi
from wger.utils.viewsets import WgerOwnerObjectModelViewSet
logger = logging.getLogger(__name__)
-def calculate_bmi(user, category_id):
- from wger.weight.models import WeightEntry
-
- profile = getattr(user, 'userprofile', None)
- if not profile or not profile.height or profile.height <= 0:
- return []
-
- # height_sq will be a float
- height_sq = (profile.height / 100) ** 2
-
- weights = WeightEntry.objects.filter(user=user).order_by('date')
-
- return [
- {
- 'id': w.id, # Use integer IDs so the frontend state manager doesn't complain
- 'category': int(category_id), # Link it to the requested category
- 'date': w.date.isoformat() if hasattr(w.date, 'isoformat') else w.date,
- 'value': round(float(w.weight) / height_sq, 2),
- 'notes': 'Auto-calculated from weight entry'
- }
- for w in weights
- ]
# Map the dynamic_type enum to the math function
DYNAMIC_REGISTRY = {
@@ -71,6 +50,7 @@ DYNAMIC_REGISTRY = {
# add squat 1rm later
}
+
class CategoryViewSet(WgerOwnerObjectModelViewSet):
"""
API endpoint for measurement units
@@ -112,8 +92,7 @@ class CategoryViewSet(WgerOwnerObjectModelViewSet):
URL: /api/v2/measurement-category/dynamic-types/
"""
choices = [
- {"value": choice.value, "label": choice.label}
- for choice in Category.DynamicType
+ {'value': choice.value, 'label': choice.label} for choice in Category.DynamicType
]
return Response(choices)
@@ -155,21 +134,18 @@ class MeasurementViewSet(WgerOwnerObjectModelViewSet):
try:
# look up the category and check its enum value
category = Category.objects.get(id=category_id, user=request.user)
-
+
if category.dynamic_type != Category.DynamicType.NONE:
calc_func = DYNAMIC_REGISTRY.get(category.dynamic_type)
-
+
if calc_func:
# execute the math function and wrap it in the DRF pagination envelope
data = calc_func(request.user, category_id)
- return Response({
- "count": len(data),
- "next": None,
- "previous": None,
- "results": data
- })
+ return Response(
+ {'count': len(data), 'next': None, 'previous': None, 'results': data}
+ )
except (Category.DoesNotExist, ValueError):
# fallback to standard behavior
pass
- return super().list(request, *args, **kwargs)
\ No newline at end of file
+ return super().list(request, *args, **kwargs)
diff --git a/wger/measurements/migrations/0004_category_is_dynamic.py b/wger/measurements/migrations/0004_category_is_dynamic.py
index f5d40d81e..16f7f3ab8 100644
--- a/wger/measurements/migrations/0004_category_is_dynamic.py
+++ b/wger/measurements/migrations/0004_category_is_dynamic.py
@@ -4,7 +4,6 @@ from django.db import migrations, models
class Migration(migrations.Migration):
-
dependencies = [
('measurements', '0003_alter_measurement_unique_together_and_more'),
]
@@ -13,6 +12,10 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='category',
name='is_dynamic',
- field=models.BooleanField(default=False, help_text='Indicates if this category is automatically calculated.', verbose_name='Is Dynamic'),
+ field=models.BooleanField(
+ default=False,
+ help_text='Indicates if this category is automatically calculated.',
+ verbose_name='Is Dynamic',
+ ),
),
]
diff --git a/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.py b/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.py
index e0b3c0dd1..3a129e59e 100644
--- a/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.py
+++ b/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.py
@@ -4,7 +4,6 @@ from django.db import migrations, models
class Migration(migrations.Migration):
-
dependencies = [
('measurements', '0004_category_is_dynamic'),
]
@@ -17,6 +16,11 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='category',
name='dynamic_type',
- field=models.CharField(choices=[('NONE', 'None'), ('BMI', 'Bmi'), ('SQUAT_1RM', 'Squat 1Rm')], db_index=True, default='NONE', max_length=20),
+ field=models.CharField(
+ choices=[('NONE', 'None'), ('BMI', 'Bmi'), ('SQUAT_1RM', 'Squat 1Rm')],
+ db_index=True,
+ default='NONE',
+ max_length=20,
+ ),
),
]
diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.py
index dd001788e..bf57f595f 100644
--- a/wger/measurements/models/category.py
+++ b/wger/measurements/models/category.py
@@ -42,15 +42,12 @@ class Category(models.Model):
)
class DynamicType(models.TextChoices):
- NONE = 'NONE',
- BMI = 'BMI',
+ NONE = ('NONE',)
+ BMI = ('BMI',)
# SQUAT_1RM = 'SQUAT_1RM', can be added in future
dynamic_type = models.CharField(
- max_length=20,
- choices=DynamicType.choices,
- default=DynamicType.NONE,
- db_index=True
+ max_length=20, choices=DynamicType.choices, default=DynamicType.NONE, db_index=True
)
def get_owner_object(self):
diff --git a/wger/measurements/tests/test_dynamic_measurements.py b/wger/measurements/tests/test_dynamic_measurements.py
new file mode 100644
index 000000000..d725f0266
--- /dev/null
+++ b/wger/measurements/tests/test_dynamic_measurements.py
@@ -0,0 +1,62 @@
+# Standard Library
+import unittest
+from unittest.mock import (
+ MagicMock,
+ patch,
+)
+
+# wger
+from wger.measurements.utils.bmi import calculate_bmi
+
+
+class BMILogicTest(unittest.TestCase):
+ """
+ Pure unit test for BMI math logic.
+ Bypasses Django database and wger signals.
+ """
+
+ @patch('wger.weight.models.WeightEntry.objects.filter')
+ def test_calculate_bmi_math(self, mock_filter):
+ user = MagicMock()
+ user.userprofile.height = 180 # 1.8m
+
+ weight_entry = MagicMock()
+ weight_entry.weight = 80.0
+ weight_entry.date = '2026-05-12'
+
+ mock_filter.return_value.order_by.return_value = [weight_entry]
+
+ results = calculate_bmi(user, category_id=99)
+
+ # 80 / (1.8 * 1.8) = 24.69
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]['value'], 24.69)
+ self.assertEqual(results[0]['category'], 99)
+
+ def test_calculate_bmi_missing_height(self):
+ user = MagicMock()
+ user.userprofile.height = None
+
+ results = calculate_bmi(user, category_id=99)
+ self.assertEqual(results, [])
+
+ @patch('wger.weight.models.WeightEntry.objects.filter')
+ def test_calculate_bmi_multiple_entries(self, mock_filter):
+ user = MagicMock()
+ user.userprofile.height = 175 # 1.75m
+
+ w1 = MagicMock(weight=70.0, date='2026-05-01')
+ w2 = MagicMock(weight=75.0, date='2026-05-10')
+
+ mock_filter.return_value.order_by.return_value = [w1, w2]
+
+ results = calculate_bmi(user, category_id=99)
+
+ # 70 / 1.75^2 = 22.86
+ self.assertEqual(results[0]['value'], 22.86)
+ # 75 / 1.75^2 = 24.49
+ self.assertEqual(results[1]['value'], 24.49)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/wger/measurements/utils/__init__.py b/wger/measurements/utils/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/wger/measurements/utils/bmi.py b/wger/measurements/utils/bmi.py
new file mode 100644
index 000000000..8f4e1bc9e
--- /dev/null
+++ b/wger/measurements/utils/bmi.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# 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/>.
+
+
+def calculate_bmi(user, category_id):
+ # wger
+ from wger.weight.models import WeightEntry
+
+ profile = getattr(user, 'userprofile', None)
+ if not profile or not profile.height or profile.height <= 0:
+ return []
+
+ # height_sq will be a float
+ height_sq = (profile.height / 100) ** 2
+
+ weights = WeightEntry.objects.filter(user=user).order_by('date')
+
+ return [
+ {
+ 'id': w.id, # Use integer IDs so the frontend state manager doesn't complain
+ 'category': int(category_id), # Link it to the requested category
+ 'date': w.date.isoformat() if hasattr(w.date, 'isoformat') else w.date,
+ 'value': round(float(w.weight) / height_sq, 2),
+ 'notes': 'Auto-calculated from weight entry',
+ }
+ for w in weights
+ ]