Self hosted FLOSS fitness/workout, nutrition and weight tracker
Improve exercise deletion logic
Roland Geider67741607c4a9
diff --git a/wger/core/tests/base_testcase.py b/wger/core/tests/base_testcase.pyindex d583f96e7..a970e89d2 100644--- a/wger/core/tests/base_testcase.py+++ b/wger/core/tests/base_testcase.py@@ -124,6 +124,7 @@ class BaseTestCase:'test-muscles','test-exercises','test-exercise-images',+ 'test-exercise-videos','test-ingredients','test-nutrition-data','test-nutrition-diary',diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex a28839cc5..7da4cec07 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -114,7 +114,11 @@ class ExerciseViewSet(ModelViewSet):except ValueError:uuid = None- instance.delete(replace_by=uuid)+ instance.delete(+ replace_by=uuid,+ transfer_media='transfer_media' in self.request.query_params,+ transfer_translations='transfer_translations' in self.request.query_params,+ )class ExerciseTranslationViewSet(ModelViewSet):diff --git a/wger/exercises/fixtures/test-exercise-videos.json b/wger/exercises/fixtures/test-exercise-videos.jsonindex 65ffb5861..33f68c2b3 100644--- a/wger/exercises/fixtures/test-exercise-videos.json+++ b/wger/exercises/fixtures/test-exercise-videos.json@@ -3,7 +3,7 @@"pk": 1,"model": "exercises.exercisevideo","fields": {- "image": "exercise-images/1/protestschwein.jpg",+ "video": "exercise-images/1/protestschwein.jpg","exercise": 1,"is_main": true,"license": "1",@@ -20,7 +20,7 @@"pk": 2,"model": "exercises.exercisevideo","fields": {- "image": "exercise-images/1/wildschwein.jpg",+ "video": "exercise-images/1/wildschwein.jpg","exercise": 1,"is_main": false,"license": "2",@@ -36,7 +36,7 @@"pk": 3,"model": "exercises.exercisevideo","fields": {- "image": "exercise-images/1/wildschwein.jpg",+ "video": "exercise-images/1/wildschwein.jpg","exercise": 2,"is_main": false,"license": "2",diff --git a/wger/exercises/models/base.py b/wger/exercises/models/base.pyindex 7ea4d3cc4..8aa87c1ce 100644--- a/wger/exercises/models/base.py+++ b/wger/exercises/models/base.py@@ -247,13 +247,31 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):reset_exercise_api_cache(self.uuid)- def delete(self, using=None, keep_parents=False, replace_by: str = None):+ def delete(+ self,+ using=None,+ keep_parents=False,+ replace_by: str = None,+ transfer_media: bool = False,+ transfer_translations: bool = False,+ ):"""Save entry to deletion log and optionally replace references inworkout logs and routines before deleting.++ If ``transfer_media`` is set and a replacement is given, all images and+ videos of this exercise are reassigned to the replacement before+ deletion.++ If ``transfer_translations`` is set and a replacement is given, all+ translations whose language is not yet present on the replacement are+ reassigned."""# wgerfrom wger.exercises.models import DeletionLog+ from wger.exercises.models.image import ExerciseImage+ from wger.exercises.models.translation import Translation+ from wger.exercises.models.video import ExerciseVideofrom wger.manager.models import WorkoutLogfrom wger.manager.models.slot_entry import SlotEntry@@ -279,6 +297,20 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):SlotEntry.objects.filter(exercise=self).update(exercise=replacement)WorkoutLog.objects.filter(exercise=self).update(exercise=replacement)+ if transfer_media:+ ExerciseImage.objects.filter(exercise=self).update(exercise=replacement)+ ExerciseVideo.objects.filter(exercise=self).update(exercise=replacement)++ if transfer_translations:+ existing_languages = Translation.objects.filter(+ exercise=replacement,+ ).values_list('language_id', flat=True)+ Translation.objects.filter(exercise=self).exclude(+ language_id__in=list(existing_languages),+ ).update(exercise=replacement)+reset_exercise_api_cache(str(self.uuid))+ if replacement:+ reset_exercise_api_cache(str(replacement.uuid))return super().delete(using, keep_parents)diff --git a/wger/exercises/tests/api/test_exercise_delete_api.py b/wger/exercises/tests/api/test_exercise_delete_api.pynew file mode 100644index 000000000..601f20184--- /dev/null+++ b/wger/exercises/tests/api/test_exercise_delete_api.py@@ -0,0 +1,154 @@+# 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.exercises.models import (+ Exercise,+ Translation,+)+from wger.exercises.models.image import ExerciseImage+from wger.exercises.models.video import ExerciseVideo+++class ExerciseDeleteApiTestCase(BaseTestCase, ApiBaseTestCase):+ """+ Tests the DELETE endpoint of the exercise API, in particular the optional+ ``replaced_by``, ``transfer_media`` and ``transfer_translations`` query+ parameters.+ """++ # Source has 2 images, 2 videos, translations in lang 2 and lang 3.+ # Target has 1 image, 1 video, translation in lang 2.+ source_pk = 1+ target_pk = 2+ target_uuid = 'ae3328ba-9a35-4731-bc23-5da50720c5aa'++ def url(self):+ return f'/api/v2/exercise/{self.source_pk}/'++ def test_delete_without_replacement_cascades(self):+ """Without replace_by, related media and translations are dropped."""+ self.authenticate('admin')++ response = self.client.delete(self.url())++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(Exercise.objects.filter(pk=self.source_pk).exists())+ self.assertEqual(ExerciseImage.objects.filter(exercise_id=self.source_pk).count(), 0)+ self.assertEqual(ExerciseVideo.objects.filter(exercise_id=self.source_pk).count(), 0)++ def test_delete_with_replacement_no_transfer_flags(self):+ """+ With replace_by but no transfer flags, media and translations are+ cascade-deleted; only routine and log references move.+ """+ self.authenticate('admin')++ response = self.client.delete(f'{self.url()}?replaced_by={self.target_uuid}')++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ target = Exercise.objects.get(pk=self.target_pk)+ self.assertEqual(target.exerciseimage_set.count(), 1)+ self.assertEqual(target.exercisevideo_set.count(), 1)+ self.assertEqual(set(target.translations.values_list('language_id', flat=True)), {2})++ def test_delete_with_transfer_media(self):+ """transfer_media moves both images and videos to the replacement."""+ self.authenticate('admin')++ response = self.client.delete(+ f'{self.url()}?replaced_by={self.target_uuid}&transfer_media'+ )++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ target = Exercise.objects.get(pk=self.target_pk)+ self.assertEqual(target.exerciseimage_set.count(), 3)+ self.assertEqual(target.exercisevideo_set.count(), 3)++ def test_delete_with_transfer_translations(self):+ """+ transfer_translations moves translations whose language is not yet+ present on the replacement; languages already present are+ cascade-deleted.+ """+ self.authenticate('admin')++ response = self.client.delete(+ f'{self.url()}?replaced_by={self.target_uuid}&transfer_translations'+ )++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ target = Exercise.objects.get(pk=self.target_pk)+ self.assertEqual(set(target.translations.values_list('language_id', flat=True)), {2, 3})++ # The lang 3 translation was reassigned (its pk is preserved)+ moved = Translation.objects.get(pk=5)+ self.assertEqual(moved.exercise_id, self.target_pk)++ # The lang 2 translation on the source was cascade-deleted+ self.assertFalse(Translation.objects.filter(pk=1).exists())++ def test_delete_with_both_transfer_flags(self):+ """Both flags can be combined in a single request."""+ self.authenticate('admin')++ response = self.client.delete(+ f'{self.url()}?replaced_by={self.target_uuid}'+ '&transfer_media&transfer_translations'+ )++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ target = Exercise.objects.get(pk=self.target_pk)+ self.assertEqual(target.exerciseimage_set.count(), 3)+ self.assertEqual(target.exercisevideo_set.count(), 3)+ self.assertEqual(set(target.translations.values_list('language_id', flat=True)), {2, 3})++ def test_delete_transfer_flags_ignored_without_replacement(self):+ """Transfer flags without replace_by have no effect — full cascade."""+ self.authenticate('admin')++ response = self.client.delete(+ f'{self.url()}?transfer_media&transfer_translations'+ )++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(Exercise.objects.filter(pk=self.source_pk).exists())+ target = Exercise.objects.get(pk=self.target_pk)+ self.assertEqual(target.exerciseimage_set.count(), 1)+ self.assertEqual(target.exercisevideo_set.count(), 1)++ def test_delete_invalid_replaced_by_is_ignored(self):+ """An invalid UUID in replace_by is silently ignored."""+ self.authenticate('admin')++ response = self.client.delete(f'{self.url()}?replaced_by=not-a-uuid')++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(Exercise.objects.filter(pk=self.source_pk).exists())++ def test_delete_requires_authentication(self):+ """Anonymous users cannot delete exercises."""+ response = self.client.delete(self.url())++ self.assertIn(+ response.status_code,+ (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN),+ )+ self.assertTrue(Exercise.objects.filter(pk=self.source_pk).exists())diff --git a/wger/exercises/tests/test_deletion_log.py b/wger/exercises/tests/test_deletion_log.pyindex f17080df9..78cb23a04 100644--- a/wger/exercises/tests/test_deletion_log.py+++ b/wger/exercises/tests/test_deletion_log.py@@ -22,6 +22,8 @@ from wger.exercises.models import (Exercise,Translation,)+from wger.exercises.models.image import ExerciseImage+from wger.exercises.models.video import ExerciseVideofrom wger.manager.models import WorkoutLogfrom wger.manager.models.slot_entry import SlotEntry@@ -113,6 +115,97 @@ class DeletionLogTestCase(WgerTestCase):# The slot entry should now point to the replacementself.assertEqual(SlotEntry.objects.filter(exercise=replacement).count(), 2)+ def test_exercise_replace_by_transfers_media(self):+ """+ Test that images and videos of the deleted exercise are reassigned to+ the replacement when transfer_media is set.+ """+ exercise_to_delete = Exercise.objects.get(pk=1)+ replacement = Exercise.objects.get(pk=2)++ self.assertEqual(ExerciseImage.objects.filter(exercise=exercise_to_delete).count(), 2)+ self.assertEqual(ExerciseImage.objects.filter(exercise=replacement).count(), 1)+ self.assertEqual(ExerciseVideo.objects.filter(exercise=exercise_to_delete).count(), 2)+ self.assertEqual(ExerciseVideo.objects.filter(exercise=replacement).count(), 1)++ exercise_to_delete.delete(replace_by=str(replacement.uuid), transfer_media=True)++ self.assertEqual(ExerciseImage.objects.filter(exercise=replacement).count(), 3)+ self.assertEqual(ExerciseVideo.objects.filter(exercise=replacement).count(), 3)++ def test_exercise_replace_by_does_not_transfer_media_by_default(self):+ """+ Test that images and videos are cascade-deleted with the exercise when+ transfer_media is not set, even if a replacement is provided.+ """+ exercise_to_delete = Exercise.objects.get(pk=1)+ replacement = Exercise.objects.get(pk=2)++ self.assertEqual(ExerciseImage.objects.filter(exercise=replacement).count(), 1)+ self.assertEqual(ExerciseVideo.objects.filter(exercise=replacement).count(), 1)++ exercise_to_delete.delete(replace_by=str(replacement.uuid))++ self.assertEqual(ExerciseImage.objects.filter(exercise=replacement).count(), 1)+ self.assertEqual(ExerciseVideo.objects.filter(exercise=replacement).count(), 1)++ def test_exercise_replace_by_transfers_translations_in_missing_languages(self):+ """+ Test that translations of the deleted exercise whose language is not+ yet present on the replacement are reassigned. Translations in+ languages already present on the replacement are cascade-deleted.+ """+ exercise_to_delete = Exercise.objects.get(pk=1)+ replacement = Exercise.objects.get(pk=2)++ # ex1 has lang 2 ("An exercise", pk=1) and lang 3 ("Test exercise 123", pk=5)+ # ex2 has lang 2 ("Very cool exercise", pk=2)+ self.assertEqual(set(replacement.translations.values_list('language_id', flat=True)), {2})++ exercise_to_delete.delete(replace_by=str(replacement.uuid), transfer_translations=True)++ replacement.refresh_from_db()+ languages_on_replacement = set(+ replacement.translations.values_list('language_id', flat=True)+ )+ self.assertEqual(languages_on_replacement, {2, 3})++ # The lang 3 translation moved over (pk preserved)+ moved = Translation.objects.get(pk=5)+ self.assertEqual(moved.exercise_id, replacement.pk)+ self.assertEqual(moved.name, 'Test exercise 123')++ # The lang 2 translation on the source was cascade-deleted+ self.assertFalse(Translation.objects.filter(pk=1).exists())++ def test_exercise_replace_by_does_not_transfer_translations_by_default(self):+ """+ Test that translations are cascade-deleted with the exercise when+ transfer_translations is not set, even with a replacement.+ """+ exercise_to_delete = Exercise.objects.get(pk=1)+ replacement = Exercise.objects.get(pk=2)++ exercise_to_delete.delete(replace_by=str(replacement.uuid))++ replacement.refresh_from_db()+ languages_on_replacement = set(+ replacement.translations.values_list('language_id', flat=True)+ )+ self.assertEqual(languages_on_replacement, {2})++ def test_exercise_replace_by_transfer_flags_ignored_without_replacement(self):+ """+ Test that transfer flags have no effect if no replacement is given —+ everything cascades as usual.+ """+ exercise_to_delete = Exercise.objects.get(pk=1)+ exercise_to_delete.delete(transfer_media=True, transfer_translations=True)++ self.assertFalse(Exercise.objects.filter(pk=1).exists())+ self.assertEqual(ExerciseImage.objects.filter(exercise_id=1).count(), 0)+ self.assertEqual(ExerciseVideo.objects.filter(exercise_id=1).count(), 0)+def test_exercise_delete_without_replace_by_does_not_keep_references(self):"""Test that deleting without replace_by does not attempt to update