Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Correctly generate activity stream entries when submitting exercises

Roland Geidere8a4cb71ddc4
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py
index 532d58a67..6c2fa04a0 100644
--- a/wger/exercises/api/serializers.py
+++ b/wger/exercises/api/serializers.py
@@ -23,6 +23,7 @@ from django.db import transaction
from django.db.models import Q
# Third Party
+from actstream import action as actstream_action
from lingua import LanguageDetectorBuilder
from rest_framework import serializers
@@ -43,6 +44,7 @@ from wger.exercises.models import (
Muscle,
Translation,
)
+from wger.exercises.views.helper import StreamVerbs
from wger.utils.cache import CacheKeyMapper
from wger.utils.constants import CC_BY_SA_4_LICENSE_ID
@@ -50,6 +52,23 @@ from wger.utils.constants import CC_BY_SA_4_LICENSE_ID
logger = logging.getLogger(__name__)
+def _log_action_creation(serializer, instance):
+ """
+ Emit an actstream ``created`` event for a freshly-created instance.
+
+ Used by the submission serializers, which create nested objects directly
+ instead of going through the regular ViewSet ``perform_create`` path.
+ """
+ request = serializer.context.get('request')
+ if request is None or not getattr(request.user, 'is_authenticated', False):
+ return
+ actstream_action.send(
+ request.user,
+ verb=StreamVerbs.CREATED.value,
+ action_object=instance,
+ )
+
+
class ExerciseSerializer(serializers.ModelSerializer):
"""
Exercise serializer
@@ -254,6 +273,7 @@ class ExerciseCommentSubmissionSerializer(serializers.ModelSerializer):
# Create the comment with the parent translation
comment = ExerciseComment.objects.create(translation=translation, **validated_data)
+ _log_action_creation(self, comment)
return comment
@@ -294,6 +314,7 @@ class ExerciseAliasSubmissionSerializer(serializers.ModelSerializer):
# Create the Alias with the parent translation
alias = Alias.objects.create(translation=translation, **validated_data)
+ _log_action_creation(self, alias)
return alias
@@ -363,9 +384,9 @@ class MuscleSerializer(serializers.ModelSerializer):
return None
-class ExerciseTranslationBaseInfoSerializer(serializers.ModelSerializer):
+class ExerciseTranslationInfoSerializer(serializers.ModelSerializer):
"""
- Exercise translation serializer for the base info endpoint
+ Exercise translation serializer for the info endpoint
"""
id = serializers.IntegerField(required=False, read_only=True)
@@ -467,6 +488,7 @@ class ExerciseTranslationSubmissionSerializer(serializers.ModelSerializer):
# Create the translation with the parent exercise
translation = Translation.objects.create(exercise=exercise, **validated_data)
+ _log_action_creation(self, translation)
# Create the individual aliases
for alias_data in aliases_data:
@@ -548,7 +570,7 @@ class ExerciseInfoSerializer(serializers.ModelSerializer):
muscles = MuscleSerializer(many=True, read_only=True)
muscles_secondary = MuscleSerializer(many=True, read_only=True)
equipment = EquipmentSerializer(many=True, read_only=True)
- translations = ExerciseTranslationBaseInfoSerializer(many=True, read_only=True)
+ translations = ExerciseTranslationInfoSerializer(many=True, read_only=True)
videos = ExerciseVideoInfoSerializer(source='exercisevideo_set', many=True, read_only=True)
author_history = serializers.ListSerializer(child=serializers.CharField())
total_authors_history = serializers.ListSerializer(child=serializers.CharField())
@@ -692,6 +714,7 @@ class ExerciseSubmissionSerializer(serializers.ModelSerializer):
exercise.muscles.set(validated_data.pop('muscles'))
exercise.muscles_secondary.set(validated_data.pop('muscles_secondary'))
exercise.equipment.set(validated_data.pop('equipment'))
+ _log_action_creation(self, exercise)
# Create the individual translations
for translation in validated_data.pop('translations', []):
diff --git a/wger/exercises/tests/api/__init__.py b/wger/exercises/tests/api/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/wger/exercises/tests/api/test_exercise_submission_api.py b/wger/exercises/tests/api/test_exercise_submission_api.py
index 048f83cbf..3e6339863 100644
--- a/wger/exercises/tests/api/test_exercise_submission_api.py
+++ b/wger/exercises/tests/api/test_exercise_submission_api.py
@@ -17,6 +17,7 @@
from collections import namedtuple
# Third Party
+from actstream.models import Action
from rest_framework import status
# wger
@@ -28,6 +29,7 @@ from wger.exercises.models import (
ExerciseComment,
Translation,
)
+from wger.exercises.views.helper import StreamVerbs
class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
@@ -46,7 +48,7 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
'translations': [
{
'name': '1-Arm Half-Kneeling Lat Pulldown',
- 'description': 'Attach a D-Handle to a high pully. And use your lat muscles to pull the weight single handedly.',
+ 'description_source': 'Attach a D-Handle to a high pully. And use your lat muscles to pull the weight single handedly.',
'language': 2,
'license_author': 'tester',
'aliases': [
@@ -54,14 +56,14 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
{'alias': 'yet another name'},
],
'comments': [
- {'comment': 'This is a very important note'},
- {'comment': 'Do the exercise correctly'},
- {'comment': 'the third comment'},
+ {'comment': 'This is a very important note about the exercise'},
+ {'comment': 'Do the exercise correctly and keep your back straight'},
+ {'comment': 'Remember to breathe out during the exertion phase'},
],
},
{
'name': '2 Handed Kettlebell Swing',
- 'description': '<p>das ist die Beschreibung für die Übung</p>',
+ 'description_source': 'das ist die Beschreibung für die Übung',
'language': 1,
'license_author': 'tester',
},
@@ -175,6 +177,22 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
['You must provide at least one translation in English.'],
)
+ def test_submission_creates_actstream_events(self):
+ """
+ Every object created via the submission API produces a CREATED actstream event
+ """
+
+ self.authenticate('admin')
+
+ actions_before = Action.objects.filter(verb=StreamVerbs.CREATED.value).count()
+ response = self.client.post(self.url, data=self.get_payload())
+ actions_after = Action.objects.filter(verb=StreamVerbs.CREATED.value).count()
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ # Payload has: 1 exercise + 2 translations + 2 aliases + 3 comments = 8
+ self.assertEqual(actions_after - actions_before, 8)
+
def test_successfully_creates_new_variation(self):
"""
Correctly connects the new exercise to another exercise via a new variation.
diff --git a/wger/exercises/tests/api_mixins.py b/wger/exercises/tests/api_mixins.py
new file mode 100644
index 000000000..cacf7944f
--- /dev/null
+++ b/wger/exercises/tests/api_mixins.py
@@ -0,0 +1,71 @@
+# 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.contrib.contenttypes.models import ContentType
+
+# Third Party
+from actstream.models import Action
+from rest_framework import status
+
+# wger
+from wger.exercises.views.helper import StreamVerbs
+
+
+class _ActstreamMixinBase:
+ """
+ Common helpers for the actstream-event mixins.
+
+ The model whose ContentType the emitted events reference defaults to
+ ``self.resource`` (already set on the standard API test cases) and can be
+ overridden via ``actstream_model`` when the two diverge.
+ """
+
+ actstream_model = None
+
+ def _actstream_model(self):
+ return self.actstream_model or self.resource
+
+ def _count_actions(self, verb):
+ ct = ContentType.objects.get_for_model(self._actstream_model())
+ return Action.objects.filter(
+ verb=verb,
+ action_object_content_type=ct,
+ ).count()
+
+
+class ActstreamCreateMixin(_ActstreamMixinBase):
+ """POSTing ``self.data`` to ``self.url`` emits a CREATED actstream event."""
+
+ def test_actstream_event_on_create(self):
+ self.authenticate('admin')
+ before = self._count_actions(StreamVerbs.CREATED.value)
+ response = self.client.post(self.url, data=self.data)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(self._count_actions(StreamVerbs.CREATED.value), before + 1)
+
+
+class ActstreamUpdateMixin(_ActstreamMixinBase):
+ """PATCHing ``self.data`` to ``self.url_detail`` emits an UPDATED event."""
+
+ def test_actstream_event_on_update(self):
+ self.authenticate('admin')
+ before = self._count_actions(StreamVerbs.UPDATED.value)
+ response = self.client.patch(self.url_detail, data=self.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(self._count_actions(StreamVerbs.UPDATED.value), before + 1)
+
+
+class ActstreamApiMixin(ActstreamCreateMixin, ActstreamUpdateMixin):
+ """Covers both create and update — for endpoints supporting POST + PATCH."""
diff --git a/wger/exercises/tests/test_alias.py b/wger/exercises/tests/test_alias.py
index 4e941f9c8..1a85af4c2 100644
--- a/wger/exercises/tests/test_alias.py
+++ b/wger/exercises/tests/test_alias.py
@@ -14,10 +14,13 @@
# wger
from wger.core.tests.api_base_test import ExerciseCrudApiTestCase
+from wger.exercises.models import Alias
+from wger.exercises.tests.api_mixins import ActstreamApiMixin
-class AliasCustomApiTestCase(ExerciseCrudApiTestCase):
+class AliasCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTestCase):
pk = 1
+ resource = Alias
data = {
'translation': 1,
diff --git a/wger/exercises/tests/test_exercise.py b/wger/exercises/tests/test_exercise.py
index 71a18e7e0..78a5ff4a6 100644
--- a/wger/exercises/tests/test_exercise.py
+++ b/wger/exercises/tests/test_exercise.py
@@ -26,6 +26,7 @@ from wger.exercises.models import (
Exercise,
Translation,
)
+from wger.exercises.tests.api_mixins import ActstreamApiMixin
from wger.utils.constants import CC_BY_SA_4_LICENSE_ID
@@ -97,8 +98,9 @@ class ExerciseTestCase(WgerTestCase):
)
-class ExerciseCustomApiTestCase(ExerciseCrudApiTestCase):
+class ExerciseCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTestCase):
pk = 1
+ resource = Exercise
data = {
'category': 3,
diff --git a/wger/exercises/tests/test_exercise_comments.py b/wger/exercises/tests/test_exercise_comments.py
index 2b5e959dd..66fdfabc4 100644
--- a/wger/exercises/tests/test_exercise_comments.py
+++ b/wger/exercises/tests/test_exercise_comments.py
@@ -16,6 +16,7 @@
from wger.core.tests.api_base_test import ExerciseCrudApiTestCase
from wger.core.tests.base_testcase import WgerTestCase
from wger.exercises.models import ExerciseComment
+from wger.exercises.tests.api_mixins import ActstreamApiMixin
class ExerciseCommentRepresentationTestCase(WgerTestCase):
@@ -30,7 +31,7 @@ class ExerciseCommentRepresentationTestCase(WgerTestCase):
self.assertEqual(str(ExerciseComment.objects.get(pk=1)), 'test 123')
-class ExerciseCommentApiTestCase(ExerciseCrudApiTestCase):
+class ExerciseCommentApiTestCase(ActstreamApiMixin, ExerciseCrudApiTestCase):
"""
Tests the exercise comment overview resource
"""
diff --git a/wger/exercises/tests/test_exercise_images.py b/wger/exercises/tests/test_exercise_images.py
index 8c885c50d..346776eac 100644
--- a/wger/exercises/tests/test_exercise_images.py
+++ b/wger/exercises/tests/test_exercise_images.py
@@ -24,6 +24,7 @@ from wger.exercises.models import (
ExerciseImage,
Translation,
)
+from wger.exercises.tests.api_mixins import ActstreamUpdateMixin
class MainImageTestCase(WgerTestCase):
@@ -206,6 +207,7 @@ class ExerciseImageFromJsonSimpleTests(SimpleTestCase):
# TODO: add POST and DELETE tests
class ExerciseImagesApiTestCase(
+ ActstreamUpdateMixin,
api_base_test.BaseTestCase,
api_base_test.ApiBaseTestCase,
api_base_test.ApiGetTestCase,
@@ -218,3 +220,4 @@ class ExerciseImagesApiTestCase(
private_resource = False
resource = ExerciseImage
overview_cached = True
+ data = {'is_main': True}
diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.py
index e63f0ad37..bc92b5695 100644
--- a/wger/exercises/tests/test_exercise_translation.py
+++ b/wger/exercises/tests/test_exercise_translation.py
@@ -24,6 +24,7 @@ from wger.exercises.models import (
Muscle,
Translation,
)
+from wger.exercises.tests.api_mixins import ActstreamApiMixin
from wger.utils.constants import (
CC_0_LICENSE_ID,
CC_BY_SA_4_LICENSE_ID,
@@ -114,8 +115,9 @@ class ExerciseInfoApiTestCase(
return 'exerciseinfo'
-class ExerciseTranslationCustomApiTestCase(ExerciseCrudApiTestCase):
+class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTestCase):
pk = 1
+ resource = Translation
data = {
'name': 'A new name',
diff --git a/wger/exercises/tests/test_exercise_videos.py b/wger/exercises/tests/test_exercise_videos.py
new file mode 100644
index 000000000..57d8fbf5c
--- /dev/null
+++ b/wger/exercises/tests/test_exercise_videos.py
@@ -0,0 +1,40 @@
+# 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
+
+# wger
+from wger.core.tests import api_base_test
+from wger.exercises.models import ExerciseVideo
+from wger.exercises.tests.api_mixins import ActstreamUpdateMixin
+
+
+# TODO: add POST and DELETE tests
+class ExerciseVideosApiTestCase(
+ ActstreamUpdateMixin,
+ api_base_test.BaseTestCase,
+ api_base_test.ApiBaseTestCase,
+ api_base_test.ApiGetTestCase,
+):
+ """
+ Tests the exercise video resource
+ """
+
+ pk = 1
+ private_resource = False
+ resource = ExerciseVideo
+ overview_cached = False
+ data = {'is_main': True}
+
+ def get_resource_name(self):
+ # The video endpoint is registered as ``video``, not ``exercisevideo``.
+ return 'video'
diff --git a/wger/exercises/tests/test_history.py b/wger/exercises/tests/test_history.py
index d38f78b3a..550c4676c 100644
--- a/wger/exercises/tests/test_history.py
+++ b/wger/exercises/tests/test_history.py
@@ -92,9 +92,10 @@ class ExerciseHistoryControl(WgerTestCase):
self.assertEqual(translation.description, 'Boring exercise')
-class ExerciseHistoryControlRegression(WgerTestCase):
+class ExerciseHistoryControlExtras(WgerTestCase):
"""
- Regression tests for the rewritten history control view.
+ Tests for pagination, filters and contributor flagging on the history
+ control view.
"""
def setUp(self):