Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add tests for untested security- and correctness-critical paths

Roland Geiderf849d7a47c34
diff --git a/wger/exercises/tests/api/test_exercise_submission_api.py b/wger/exercises/tests/api/test_exercise_submission_api.py
index 09fe667ec..0491d0551 100644
--- a/wger/exercises/tests/api/test_exercise_submission_api.py
+++ b/wger/exercises/tests/api/test_exercise_submission_api.py
@@ -32,7 +32,7 @@ from wger.exercises.models import (
from wger.exercises.views.helper import StreamVerbs
-class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
+class ExerciseSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
url = '/api/v2/exercise-submission/'
@staticmethod
@@ -84,6 +84,24 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
ExerciseComment.objects.count(),
)
+ def test_submission_anonymous(self):
+ """Anonymous users cannot submit exercises"""
+ before = self.get_counts()
+ response = self.client.post(self.url, data=self.get_payload())
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(before, self.get_counts())
+
+ def test_submission_untrustworthy_user(self):
+ """Users without a verified email cannot submit exercises"""
+ self.authenticate('test')
+
+ before = self.get_counts()
+ response = self.client.post(self.url, data=self.get_payload())
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(before, self.get_counts())
+
def test_successful_submission_full(self):
"""Test that all objects were correctly created."""
diff --git a/wger/exercises/tests/test_history.py b/wger/exercises/tests/test_history.py
index 4917d7ac9..334b53856 100644
--- a/wger/exercises/tests/test_history.py
+++ b/wger/exercises/tests/test_history.py
@@ -306,3 +306,54 @@ class ExerciseHistoryControlExtras(WgerTestCase):
response.context['context'][0]['verb'],
StreamVerbs.DELETED.value,
)
+
+
+class ExerciseHistoryPermissionTestCase(WgerTestCase):
+ """
+ Tests that the history admin views require the change_exercise permission
+ """
+
+ def get_revert_url(self) -> str:
+ translation = Translation.objects.get(pk=2)
+ translation.description = 'Boring exercise'
+ translation.save()
+ history_entry = translation.history.order_by('history_date').last()
+
+ translation.description = 'Very cool exercise!'
+ translation.save()
+
+ return reverse(
+ 'exercise:history:revert',
+ kwargs={
+ 'history_pk': history_entry.history_id,
+ 'content_type_id': ContentType.objects.get_for_model(translation).id,
+ },
+ )
+
+ def assert_revert_denied(self):
+ response = self.client.post(self.get_revert_url())
+
+ # Not the redirect to the overview that a successful revert returns
+ self.assertIn(response.status_code, (302, 403))
+ if response.status_code == 302:
+ self.assertNotEqual(response['Location'], reverse('exercise:history:overview'))
+
+ # The description was not reverted
+ translation = Translation.objects.get(pk=2)
+ self.assertEqual(translation.description, 'Very cool exercise!')
+
+ def test_overview_anonymous(self):
+ response = self.client.get(reverse('exercise:history:overview'))
+ self.assertIn(response.status_code, (302, 403))
+
+ def test_overview_no_permission(self):
+ self.user_login('test')
+ response = self.client.get(reverse('exercise:history:overview'))
+ self.assertIn(response.status_code, (302, 403))
+
+ def test_revert_anonymous(self):
+ self.assert_revert_denied()
+
+ def test_revert_no_permission(self):
+ self.user_login('test')
+ self.assert_revert_denied()
diff --git a/wger/gallery/tests/test_api.py b/wger/gallery/tests/test_api.py
new file mode 100644
index 000000000..6c62fa3b6
--- /dev/null
+++ b/wger/gallery/tests/test_api.py
@@ -0,0 +1,98 @@
+# 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/>.
+
+# Third Party
+from rest_framework import status
+
+# wger
+from wger.core.tests.api_base_test import ApiBaseTestCase
+from wger.core.tests.base_testcase import BaseTestCase
+from wger.gallery.models import Image
+
+
+class GalleryImageApiTestCase(BaseTestCase, ApiBaseTestCase):
+ """
+ Tests that the gallery API only ever exposes the user's own images
+
+ User test owns image 3, user admin owns images 1 and 2.
+ """
+
+ url = '/api/v2/gallery/'
+
+ def test_anonymous(self):
+ response = self.client.get(self.url)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ response = self.client.get(f'{self.url}3/')
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_list_contains_only_own_images(self):
+ self.authenticate('test')
+ response = self.client.get(self.url)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual([image['id'] for image in response.json()['results']], [3])
+
+ self.authenticate('admin')
+ response = self.client.get(self.url)
+ self.assertCountEqual(
+ [image['id'] for image in response.json()['results']],
+ [1, 2],
+ )
+
+ def test_detail_own_image(self):
+ self.authenticate('test')
+ response = self.client.get(f'{self.url}3/')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()['id'], 3)
+
+ def test_detail_other_user_image(self):
+ self.authenticate('test')
+ response = self.client.get(f'{self.url}1/')
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_post_sets_owner(self):
+ self.authenticate('test')
+
+ with open('wger/exercises/tests/protestschwein.jpg', 'rb') as image_file:
+ response = self.client.post(
+ self.url,
+ data={'date': '2024-01-01', 'description': 'test', 'image': image_file},
+ format='multipart',
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ image = Image.objects.get(pk=response.json()['id'])
+ self.assertEqual(image.user.username, 'test')
+
+ def test_patch_other_user_image(self):
+ self.authenticate('test')
+ response = self.client.patch(f'{self.url}1/', data={'description': 'hacked'})
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertNotEqual(Image.objects.get(pk=1).description, 'hacked')
+
+ def test_delete_other_user_image(self):
+ self.authenticate('test')
+ response = self.client.delete(f'{self.url}1/')
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertTrue(Image.objects.filter(pk=1).exists())
+
+ def test_delete_own_image(self):
+ self.authenticate('test')
+ response = self.client.delete(f'{self.url}3/')
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(Image.objects.filter(pk=3).exists())
diff --git a/wger/manager/tests/test_routine_cache.py b/wger/manager/tests/test_routine_cache.py
new file mode 100644
index 000000000..7ce6c8446
--- /dev/null
+++ b/wger/manager/tests/test_routine_cache.py
@@ -0,0 +1,115 @@
+# 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
+
+# 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),
+ ).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 --git a/wger/manager/tests/test_routine_endpoints.py b/wger/manager/tests/test_routine_endpoints.py
new file mode 100644
index 000000000..e0e92ca5e
--- /dev/null
+++ b/wger/manager/tests/test_routine_endpoints.py
@@ -0,0 +1,91 @@
+# 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/>.
+
+# Django
+from django.urls import reverse
+
+# Third Party
+from rest_framework import status
+
+# wger
+from wger.core.tests.api_base_test import ApiBaseTestCase
+from wger.core.tests.base_testcase import BaseTestCase
+
+
+URL_NAMES = (
+ 'routine-date-sequence-display-mode',
+ 'routine-date-sequence-gym-mode',
+ 'routine-structure',
+)
+
+
+class RoutineDetailEndpointsApiTestCase(BaseTestCase, ApiBaseTestCase):
+ """
+ Tests the detail endpoints used by the mobile and web apps
+
+ Routine 1 belongs to admin, has three days and is not public.
+ """
+
+ def test_anonymous(self):
+ for url_name in URL_NAMES:
+ response = self.client.get(reverse(url_name, kwargs={'pk': 1}))
+ self.assertEqual(
+ response.status_code,
+ status.HTTP_403_FORBIDDEN,
+ f'{url_name} did not return 403 for anonymous users',
+ )
+
+ def test_other_user(self):
+ self.authenticate('test')
+ for url_name in URL_NAMES:
+ response = self.client.get(reverse(url_name, kwargs={'pk': 1}))
+ self.assertEqual(
+ response.status_code,
+ status.HTTP_404_NOT_FOUND,
+ f'{url_name} leaked a foreign routine',
+ )
+
+ def test_date_sequence_display(self):
+ self.authenticate('admin')
+ response = self.client.get(reverse('routine-date-sequence-display-mode', kwargs={'pk': 1}))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertTrue(data)
+
+ first_day = data[0]
+ self.assertIn('iteration', first_day)
+ self.assertIn('date', first_day)
+ self.assertIn('day', first_day)
+ self.assertIn('slots', first_day)
+
+ def test_date_sequence_gym(self):
+ self.authenticate('admin')
+ response = self.client.get(reverse('routine-date-sequence-gym-mode', kwargs={'pk': 1}))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertTrue(data)
+ self.assertIn('day', data[0])
+
+ def test_structure(self):
+ self.authenticate('admin')
+ response = self.client.get(reverse('routine-structure', kwargs={'pk': 1}))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data['id'], 1)
+ self.assertEqual(len(data['days']), 3)
+ self.assertTrue(any(day['slots'] for day in data['days']))
diff --git a/wger/trophies/tests/test_statistics_streaks.py b/wger/trophies/tests/test_statistics_streaks.py
new file mode 100644
index 000000000..76c906d34
--- /dev/null
+++ b/wger/trophies/tests/test_statistics_streaks.py
@@ -0,0 +1,204 @@
+# 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
+
+# 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)
+ 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)