Self hosted FLOSS fitness/workout, nutrition and weight tracker
Merge remote-tracking branch 'origin/master' into fix-midnight-session-datetime
Roland Geider2fc652ab4bb3
diff --cc wger/core/tests/test_user.pyindex 771bc5579,ef061e3e5..417ffff5a--- a/wger/core/tests/test_user.py+++ b/wger/core/tests/test_user.py@@@ -34,7 -32,7 +34,8 @@@ from wger.core.tests.base_testcase impoWgerEditTestCase,WgerTestCase,)+from wger.manager.models import WorkoutSession+ from wger.nutrition.models import NutritionPlanclass StatusUserTestCase(WgerTestCase):@@@ -364,37 -362,27 +365,58 @@@ class UserDetailPageTestCase2(WgerAcces)+class UserDetailPageSessionTableTestCase(WgerTestCase):+ """+ Test the workout session table on the user detail page+ """++ def test_session_date_and_times_are_rendered(self):+ """The session table shows the day and the start/end times of a session"""++ session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000005')+ start = timezone.localtime(session.datetime_start)+ end = timezone.localtime(session.datetime_end)++ self.user_login('trainer1')+ response = self.client.get(reverse('core:user:overview', kwargs={'pk': 2}))++ self.assertContains(response, date_format(start))+ self.assertContains(response, f'{start:%H:%M} - {end:%H:%M}')++ def test_session_without_end_shows_no_times(self):+ """An open session (no end) falls back to the placeholder"""++ WorkoutSession.objects.filter(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000005').update(+ datetime_end=None+ )++ self.user_login('trainer1')+ response = self.client.get(reverse('core:user:overview', kwargs={'pk': 2}))++ self.assertContains(response, '-/-')+++ class UserDetailPageMacroUnitTestCase(WgerTestCase):+ """+ Tests that nutrition plan macros on the user detail page are labeled in grams+ """++ def test_macros_labeled_in_grams_for_imperial_user(self):+ """+ Tests that the macro labels stay 'g' for users with imperial units+ """+ member = User.objects.get(pk=2)+ member.userprofile.weight_unit = 'lb'+ member.userprofile.save()+ NutritionPlan.objects.create(user=member)++ self.user_login('trainer1')+ response = self.client.get(reverse('core:user:overview', kwargs={'pk': member.pk}))++ self.assertEqual(response.status_code, 200)+ self.assertNotContains(response, 'oz')++class UserTrustworthinessTestCase(WgerTestCase):request = HttpRequest()diff --cc wger/gym/helpers.pyindex 90a3b4c11,254f0cb56..db1ee6e8b--- a/wger/gym/helpers.py+++ b/wger/gym/helpers.py@@@ -29,27 -32,20 +32,20 @@@ def get_user_last_activity(user)WorkoutSession,)- last_activity = None+ dates = []- # Check workout logs+ # Check workout logs. They use datetimes, the sessions and the user cache+ # only dateslast_log = WorkoutLog.objects.filter(user=user).order_by('date').last()if last_log:- last_activity = last_log.date+ dates.append(timezone.localdate(last_log.date))# Check workout sessions- last_session = WorkoutSession.objects.filter(user=user).order_by('date').last()+ last_session = WorkoutSession.objects.filter(user=user).order_by('datetime_start').last()if last_session:- last_session = last_session.datetime_start-- # Return the last one- # if last_session:- # if not last_activity:- # last_activity = last_session- #- # if last_activity < last_session:- # last_activity = last_session- dates.append(last_session.date)++ dates.append(timezone.localdate(last_session.datetime_start))- return last_activity+ return max(dates) if dates else None_CSV_FORMULA_PREFIXES = ('=', '+', '-', '@', '\t', '\r')diff --cc wger/gym/tests/test_user_last_activity.pyindex 721a6a475,861bee3cb..e8ff3cca2--- a/wger/gym/tests/test_user_last_activity.py+++ b/wger/gym/tests/test_user_last_activity.py@@@ -34,56 -35,53 +35,59 @@@ class UserLastActivityTestCase(WgerTestTODO: check if we want to get rid of usercache.last_activity"""- def test_user_last_activity(self):+ def setUp(self):+ super().setUp()++ self.user = User.objects.get(username='admin')++ # Start from a clean slate, the fixtures have both logs and sessions+ WorkoutLog.objects.filter(user=self.user).delete()+ WorkoutSession.objects.filter(user=self.user).delete()++ def add_log(self, date: datetime.date):+ WorkoutLog(+ user=self.user,+ exercise_id=1,+ routine_id=1,+ weight=80,+ repetitions=5,+ date=timezone.make_aware(datetime.datetime.combine(date, datetime.time(12, 0))),+ ).save()++ def add_session(self, date: datetime.date):- WorkoutSession(user=self.user, routine_id=1, date=date).save()++ WorkoutSession(++ user=self.user,++ routine_id=1,++ datetime_start=timezone.make_aware(++ datetime.datetime.combine(date, datetime.time(12, 0))++ ),++ ).save()++ def test_no_activity(self):+ self.assertIsNone(get_user_last_activity(self.user))++ def test_only_logs(self):+ self.add_log(datetime.date(2024, 3, 1))+ self.add_log(datetime.date(2024, 3, 5))++ self.assertEqual(get_user_last_activity(self.user), datetime.date(2024, 3, 5))++ def test_only_sessions(self):"""- Test the helper function for last user activity+ Users that only track sessions are active too"""- self.user_login('admin')- user = User.objects.get(username='admin')- log = WorkoutLog.objects.get(pk='aaaaaaaa-aaaa-aaaa-aaaa-000000000001')- session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000001')-- self.assertEqual(user.usercache.last_activity, datetime.date(2025, 11, 1))- self.assertEqual(- get_user_last_activity(user),- datetime.datetime(2025, 10, 31, 23, 0, tzinfo=datetime.timezone.utc),- )-- # Log more recent than session- log.date = datetime.date(2014, 10, 2)- log.save()- session.date = datetime.date(2014, 10, 1)- session.save()- user = User.objects.get(username='admin')- self.assertEqual(- get_user_last_activity(user),- datetime.datetime(2025, 10, 31, 23, 0, tzinfo=datetime.timezone.utc),- )- self.assertEqual(- user.usercache.last_activity,- datetime.date(2025, 11, 1),- )-- # Session more recent than log- log.date = datetime.date(2014, 9, 1)- log.save()- session.date = datetime.date(2014, 10, 5)- session.save()- user = User.objects.get(username='admin')- self.assertEqual(- get_user_last_activity(user),- datetime.datetime(2025, 10, 31, 23, 0, tzinfo=datetime.timezone.utc),- )- self.assertEqual(- user.usercache.last_activity,- datetime.date(2025, 11, 1),- )-- # No logs, but session- WorkoutLog.objects.filter(user=user).delete()- user = User.objects.get(username='admin')- self.assertEqual(get_user_last_activity(user), None)- self.assertEqual(- user.usercache.last_activity,- datetime.date(2025, 11, 1),- )+ self.add_session(datetime.date(2024, 3, 7))++ self.assertEqual(get_user_last_activity(self.user), datetime.date(2024, 3, 7))++ def test_log_more_recent_than_session(self):+ self.add_log(datetime.date(2024, 3, 10))+ self.add_session(datetime.date(2024, 3, 2))++ self.assertEqual(get_user_last_activity(self.user), datetime.date(2024, 3, 10))++ def test_session_more_recent_than_log(self):+ self.add_log(datetime.date(2024, 3, 2))+ self.add_session(datetime.date(2024, 3, 10))++ self.assertEqual(get_user_last_activity(self.user), datetime.date(2024, 3, 10))diff --cc wger/manager/tests/test_routine_cache.pyindex 000000000,7ce6c8446..89b15a80cmode 000000,100644..100644--- a/wger/manager/tests/test_routine_cache.py+++ b/wger/manager/tests/test_routine_cache.py@@@ -1,0 -1,115 +1,116 @@@+ # 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/>.++ # Standard Library+ import datetime++ # Django+ from django.core.cache import cache+ from django.urls import reverse++from django.utils import timezone++ # wger+ from wger.core.tests.api_base_test import ApiBaseTestCase+ from wger.core.tests.base_testcase import BaseTestCase+ from wger.manager.models import (+ WorkoutLog,+ WorkoutSession,+ )+ from wger.utils.cache import CacheKeyMapper+++ class RoutineCacheInvalidationTestCase(BaseTestCase, ApiBaseTestCase):+ """+ Tests that log and session changes invalidate the routine caches++ Routine 1 belongs to the admin user (user 1). Log and session changes+ invalidate everything except the structure cache, which does not depend+ on them.+ """++ ROUTINE_ID = 1+ USER_ID = 1++ @property+ def volatile_keys(self):+ return (+ CacheKeyMapper.routine_date_sequence_key(self.ROUTINE_ID),+ CacheKeyMapper.routine_api_date_sequence_display_key(self.ROUTINE_ID, self.USER_ID),+ CacheKeyMapper.routine_api_date_sequence_gym_key(self.ROUTINE_ID, self.USER_ID),+ CacheKeyMapper.routine_api_logs(self.ROUTINE_ID, self.USER_ID),+ CacheKeyMapper.routine_api_stats(self.ROUTINE_ID, self.USER_ID),+ )++ @property+ def structure_key(self):+ return CacheKeyMapper.routine_api_structure_key(self.ROUTINE_ID, self.USER_ID)++ def prime_caches(self):+ """+ Populate all routine caches through the API, like the apps do+ """+ self.authenticate('admin')+ for url_name in (+ 'routine-date-sequence-display-mode',+ 'routine-date-sequence-gym-mode',+ 'routine-structure',+ 'routine-logs',+ 'routine-stats',+ ):+ response = self.client.get(reverse(url_name, kwargs={'pk': self.ROUTINE_ID}))+ self.assertEqual(response.status_code, 200)++ for key in self.volatile_keys:+ self.assertIsNotNone(cache.get(key), f'Cache key {key} was not primed')+ self.assertIsNotNone(cache.get(self.structure_key))++ def assert_volatile_caches_cleared(self):+ for key in self.volatile_keys:+ self.assertIsNone(cache.get(key), f'Cache key {key} was not invalidated')++ # The structure does not depend on logs or sessions+ self.assertIsNotNone(cache.get(self.structure_key))++ def test_saving_a_log_resets_the_cache(self):+ self.prime_caches()++ WorkoutLog(+ user_id=self.USER_ID,+ exercise_id=1,+ routine_id=self.ROUTINE_ID,+ weight=80,+ repetitions=5,+ ).save()++ self.assert_volatile_caches_cleared()++ def test_saving_a_session_resets_the_cache(self):+ self.prime_caches()++ WorkoutSession(+ user_id=self.USER_ID,+ routine_id=self.ROUTINE_ID,- date=datetime.date(2024, 5, 1),++ datetime_start=timezone.make_aware(datetime.datetime(2024, 5, 1, 12, 0)),+ ).save()++ self.assert_volatile_caches_cleared()++ def test_log_without_routine_keeps_the_cache(self):+ self.prime_caches()++ WorkoutLog(user_id=self.USER_ID, exercise_id=1, weight=80, repetitions=5).save()++ for key in self.volatile_keys:+ self.assertIsNotNone(cache.get(key))diff --cc wger/trophies/tests/test_statistics_streaks.pyindex 000000000,76c906d34..a1c74fa71mode 000000,100644..100644--- a/wger/trophies/tests/test_statistics_streaks.py+++ b/wger/trophies/tests/test_statistics_streaks.py@@@ -1,0 -1,204 +1,210 @@@+ # 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/>.++ # Standard Library+ import datetime+ from unittest import mock++ # Django+ from django.contrib.auth.models import User+ from django.test import SimpleTestCase++from django.utils import timezone++ # wger+ from wger.core.tests.base_testcase import WgerTestCase+ from wger.manager.models import WorkoutSession+ from wger.trophies.models import UserStatistics+ from wger.trophies.services.statistics import UserStatisticsService+++ FROZEN_TODAY = datetime.date(2024, 6, 19)+ """A Wednesday; the most recent Saturday is 2024-06-15"""+++ def frozen_today():+ """+ Freezes datetime.date.today() so the streak calculations are deterministic+ """++ class FrozenDate(datetime.date):+ @classmethod+ def today(cls):+ return FROZEN_TODAY++ return mock.patch('datetime.date', FrozenDate)+++ def days_ago(days: int) -> datetime.date:+ return FROZEN_TODAY - datetime.timedelta(days=days)+++ class CalculateStreaksTestCase(SimpleTestCase):+ """+ Tests the full streak calculation over real date sequences+ """++ def calculate(self, dates):+ with frozen_today():+ return UserStatisticsService._calculate_streaks(dates)++ def test_no_workouts(self):+ self.assertEqual(self.calculate([]), (0, 0))++ def test_single_workout_today(self):+ self.assertEqual(self.calculate([FROZEN_TODAY]), (1, 1))++ def test_run_ending_today(self):+ dates = [days_ago(2), days_ago(1), FROZEN_TODAY]+ self.assertEqual(self.calculate(dates), (3, 3))++ def test_run_ending_yesterday_is_still_active(self):+ dates = [days_ago(3), days_ago(2), days_ago(1)]+ self.assertEqual(self.calculate(dates), (3, 3))++ def test_run_ending_two_days_ago_is_broken(self):+ dates = [days_ago(4), days_ago(3), days_ago(2)]+ self.assertEqual(self.calculate(dates), (0, 3))++ def test_longest_streak_in_the_past(self):+ dates = [days_ago(10), days_ago(9), days_ago(8), days_ago(1), FROZEN_TODAY]+ self.assertEqual(self.calculate(dates), (2, 3))++ def test_duplicate_days_count_once(self):+ dates = [days_ago(1), days_ago(1), days_ago(1), FROZEN_TODAY]+ self.assertEqual(self.calculate(dates), (2, 2))++ def test_streak_across_year_boundary(self):+ dates = [+ datetime.date(2023, 12, 30),+ datetime.date(2023, 12, 31),+ datetime.date(2024, 1, 1),+ ]+ self.assertEqual(self.calculate(dates), (0, 3))+++ class CalculateWeekendStreakTestCase(SimpleTestCase):+ """+ Tests the weekend streak calculation over real date sequences++ With today frozen to Wednesday 2024-06-19, the most recent Saturday+ is 2024-06-15.+ """++ def calculate(self, dates):+ with frozen_today():+ return UserStatisticsService._calculate_weekend_streak(dates)++ def test_no_workouts(self):+ self.assertEqual(self.calculate([]), (0, None))++ def test_last_weekend_complete(self):+ dates = [datetime.date(2024, 6, 15), datetime.date(2024, 6, 16)]+ self.assertEqual(self.calculate(dates), (1, datetime.date(2024, 6, 15)))++ def test_saturday_alone_is_not_a_complete_weekend(self):+ self.assertEqual(self.calculate([datetime.date(2024, 6, 15)]), (0, None))++ def test_two_consecutive_weekends(self):+ dates = [+ datetime.date(2024, 6, 8),+ datetime.date(2024, 6, 9),+ datetime.date(2024, 6, 15),+ datetime.date(2024, 6, 16),+ ]+ self.assertEqual(self.calculate(dates), (2, datetime.date(2024, 6, 15)))++ def test_gap_resets_the_streak(self):+ dates = [+ datetime.date(2024, 6, 1),+ datetime.date(2024, 6, 2),+ # weekend of 2024-06-08 is skipped+ datetime.date(2024, 6, 15),+ datetime.date(2024, 6, 16),+ ]+ self.assertEqual(self.calculate(dates), (1, datetime.date(2024, 6, 15)))++ def test_old_weekend_is_no_current_streak(self):+ dates = [datetime.date(2024, 6, 1), datetime.date(2024, 6, 2)]+ self.assertEqual(self.calculate(dates), (0, datetime.date(2024, 6, 1)))+++ class IncrementWorkoutStreakTestCase(WgerTestCase):+ """+ Tests the incremental streak bookkeeping used by the signal handlers++ increment_workout does not depend on today's date, so the scenarios run+ with fixed dates.+ """++ def setUp(self):+ super().setUp()+ self.user = User.objects.get(username='admin')+ UserStatistics.objects.filter(user=self.user).delete()++ def increment(self, date: datetime.date) -> UserStatistics:- session = WorkoutSession(user=self.user, date=date)++ session = WorkoutSession(++ user=self.user,++ datetime_start=timezone.make_aware(++ datetime.datetime.combine(date, datetime.time(12, 0))++ ),++ )+ return UserStatisticsService.increment_workout(self.user, session=session)++ def test_first_workout_starts_a_streak(self):+ stats = self.increment(datetime.date(2024, 3, 1))++ self.assertEqual(stats.current_streak, 1)+ self.assertEqual(stats.longest_streak, 1)+ self.assertEqual(stats.last_workout_date, datetime.date(2024, 3, 1))++ def test_consecutive_day_extends_the_streak(self):+ self.increment(datetime.date(2024, 3, 1))+ stats = self.increment(datetime.date(2024, 3, 2))++ self.assertEqual(stats.current_streak, 2)+ self.assertEqual(stats.longest_streak, 2)++ def test_second_workout_on_the_same_day_does_not_extend(self):+ self.increment(datetime.date(2024, 3, 1))+ self.increment(datetime.date(2024, 3, 2))+ stats = self.increment(datetime.date(2024, 3, 2))++ self.assertEqual(stats.current_streak, 2)++ def test_gap_resets_the_streak_but_keeps_the_longest(self):+ self.increment(datetime.date(2024, 3, 1))+ self.increment(datetime.date(2024, 3, 2))+ self.increment(datetime.date(2024, 3, 3))+ stats = self.increment(datetime.date(2024, 3, 10))++ self.assertEqual(stats.current_streak, 1)+ self.assertEqual(stats.longest_streak, 3)++ def test_streak_across_month_boundary(self):+ self.increment(datetime.date(2024, 3, 31))+ stats = self.increment(datetime.date(2024, 4, 1))++ self.assertEqual(stats.current_streak, 2)++ def test_long_gap_records_the_inactive_date(self):+ self.increment(datetime.date(2024, 3, 1))+ stats = self.increment(datetime.date(2024, 4, 15))++ self.assertEqual(stats.current_streak, 1)+ self.assertEqual(stats.last_inactive_date, datetime.date(2024, 3, 1))++ def test_jan_first_workout_is_flagged(self):+ stats = self.increment(datetime.date(2024, 1, 1))+ self.assertTrue(stats.worked_out_jan_1)