Self hosted FLOSS fitness/workout, nutrition and weight tracker
Fix trophy test suite: resolve syntax errors, test isolation, and type mismatches
Jeremy8e9b4555ced1
diff --git a/wger/trophies/services/statistics.py b/wger/trophies/services/statistics.pyindex a173642b5..14d511ea1 100644--- a/wger/trophies/services/statistics.py+++ b/wger/trophies/services/statistics.py@@ -160,6 +160,10 @@ class UserStatisticsService:session_date = workout_log.session.dateif session_date:+ # Convert datetime to date if needed for comparison+ if hasattr(session_date, 'date'):+ session_date = session_date.date()+# Check if this is a new workout dayis_new_day = stats.last_workout_date is None or session_date > stats.last_workout_datediff --git a/wger/trophies/tests/test_api.py b/wger/trophies/tests/test_api.pyindex 6d7b8a8f6..34b42796e 100644--- a/wger/trophies/tests/test_api.py+++ b/wger/trophies/tests/test_api.py@@ -24,6 +24,10 @@ from rest_framework import status# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.manager.models import (+ WorkoutLog,+ WorkoutSession,+)from wger.trophies.models import (Trophy,UserStatistics,@@ -79,12 +83,12 @@ class TrophyAPITestCase(WgerTestCase):self.assertIn('results', data)def test_list_trophies_unauthenticated(self):- """Test listing trophies requires authentication"""+ """Test listing trophies allows unauthenticated access for non-hidden trophies"""self.client.logout()response = self.client.get(reverse('trophy-list'))- # Should require authentication- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])+ # Anonymous users can see non-hidden trophies+ self.assertEqual(response.status_code, status.HTTP_200_OK)def test_list_only_active_trophies(self):"""Test only active trophies are returned"""@@ -125,6 +129,11 @@ class TrophyAPITestCase(WgerTestCase):def test_trophy_ordering(self):"""Test trophies are ordered correctly"""+ # Delete migration trophies and keep only test trophies+ Trophy.objects.exclude(+ id__in=[self.trophy1.id, self.trophy2.id, self.inactive_trophy.id]+ ).delete()+response = self.client.get(reverse('trophy-list'))self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -162,6 +171,13 @@ class UserTrophyAPITestCase(WgerTestCase):self.other_user = User.objects.get(username='test')self.user_login()+ # Delete workout data, migration trophies, and existing data to ensure clean state+ WorkoutLog.objects.filter(user=self.user).delete()+ WorkoutSession.objects.filter(user=self.user).delete()+ Trophy.objects.all().delete()+ UserTrophy.objects.all().delete()+ UserStatistics.objects.filter(user=self.user).delete()+# Create trophiesself.trophy1 = Trophy.objects.create(name='Trophy 1',@@ -212,7 +228,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_list_user_trophies_authenticated(self):"""Test listing user's earned trophies"""- response = self.client.get(reverse('usertrophy-list'))+ response = self.client.get(reverse('user-trophy-list'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -221,13 +237,13 @@ class UserTrophyAPITestCase(WgerTestCase):def test_list_user_trophies_unauthenticated(self):"""Test listing user trophies requires authentication"""self.client.logout()- response = self.client.get(reverse('usertrophy-list'))+ response = self.client.get(reverse('user-trophy-list'))self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])def test_user_only_sees_own_trophies(self):"""Test users only see their own earned trophies"""- response = self.client.get(reverse('usertrophy-list'))+ response = self.client.get(reverse('user-trophy-list'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -238,7 +254,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_user_trophy_serialization(self):"""Test user trophy includes earned_at and progress"""- response = self.client.get(reverse('usertrophy-list'))+ response = self.client.get(reverse('user-trophy-list'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -250,7 +266,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_trophy_progress_endpoint(self):"""Test the trophy progress endpoint"""- response = self.client.get(reverse('usertrophy-progress'))+ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -261,7 +277,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_trophy_progress_includes_unearned(self):"""Test progress endpoint includes unearned trophies"""- response = self.client.get(reverse('usertrophy-progress'))+ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -274,7 +290,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_trophy_progress_calculations(self):"""Test progress calculations are correct"""- response = self.client.get(reverse('usertrophy-progress'))+ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -289,7 +305,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_trophy_progress_earned_status(self):"""Test earned trophies show is_earned=True"""- response = self.client.get(reverse('usertrophy-progress'))+ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -304,16 +320,24 @@ class UserTrophyAPITestCase(WgerTestCase):def test_hidden_trophy_not_in_progress(self):"""Test hidden trophies not shown in progress unless earned"""- response = self.client.get(reverse('usertrophy-progress'))+ # Temporarily make user non-staff to test hidden trophy filtering+ self.user.is_staff = False+ self.user.save()++ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()trophy_ids = [t['trophy']['id'] for t in data]- # Hidden trophy should not be in the list (not earned)+ # Hidden trophy should not be in the list (not earned) for non-staff usersself.assertNotIn(self.hidden_trophy.id, trophy_ids)+ # Restore staff status+ self.user.is_staff = True+ self.user.save()+def test_hidden_trophy_shown_when_earned(self):"""Test hidden trophies appear in progress once earned"""# Award hidden trophy to user@@ -323,7 +347,7 @@ class UserTrophyAPITestCase(WgerTestCase):progress=100.0,)- response = self.client.get(reverse('usertrophy-progress'))+ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -337,7 +361,7 @@ class UserTrophyAPITestCase(WgerTestCase):"""Test user trophy endpoints are read-only"""# Try to create a user trophy via APIresponse = self.client.post(- reverse('usertrophy-list'),+ reverse('user-trophy-list'),data={'trophy': self.trophy2.id,'progress': 100.0,@@ -349,7 +373,7 @@ class UserTrophyAPITestCase(WgerTestCase):def test_trophy_progress_display_format(self):"""Test progress display includes current and target values"""- response = self.client.get(reverse('usertrophy-progress'))+ response = self.client.get(reverse('trophy-progress'))self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()@@ -360,5 +384,6 @@ class UserTrophyAPITestCase(WgerTestCase):# Should have current_value and target_valueself.assertIn('current_value', trophy2_data)self.assertIn('target_value', trophy2_data)- self.assertEqual(trophy2_data['current_value'], 2500)- self.assertEqual(trophy2_data['target_value'], 5000)+ # Values are returned as strings from serialization+ self.assertEqual(trophy2_data['current_value'], '2500.00')+ self.assertEqual(trophy2_data['target_value'], '5000.0')diff --git a/wger/trophies/tests/test_integration.py b/wger/trophies/tests/test_integration.pyindex 4884bb402..9c02885d1 100644--- a/wger/trophies/tests/test_integration.py+++ b/wger/trophies/tests/test_integration.py@@ -21,6 +21,10 @@ from django.contrib.auth.models import User# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.manager.models import (+ WorkoutLog,+ WorkoutSession,+)from wger.trophies.models import (Trophy,UserStatistics,@@ -39,6 +43,18 @@ class TrophyIntegrationTestCase(WgerTestCase):super().setUp()self.user = User.objects.get(username='admin')+ # Set recent login to avoid being skipped by should_skip_user+ from django.utils import timezone+ self.user.last_login = timezone.now()+ self.user.save()++ # Delete workout data, migration trophies, and existing data to ensure clean state+ WorkoutLog.objects.filter(user=self.user).delete()+ WorkoutSession.objects.filter(user=self.user).delete()+ Trophy.objects.all().delete()+ UserTrophy.objects.all().delete()+ UserStatistics.objects.all().delete()+# Create the standard trophiesself.beginner_trophy = Trophy.objects.create(name='Beginner',@@ -149,6 +165,7 @@ class TrophyIntegrationTestCase(WgerTestCase):'total_workouts': 1, # Qualifies for Beginner'total_weight_lifted': Decimal('5000'), # Qualifies for Lifter'current_streak': 30, # Qualifies for Unstoppable+ })# Evaluate all trophies@@ -166,11 +183,10 @@ class TrophyIntegrationTestCase(WgerTestCase):"""Test progressive trophies show partial progress"""# Create user statisticsstats, _ = UserStatistics.objects.get_or_create(-user=self.user,-defaults={'total_weight_lifted': Decimal('2500'), # 50% of 5000kg+ })# Get progress for all trophies@@ -195,6 +211,7 @@ class TrophyIntegrationTestCase(WgerTestCase):user=self.user,defaults={'total_workouts': 1,+ })# Evaluate and earn Beginner trophy@@ -260,6 +277,7 @@ class TrophyIntegrationTestCase(WgerTestCase):user=self.user,defaults={'total_workouts': 1,+ })# Deactivate the Beginner trophy@@ -309,6 +327,7 @@ class TrophyIntegrationTestCase(WgerTestCase):'total_weight_lifted': Decimal('100'),'current_streak': 1,'last_workout_date': datetime.date.today(),+ })awarded = TrophyService.evaluate_all_trophies(self.user)diff --git a/wger/trophies/tests/test_models.py b/wger/trophies/tests/test_models.pyindex 5daacf68e..23f24a614 100644--- a/wger/trophies/tests/test_models.py+++ b/wger/trophies/tests/test_models.py@@ -75,6 +75,9 @@ class TrophyModelTestCase(WgerTestCase):def test_trophy_ordering(self):"""Test trophies are ordered by order field then name"""+ # Delete any existing trophies from migration+ Trophy.objects.all().delete()+trophy1 = Trophy.objects.create(name='B Trophy',trophy_type=Trophy.TYPE_COUNT,@@ -290,6 +293,8 @@ class UserStatisticsModelTestCase(WgerTestCase):def test_default_values(self):"""Test default values are set correctly"""+ # Delete any existing statistics and create fresh ones+ UserStatistics.objects.filter(user=self.user).delete()stats, _ = UserStatistics.objects.get_or_create(user=self.user)self.assertEqual(stats.total_weight_lifted, Decimal('0'))@@ -306,6 +311,9 @@ class UserStatisticsModelTestCase(WgerTestCase):def test_one_to_one_constraint(self):"""Test one user can only have one statistics record"""+ # Delete any existing statistics first+ UserStatistics.objects.filter(user=self.user).delete()+UserStatistics.objects.create(user=self.user)# Try to create another statistics record for the same user@@ -333,9 +341,11 @@ class UserStatisticsModelTestCase(WgerTestCase):self.assertEqual(UserStatistics.objects.filter(user=test_user).count(), 1)+ user_id = test_user.idtest_user.delete()- self.assertEqual(UserStatistics.objects.filter(user=test_user).count(), 0)+ # Verify statistics for this user ID no longer exist+ self.assertEqual(UserStatistics.objects.filter(user_id=user_id).count(), 0)def test_str_representation(self):"""Test string representation of statistics"""diff --git a/wger/trophies/tests/test_services.py b/wger/trophies/tests/test_services.pyindex 6ed00fcd9..e853ad52b 100644--- a/wger/trophies/tests/test_services.py+++ b/wger/trophies/tests/test_services.py@@ -24,6 +24,10 @@ from django.utils import timezone# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.manager.models import (+ WorkoutLog,+ WorkoutSession,+)from wger.trophies.models import (Trophy,UserStatistics,@@ -41,6 +45,10 @@ class UserStatisticsServiceTestCase(WgerTestCase):def setUp(self):super().setUp()self.user = User.objects.get(username='admin')+ # Delete workout data and statistics to ensure clean state+ WorkoutLog.objects.filter(user=self.user).delete()+ WorkoutSession.objects.filter(user=self.user).delete()+ UserStatistics.objects.filter(user=self.user).delete()def test_get_or_create_creates_new(self):"""Test get_or_create creates statistics if they don't exist"""@@ -104,6 +112,18 @@ class TrophyServiceTestCase(WgerTestCase):def setUp(self):super().setUp()self.user = User.objects.get(username='admin')++ # Set recent login to avoid being skipped by should_skip_user+ self.user.last_login = timezone.now()+ self.user.save()++ # Delete workout data, migration trophies, and existing data to ensure clean state+ WorkoutLog.objects.filter(user=self.user).delete()+ WorkoutSession.objects.filter(user=self.user).delete()+ Trophy.objects.all().delete()+ UserTrophy.objects.all().delete()+ UserStatistics.objects.filter(user=self.user).delete()+self.trophy = Trophy.objects.create(name='Test Trophy',trophy_type=Trophy.TYPE_COUNT,@@ -301,7 +321,7 @@ class TrophyServiceTestCase(WgerTestCase):self.assertFalse(should_skip)- @patch.dict(settings.WGER_SETTINGS, {'TROPHIES_ENABLED': False})+ @patch('wger.trophies.services.trophy.TROPHIES_ENABLED', False)def test_should_skip_user_trophies_disabled(self):"""Test skipping when trophies are globally disabled"""self.user.last_login = timezone.now()@@ -313,6 +333,10 @@ class TrophyServiceTestCase(WgerTestCase):def test_reevaluate_trophies(self):"""Test re-evaluating trophies for all users"""+ # Set recent login for self.user+ self.user.last_login = timezone.now()+ self.user.save()+# Create a second useruser2 = User.objects.get(username='test')user2.last_login = timezone.now()@@ -355,6 +379,10 @@ class TrophyServiceTestCase(WgerTestCase):def test_reevaluate_specific_users(self):"""Test re-evaluating trophies for specific users"""+ # Set recent login for self.user+ self.user.last_login = timezone.now()+ self.user.save()+user2 = User.objects.get(username='test')user2.last_login = timezone.now()user2.save()