Self hosted FLOSS fitness/workout, nutrition and weight tracker
feat(manager): double progression via max_* requirement rules + all_sets
Ben Tucker59a4c235cfa4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c9f42413..4833fb6a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@### Sync with Apple Health and Health ConnectThe mobile app can now import your body metrics from Apple Health (iOS) and Health Connect (Android). Once enabled in the settings, the data your smart scale, blood pressure monitor, smartwatch or what other health apps record is imported automatically and shows up alongside your manually entered entries. At the moment we support these:+### Double progression support+Progression requirements can now reference the top of the prescribed range via the new rules `max_repetitions` and `max_weight`, and the new `all_sets` flag requires every prescribed set to qualify. Together they enable classic double progression schemes ("work from 8 to 12 reps at a fixed weight, add weight only once all sets reach 12"), e.g. `{"rules": ["max_repetitions"], "all_sets": true}`.+- body weight- body fatdiff --git a/wger/manager/api/validators.py b/wger/manager/api/validators.pyindex 207baaa5d..a0ea16255 100644--- a/wger/manager/api/validators.py+++ b/wger/manager/api/validators.py@@ -24,6 +24,11 @@ REQUIREMENTS_REQUIRED_KEYS = ['rules',]+REQUIREMENTS_ALLOWED_KEYS = {+ 'rules',+ 'all_sets',+}+def validate_requirements(value: dict | None):"""Validates the requirements field."""@@ -37,9 +42,16 @@ def validate_requirements(value: dict | None):if not all(key in value for key in REQUIREMENTS_REQUIRED_KEYS):raise serializers.ValidationError("Missing required keys: 'rules'")+ unknown_keys = set(value) - REQUIREMENTS_ALLOWED_KEYS+ if unknown_keys:+ raise serializers.ValidationError(f'Unknown keys: {sorted(unknown_keys)}')+if 'rules' in value and not isinstance(value['rules'], list):raise serializers.ValidationError("'rules' must be a list.")+ if 'all_sets' in value and not isinstance(value['all_sets'], bool):+ raise serializers.ValidationError("'all_sets' must be a boolean.")+for rule in value['rules']:if rule not in REQUIREMENTS_RULES_KEYS:raise serializers.ValidationError(f'Invalid rule: {rule}')diff --git a/wger/manager/consts.py b/wger/manager/consts.pyindex b5293edc9..1c9a5a72e 100644--- a/wger/manager/consts.py+++ b/wger/manager/consts.py@@ -16,13 +16,27 @@RIR_OPTIONS = [None, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5]-REQUIREMENTS_RULES_KEYS = [- 'weight',- 'repetitions',- 'rir',- 'rest',-]-"""Log fields that progression requirements can reference"""+REQUIREMENT_RULES = {+ 'weight': ('weight', 'weight'),+ 'repetitions': ('repetitions', 'repetitions'),+ 'rir': ('rir', 'rir'),+ 'rest': ('rest', 'rest'),+ 'max_weight': ('weight', 'maxweight'),+ 'max_repetitions': ('repetitions', 'maxrepetitions'),+}+"""+Rules that progression requirements can reference.++Maps the rule key to ``(log field, threshold field)``: the workout log field+the rule reads, and the progression field whose displayed prescription serves+as the threshold. The ``max_*`` rules compare the same log field as their base+rule but against the top of the prescribed range, enabling double progression+(e.g. ``max_repetitions``: increase the weight only once the top of the rep+range is reached).+"""++REQUIREMENTS_RULES_KEYS = list(REQUIREMENT_RULES.keys())+"""Rule keys accepted in a progression requirement"""REP_UNIT_REPETITIONS = 1REP_UNIT_TILL_FAILURE = 2diff --git a/wger/manager/dataclasses.py b/wger/manager/dataclasses.pyindex df5adc2d5..f5aca5e8c 100644--- a/wger/manager/dataclasses.py+++ b/wger/manager/dataclasses.py@@ -270,9 +270,17 @@ def round_value(@dataclass(init=False)class ConfigRequirements:rules: List[str] = field(default_factory=list)+ all_sets: bool = False+ """+ When set, every logged set of the gating iteration must meet all rules and+ at least the prescribed number of sets must have been logged, instead of a+ single qualifying set being enough. Used for strict double progression+ ("all prescribed sets at the top of the range").+ """def __init__(self, data: Dict[str, Any]):self.rules = data.get('rules', [])+ self.all_sets = bool(data.get('all_sets', False))def __bool__(self):return bool(self.rules)diff --git a/wger/manager/models/slot_entry.py b/wger/manager/models/slot_entry.pyindex c52a93a5f..8e769ad85 100644--- a/wger/manager/models/slot_entry.py+++ b/wger/manager/models/slot_entry.py@@ -35,7 +35,7 @@ from wger.core.models import (from wger.exercises.models import Exercisefrom wger.manager.consts import (REP_UNIT_REPETITIONS,- REQUIREMENTS_RULES_KEYS,+ REQUIREMENT_RULES,WEIGHT_UNIT_KG,)from wger.manager.dataclasses import (@@ -358,14 +358,41 @@ class SlotEntry(models.Model):}.get(field)@staticmethod- def _requirements_met(requirements, log_data: List[WorkoutLog], thresholds: dict) -> bool:- """True if any single log reaches the thresholds of all required fields"""+ def _requirements_met(+ requirements,+ log_data: List[WorkoutLog],+ thresholds: dict,+ prescribed_sets: Decimal | None,+ ) -> bool:+ """+ True if the logs of the gating iteration satisfy the requirements.++ Default policy: any single log reaching the thresholds of all required+ fields is enough. With ``all_sets`` every log must reach the thresholds+ and at least the prescribed number of sets must have been logged+ (strict double progression: no set may fall below the top of the+ range, and under-logging never qualifies).+ """def rule_met(log: WorkoutLog, rule: str) -> bool:- log_value = getattr(log, rule, None)- threshold = thresholds.get(rule)+ # Unknown rules can only be persisted by writes that bypass the API+ # validator; treat them as unmet (safe-hold) instead of raising+ log_field, threshold_field = REQUIREMENT_RULES.get(rule, (None, None))+ if log_field is None:+ return False+ log_value = getattr(log, log_field, None)+ threshold = thresholds.get(threshold_field)return log_value is not None and threshold is not None and log_value >= threshold+ if requirements.all_sets:+ # Floor the prescribed count at 1: it covers both a missing+ # SetsConfig (None) and a degenerate <= 0 prescription, and keeps+ # the length check subsuming the empty-log case (all([]) is True).+ min_sets = prescribed_sets if prescribed_sets and prescribed_sets >= 1 else 1+ return len(log_data) >= min_sets and all(+ all(rule_met(log, rule) for rule in requirements.rules) for log in log_data+ )+return any(all(rule_met(log, rule) for rule in requirements.rules) for log in log_data)def get_config_data(self, iteration: int) -> SetConfigData:@@ -434,11 +461,18 @@ class SlotEntry(models.Model):logs_by_iteration[log.iteration].append(log)for i in range(1, target + 1):- # Thresholds are the displayed prescriptions of the previous iteration+ # Thresholds are the displayed prescriptions of the previous iteration.+ # Max fields (used by the max_* double progression rules) round like+ # their base field.thresholds = {- rule: round_value(states[rule].value, self._display_rounding(rule))- for rule in REQUIREMENTS_RULES_KEYS+ threshold_field: round_value(+ states[threshold_field].value,+ self._display_rounding(BASE_FIELD.get(threshold_field, threshold_field)),+ )+ for _, threshold_field in REQUIREMENT_RULES.values()}+ # Prescribed set count of the previous iteration, used by all_sets+ prescribed_sets = states['sets'].valuelog_data = logs_by_iteration.get(i - 1, [])# All fields advance first, the gates below read the candidates@@ -464,7 +498,7 @@ class SlotEntry(models.Model):is_open = (i == 1or not requirements- or self._requirements_met(requirements, log_data, thresholds)+ or self._requirements_met(requirements, log_data, thresholds, prescribed_sets))states[field].apply(candidate, is_open, FIELD_CAPS[field])diff --git a/wger/manager/tests/test_requirements_validator.py b/wger/manager/tests/test_requirements_validator.pynew file mode 100644index 000000000..3fc869e2e--- /dev/null+++ b/wger/manager/tests/test_requirements_validator.py@@ -0,0 +1,117 @@+# 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++# Django+from django.test import SimpleTestCase++# Third Party+from rest_framework import serializers++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.manager.api.serializers import WeightConfigSerializer+from wger.manager.api.validators import validate_requirements+++class RequirementsValidatorTestCase(SimpleTestCase):+ """+ Serializer-level tests for ``validate_requirements``.++ The validator is wired into ``BaseConfigSerializer.requirements`` and is *not*+ invoked by model ``save()``, so these tests call it directly (the same way the+ serializer does) and assert acceptance / ``ValidationError`` rejection.+ """++ def test_accepts_none(self):+ # Should not raise+ validate_requirements(None)++ def test_accepts_existing_rules(self):+ validate_requirements({'rules': ['weight', 'repetitions', 'rir', 'rest']})++ def test_accepts_max_repetitions(self):+ validate_requirements({'rules': ['max_repetitions']})++ def test_accepts_max_weight(self):+ validate_requirements({'rules': ['max_weight']})++ def test_accepts_all_sets_true(self):+ validate_requirements({'rules': ['max_repetitions'], 'all_sets': True})++ def test_accepts_all_sets_false(self):+ validate_requirements({'rules': ['max_repetitions'], 'all_sets': False})++ def test_rejects_max_sets(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'rules': ['max_sets']})++ def test_rejects_bogus_rule(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'rules': ['bogus']})++ def test_rejects_non_boolean_all_sets(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'rules': ['max_repetitions'], 'all_sets': 'yes'})++ def test_rejects_non_dict(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements(['max_repetitions'])++ def test_rejects_missing_rules_key(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'all_sets': True})++ def test_rejects_non_list_rules(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'rules': 'max_repetitions'})++ def test_rejects_unknown_top_level_key(self):+ """A mistyped modifier (e.g. 'all_set') must error instead of silently passing"""+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'rules': ['max_repetitions'], 'all_set': True})++ def test_rejects_unknown_top_level_key_alongside_valid(self):+ with self.assertRaises(serializers.ValidationError):+ validate_requirements({'rules': ['max_repetitions'], 'all_sets': True, 'foo': 1})+++class RequirementsSerializerWiringTestCase(WgerTestCase):+ """+ Confirms ``validate_requirements`` is actually wired into the config serializer+ field (``BaseConfigSerializer.requirements``), locking the end-to-end contract.+ """++ def test_serializer_accepts_valid_requirements(self):+ serializer = WeightConfigSerializer(+ data={+ 'slot_entry': 1,+ 'iteration': 1,+ 'value': '80',+ 'requirements': {'rules': ['max_repetitions'], 'all_sets': True},+ }+ )+ serializer.is_valid()+ self.assertNotIn('requirements', serializer.errors)++ def test_serializer_rejects_bogus_rule(self):+ serializer = WeightConfigSerializer(+ data={+ 'slot_entry': 1,+ 'iteration': 1,+ 'value': '80',+ 'requirements': {'rules': ['bogus']},+ }+ )+ serializer.is_valid()+ self.assertIn('requirements', serializer.errors)diff --git a/wger/manager/tests/test_slot_entry.py b/wger/manager/tests/test_slot_entry.pyindex 7c00b23e4..0eb1595bf 100644--- a/wger/manager/tests/test_slot_entry.py+++ b/wger/manager/tests/test_slot_entry.py@@ -1217,6 +1217,428 @@ class SlotEntryTestCase(WgerTestCase):self.assertEqual(self.slot_entry.get_config_data(3).weight, Decimal(100))+class DoubleProgressionTestCase(WgerTestCase):+ """+ Tests for double progression: the max_* requirement rules and the all_sets+ flag.++ The max_* rules gate on the top of the prescribed range (e.g. only add+ weight once the top of the rep range is reached), all_sets additionally+ requires every prescribed set to qualify.+ """++ slot_entry: SlotEntry++ def setUp(self):+ super().setUp()++ self.slot_entry = SlotEntry(+ slot_id=1,+ exercise_id=1,+ order=1,+ )+ self.slot_entry.save()++ def _build_double_progression(+ self,+ requirements,+ *,+ slot_entry=None,+ sets=3,+ repeat=False,+ ):+ """Range 8-12 reps over ``sets`` sets, +2.5 kg gated by ``requirements``."""++ entry = slot_entry or self.slot_entry+ entry.weight_rounding = Decimal('2.5')+ entry.repetition_rounding = 1+ entry.save()++ SetsConfig(slot_entry=entry, iteration=1, value=sets).save()+ RepetitionsConfig(slot_entry=entry, iteration=1, value=8).save()+ MaxRepetitionsConfig(slot_entry=entry, iteration=1, value=12).save()+ WeightConfig(slot_entry=entry, iteration=1, value=80).save()+ WeightConfig(+ slot_entry=entry,+ iteration=2,+ value=Decimal('2.5'),+ operation=OperationChoices.PLUS,+ step=StepChoices.ABSOLUTE,+ repeat=repeat,+ requirements=requirements,+ ).save()++ def _log_set(self, iteration, repetitions, *, slot_entry=None, weight=80, **kwargs):+ WorkoutLog(+ exercise_id=1,+ user_id=1,+ routine_id=1,+ slot_entry=slot_entry or self.slot_entry,+ iteration=iteration,+ weight=weight,+ repetitions=repetitions,+ **kwargs,+ ).save()++ def test_max_repetitions_holds_until_top(self):+ """Headline case: weight holds at 10 reps, advances once the top (12) is hit"""++ self._build_double_progression({'rules': ['max_repetitions']})++ self._log_set(1, repetitions=10)+ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ self._log_set(2, repetitions=12)+ self.assertEqual(self.slot_entry.get_config_data(3).weight, Decimal('82.5'))++ def test_max_repetitions_vs_repetitions(self):+ """``repetitions`` bumps at the bottom (8); ``max_repetitions`` does not"""++ entry_max = SlotEntry(slot_id=1, exercise_id=2, order=2)+ entry_max.save()++ self._build_double_progression({'rules': ['repetitions']})+ self._build_double_progression({'rules': ['max_repetitions']}, slot_entry=entry_max)++ self._log_set(1, repetitions=8)+ self._log_set(1, repetitions=8, slot_entry=entry_max)++ # bottom-of-range rule advances at 8+ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))+ # top-of-range rule holds at 8+ self.assertEqual(entry_max.get_config_data(2).weight, Decimal(80))++ def test_max_repetitions_any_policy_opt_out(self):+ """Without ``all_sets`` the permissive 'any' default advances on one top set"""++ self._build_double_progression({'rules': ['max_repetitions']})++ # 12 / 8 / 8 - only one set hit the top+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=8)+ self._log_set(1, repetitions=8)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))++ def test_max_repetitions_partial_no_advance(self):+ """Three logs below the top (11/11/11) hold under the 'any' default"""++ self._build_double_progression({'rules': ['max_repetitions']})++ self._log_set(1, repetitions=11)+ self._log_set(1, repetitions=11)+ self._log_set(1, repetitions=11)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_max_repetitions_missing_log(self):+ """No log for the prior iteration holds the weight"""++ self._build_double_progression({'rules': ['max_repetitions']})++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_max_repetitions_all_sets_strict_holds(self):+ """Canonical 3x12: 12/8/8 with ``all_sets`` holds (not every set at the top)"""++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=8)+ self._log_set(1, repetitions=8)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_max_repetitions_all_sets_strict_advances(self):+ """Canonical 3x12: 12/12/12 with ``all_sets`` advances"""++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))++ def test_all_sets_under_logging_holds(self):+ """Logging only two sets when 3 are prescribed holds (prescribed count gate)"""++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_all_sets_over_logging_holds(self):+ """An extra sub-top set (12/12/12/8) holds under ``all_sets``"""++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=8)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_all_sets_over_logging_all_top_advances(self):+ """Four genuine top sets (12/12/12/12) advance (4 >= 3 and all at the top)"""++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))++ def test_all_sets_empty_logs_no_advance(self):+ """``all_sets`` with no logs for the prior iteration holds (0 >= prescribed)"""++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_all_sets_no_backfill_after_skipped_iteration(self):+ """+ A repeating all_sets progression earns exactly one step per qualifying+ iteration and doesn't back-fill increments for skipped iterations+ """+ self._build_double_progression(+ {'rules': ['max_repetitions'], 'all_sets': True},+ repeat=True,+ )++ # Only iteration 2's logs qualify (all three sets at the top)+ self._log_set(1, repetitions=10)+ self._log_set(1, repetitions=10)+ self._log_set(1, repetitions=10)+ self._log_set(2, repetitions=12)+ self._log_set(2, repetitions=12)+ self._log_set(2, repetitions=12)+ self._log_set(3, repetitions=9)+ self._log_set(3, repetitions=9)+ self._log_set(3, repetitions=9)++ # One earned step, not the calendar index+ self.assertEqual(self.slot_entry.get_config_data(3).weight, Decimal('82.5'))+ self.assertEqual(self.slot_entry.get_config_data(4).weight, Decimal('82.5'))++ def test_all_sets_warmup_sets_excluded(self):+ """+ A warm-up SlotEntry logged at low reps in the same iteration does not affect+ the work entry's ``all_sets`` evaluation (logs are scoped by slot entry)+ """++ self._build_double_progression({'rules': ['max_repetitions'], 'all_sets': True})++ warmup = SlotEntry(slot_id=1, exercise_id=1, order=2, type='warmup')+ warmup.save()++ # Work entry: 3 sets all at the top+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ self._log_set(1, repetitions=12)+ # Warm-up logged at low reps in the same iteration, but on a different entry+ self._log_set(1, repetitions=5, slot_entry=warmup)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))++ def test_all_sets_no_sets_config_defaults_to_one(self):+ """+ Without a ``SetsConfig`` the prescribed count is ``None`` and floors to 1:+ zero logs hold (0 >= 1 is False), a single top log advances.+ """++ self.slot_entry.weight_rounding = Decimal('2.5')+ self.slot_entry.repetition_rounding = 1+ self.slot_entry.save()++ RepetitionsConfig(slot_entry=self.slot_entry, iteration=1, value=8).save()+ MaxRepetitionsConfig(slot_entry=self.slot_entry, iteration=1, value=12).save()+ WeightConfig(slot_entry=self.slot_entry, iteration=1, value=80).save()+ WeightConfig(+ slot_entry=self.slot_entry,+ iteration=2,+ value=Decimal('2.5'),+ operation=OperationChoices.PLUS,+ step=StepChoices.ABSOLUTE,+ requirements={'rules': ['max_repetitions'], 'all_sets': True},+ ).save()++ # No logs for the prior iteration -> holds (0 >= 1 is False)+ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ # One log at the top -> advances (default prescribed count of 1 is met)+ self._log_set(1, repetitions=12)+ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))++ def test_all_sets_zero_sets_config_floors_to_one(self):+ """+ A degenerate ``SetsConfig(value=0)`` floors the prescribed count to 1, so an+ *empty* log set holds instead of vacuously advancing (``0 >= 0`` together+ with ``all([])`` over no logs would otherwise advance the weight).+ """++ self._build_double_progression(+ {'rules': ['max_repetitions'], 'all_sets': True},+ sets=0,+ )++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++ def test_all_sets_combined_rules(self):+ """+ The strict ``all_sets`` path with combined ``['max_repetitions', 'rir']`` is+ not reps-specific: every set must meet *both* rules.+ """++ entry_met = self.slot_entry+ entry_unmet = SlotEntry(slot_id=1, exercise_id=2, order=2)+ entry_unmet.save()++ for entry in (entry_met, entry_unmet):+ self._build_double_progression(+ {'rules': ['max_repetitions', 'rir'], 'all_sets': True},+ slot_entry=entry,+ )+ RiRConfig(slot_entry=entry, iteration=1, value=2).save()++ # All 3 sets meet both rules (reps 12 >= 12 and rir 2 >= 2)+ self._log_set(1, repetitions=12, rir=2, slot_entry=entry_met)+ self._log_set(1, repetitions=12, rir=2, slot_entry=entry_met)+ self._log_set(1, repetitions=12, rir=2, slot_entry=entry_met)++ # One set fails the rir rule (1 < 2 under the >= gate) -> strict path holds+ self._log_set(1, repetitions=12, rir=2, slot_entry=entry_unmet)+ self._log_set(1, repetitions=12, rir=2, slot_entry=entry_unmet)+ self._log_set(1, repetitions=12, rir=1, slot_entry=entry_unmet)++ self.assertEqual(entry_met.get_config_data(2).weight, Decimal('82.5'))+ self.assertEqual(entry_unmet.get_config_data(2).weight, Decimal(80))++ def test_combined_rules(self):+ """``{'rules': ['max_repetitions', 'rir']}`` requires both in the same log"""++ entry_met = self.slot_entry+ entry_unmet = SlotEntry(slot_id=1, exercise_id=2, order=2)+ entry_unmet.save()++ for entry in (entry_met, entry_unmet):+ self._build_double_progression(+ {'rules': ['max_repetitions', 'rir']},+ slot_entry=entry,+ )+ RiRConfig(slot_entry=entry, iteration=1, value=2).save()++ # both rules met: 12 reps (>= 12) and rir 2 (>= 2)+ self._log_set(1, repetitions=12, rir=2, slot_entry=entry_met)+ # reps met but rir too high (1 < 2 under the >= gate)+ self._log_set(1, repetitions=12, rir=1, slot_entry=entry_unmet)++ self.assertEqual(entry_met.get_config_data(2).weight, Decimal('82.5'))+ self.assertEqual(entry_unmet.get_config_data(2).weight, Decimal(80))++ def test_max_weight_symmetry(self):+ """``max_weight`` reads log.weight and gates against the prescribed top load"""++ # entry that logs the top of the load range -> reps advance+ entry_top = SlotEntry(slot_id=1, exercise_id=1, order=1)+ entry_top.repetition_rounding = 1+ entry_top.save()+ # entry that logs below the top -> reps hold+ entry_low = SlotEntry(slot_id=1, exercise_id=2, order=2)+ entry_low.repetition_rounding = 1+ entry_low.save()++ for entry in (entry_top, entry_low):+ WeightConfig(slot_entry=entry, iteration=1, value=100).save()+ MaxWeightConfig(slot_entry=entry, iteration=1, value=110).save()+ RepetitionsConfig(slot_entry=entry, iteration=1, value=5).save()+ RepetitionsConfig(+ slot_entry=entry,+ iteration=2,+ value=1,+ operation=OperationChoices.PLUS,+ step=StepChoices.ABSOLUTE,+ requirements={'rules': ['max_weight']},+ ).save()++ self._log_set(1, repetitions=1, slot_entry=entry_top, weight=110)+ self._log_set(1, repetitions=1, slot_entry=entry_low, weight=105)++ self.assertEqual(entry_top.get_config_data(2).repetitions, Decimal(6))+ self.assertEqual(entry_low.get_config_data(2).repetitions, Decimal(5))++ def test_repeat_true_with_max_repetitions(self):+ """``repeat=True`` advances every iteration the top is hit, then stalls"""++ self._build_double_progression({'rules': ['max_repetitions']}, repeat=True)++ self._log_set(1, repetitions=12)+ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal('82.5'))++ self._log_set(2, repetitions=12)+ self.assertEqual(self.slot_entry.get_config_data(3).weight, Decimal(85))++ # Stall: top not hit, weight holds at its current value+ self._log_set(3, repetitions=8)+ self.assertEqual(self.slot_entry.get_config_data(4).weight, Decimal(85))++ def test_progressing_max_rep_top_with_weight_gate(self):+ """+ A progressing rep-range top: the weight gate always compares against the+ top as prescribed for the iteration the logs belong to+ """++ self.slot_entry.weight_rounding = Decimal('2.5')+ self.slot_entry.repetition_rounding = 1+ self.slot_entry.save()++ RepetitionsConfig(slot_entry=self.slot_entry, iteration=1, value=8).save()+ MaxRepetitionsConfig(slot_entry=self.slot_entry, iteration=1, value=12).save()+ MaxRepetitionsConfig(slot_entry=self.slot_entry, iteration=3, value=14).save()+ WeightConfig(slot_entry=self.slot_entry, iteration=1, value=80).save()+ WeightConfig(+ slot_entry=self.slot_entry,+ iteration=2,+ value=Decimal('2.5'),+ operation=OperationChoices.PLUS,+ step=StepChoices.ABSOLUTE,+ repeat=True,+ requirements={'rules': ['max_repetitions']},+ ).save()++ self._log_set(1, repetitions=12)+ self._log_set(2, repetitions=12)+ self._log_set(3, repetitions=14)++ # At iteration 3 the rep-range top has moved to 14 and the weight has+ # bumped twice (once per qualifying log against the top prescribed at+ # the time: 12, 12)+ transition = self.slot_entry.get_config_data(3)+ self.assertEqual(transition.weight, Decimal(85))+ self.assertEqual(transition.max_repetitions, Decimal(14))++ # The iteration-3 log hit the new top of 14 -> third bump+ config_data = self.slot_entry.get_config_data(4)+ self.assertEqual(config_data.weight, Decimal('87.5'))+ self.assertEqual(config_data.max_repetitions, Decimal(14))++ def test_unknown_rule_holds(self):+ """+ A bogus rule persisted past the (serializer-only) validator must hold the+ progression (safe fail) instead of raising+ """++ self._build_double_progression({'rules': ['bogus']})+ self._log_set(1, repetitions=12)++ self.assertEqual(self.slot_entry.get_config_data(2).weight, Decimal(80))++class WalkConfigValuesTestCase(SimpleTestCase):"""Tests for the ungated config walk