From dcc04890b7ce0471affa101cc59e13488fd8025f Mon Sep 17 00:00:00 2001 From: pampletousse <51699553+pampletousse@users.noreply.github.com> Date: Tue, 6 Feb 2024 11:25:48 +0100 Subject: [PATCH] [DONE] Pampletousse/fix add bulk update test (#1042) * Change default sort dashboard videos title into date_added * Try to add new test for bulk_update function * Add status code and use bulk_update function * Try to add user * Resolve format json * User fix * Try to dumps data * Remove json stringigy and loads on simple string parameter * Replace file with Badatos's version * Add Language Code variable to wsgirequest * Add Language Code variable to wsgirequest again * Try to use TransactionTestCase * Add len function to assertion * Try to fix test with pk instead of id + remove tear down on blocking test * Try to fix unique constraint error with serialized_rollback * Try to fix unique constraint error with tearDown class * Try to fix video_update_owner test removing futures.theadpoolexecutor * Fix pep8 * Remove unused import, add pydoc + try to fix pep8 * Rollback change function change_owner + change values in test * Update views.py Add typing and change number to int * Update views.py remove ":" --------- Co-authored-by: pampletousse Co-authored-by: Ptitloup --- pod/video/static/js/dashboard.js | 2 +- pod/video/tests/test_bulk_update.py | 157 ++++++++++++++++++++++++++++ pod/video/tests/test_views.py | 9 +- pod/video/views.py | 16 ++- 4 files changed, 174 insertions(+), 10 deletions(-) create mode 100644 pod/video/tests/test_bulk_update.py diff --git a/pod/video/static/js/dashboard.js b/pod/video/static/js/dashboard.js index d253ba185f..562eb1af6d 100644 --- a/pod/video/static/js/dashboard.js +++ b/pod/video/static/js/dashboard.js @@ -117,7 +117,7 @@ async function bulkUpdate() { // Construct formData to send formData.append("selected_videos", JSON.stringify(selectedVideos)); formData.append("update_fields", JSON.stringify(updateFields)); - formData.append("update_action", JSON.stringify(updateAction)); + formData.append("update_action", updateAction); // Post asynchronous request let response = await fetch(urlUpdateVideos, { diff --git a/pod/video/tests/test_bulk_update.py b/pod/video/tests/test_bulk_update.py new file mode 100644 index 0000000000..f618854c3e --- /dev/null +++ b/pod/video/tests/test_bulk_update.py @@ -0,0 +1,157 @@ +"""Unit tests for videos bulk update. + +* run with `python manage.py test pod.video.tests.test_bulk_update +""" + +from datetime import datetime + +from django.contrib.sites.models import Site +from django.test import RequestFactory, Client, TransactionTestCase + +from pod.authentication.backends import User +from pod.video.models import Video, Type +from pod.video.views import bulk_update + + +class BulkUpdateTestCase(TransactionTestCase): + """Test the videos bulk update.""" + + fixtures = [ + "initial_data.json", + ] + serialized_rollback = True + + def setUp(self): + """Create videos to be tested.""" + self.factory = RequestFactory() + self.client = Client() + + site = Site.objects.get(pk=1) + user1 = User.objects.create( + username="pod1", password="pod1234pod", email="pod@univ.fr" + ) + user2 = User.objects.create( + username="pod2", password="pod1234pod", email="pod@univ.fr" + ) + user3 = User.objects.create( + username="pod3", password="pod1234pod", email="pod@univ.fr" + ) + + type1 = Type.objects.create(title="type1") + type2 = Type.objects.create(title="type2") + + Video.objects.create( + type=type1, + title="Video1", + password=None, + date_added=datetime.today(), + encoding_in_progress=False, + owner=user1, + date_evt=datetime.today(), + video="test.mp4", + allow_downloading=True, + description="test", + is_draft=False, + duration=3, + ) + + Video.objects.create( + type=type1, + title="Video2", + password=None, + date_added=datetime.today(), + encoding_in_progress=False, + owner=user2, + date_evt=datetime.today(), + video="test.mp4", + allow_downloading=True, + description="test", + is_draft=False, + duration=3, + ) + + Video.objects.create( + type=type2, + title="Video3", + password=None, + date_added=datetime.today(), + encoding_in_progress=False, + owner=user2, + date_evt=datetime.today(), + video="test.mp4", + allow_downloading=True, + description="test", + is_draft=False, + duration=3, + ) + + Video.objects.create( + type=type2, + title="Video4", + password=None, + date_added=datetime.today(), + encoding_in_progress=False, + owner=user3, + date_evt=datetime.today(), + video="test.mp4", + allow_downloading=True, + description="test", + is_draft=False, + duration=3, + ) + + Video.objects.create( + type=type2, + title="Video5", + password=None, + date_added=datetime.today(), + encoding_in_progress=False, + owner=user3, + date_evt=datetime.today(), + video="test.mp4", + allow_downloading=True, + description="test", + is_draft=False, + duration=3, + ) + + for vid in Video.objects.all(): + vid.sites.add(site) + + print(" ---> SetUp of BulkUpdateTestCase: OK!") + + def test_bulk_update_title(self): + """Test bulk update of title attribute.""" + video1 = Video.objects.get(pk=1) + video2 = Video.objects.get(pk=2) + + user1 = User.objects.get(username="pod1") + + self.client.force_login(user1) + + post_request = self.factory.post( + '/bulk_update/', + { + 'title': 'Modified Title', + 'selected_videos': '["%s", "%s"]' % (video1.slug, video2.slug), + 'update_fields': '["title"]', + 'update_action': 'fields', + }, + HTTP_X_REQUESTED_WITH='XMLHttpRequest', + ) + + post_request.user = user1 + post_request.LANGUAGE_CODE = "fr" + response = bulk_update(post_request) + self.assertEqual(response.status_code, 200) + self.assertEqual(len(Video.objects.filter(title="Modified Title")), 2) + + print( + "---> test_bulk_update_title of BulkUpdateTestCase: OK" + ) + self.client.logout() + + def tearDown(self): + """Cleanup all created stuffs.""" + del self.client + del self.factory diff --git a/pod/video/tests/test_views.py b/pod/video/tests/test_views.py index f298ce6529..7c3cd00485 100644 --- a/pod/video/tests/test_views.py +++ b/pod/video/tests/test_views.py @@ -1203,7 +1203,7 @@ def test_update_video_owner(self): # Authentication required move TEMPORARY_REDIRECT response = self.client.post( url, - json.dumps({"videos": [1, 2], "owner": [self.simple_user.id]}), + json.dumps({"videos": [6, 7], "owner": [self.simple_user.id]}), content_type="application/json", ) self.assertEqual(response.status_code, HTTPStatus.FOUND) @@ -1232,7 +1232,7 @@ def test_update_video_owner(self): json.dumps( { # video with id 100 doesn't exist - "videos": [1, 2, 100], + "videos": [6, 7, 100], "owner": self.simple_user.id, } ), @@ -1245,7 +1245,7 @@ def test_update_video_owner(self): # Good request response = self.client.post( url, - json.dumps({"videos": [1, 2], "owner": self.simple_user.id}), + json.dumps({"videos": [6, 7], "owner": self.simple_user.id}), content_type="application/json", ) @@ -1254,9 +1254,6 @@ def test_update_video_owner(self): self.assertEqual(json.loads(response.content.decode("utf-8")), expected) self.assertEqual(Video.objects.filter(owner=self.simple_user).count(), 2) - def tearDown(self): - super(VideoTestUpdateOwner, self).tearDown() - class VideoTestFiltersViews(TestCase): fixtures = [ diff --git a/pod/video/views.py b/pod/video/views.py index 1adcfbe046..9cc01d3768 100644 --- a/pod/video/views.py +++ b/pod/video/views.py @@ -1,4 +1,5 @@ """Esup-Pod videos views.""" +from concurrent import futures from django.core.exceptions import PermissionDenied, SuspiciousOperation from django.core.handlers.wsgi import WSGIRequest @@ -29,7 +30,6 @@ # from django.contrib.auth.hashers import check_password from dateutil.parser import parse -import concurrent.futures as futures from pod.main.utils import is_ajax, dismiss_stored_messages, get_max_code_lvl_messages from pod.main.models import AdditionalChannelTab @@ -654,7 +654,7 @@ def bulk_update(request): if request.method == "POST": status = 200 # Get post parameters - update_action = json.loads(request.POST.get("update_action")) + update_action = request.POST.get("update_action") selected_videos = json.loads(request.POST.get("selected_videos")) videos_list = Video.objects.filter(slug__in=selected_videos) @@ -3058,7 +3058,17 @@ def get_response_data(self, chunked_upload, request): @csrf_protect @login_required(redirect_field_name="referrer") @admin_required -def update_video_owner(request, user_id): +def update_video_owner(request, user_id: int)-> JsonResponse: + """ + Update video owner. + + Args: + request (::class::`django.core.handlers.wsgi.WSGIRequest`): The WSGI request. + user_id (int): User identifier. + + Returns: + ::class::`django.http.JsonResponse`: The JSON response. + """ if request.method == "POST": post_data = json.loads(request.body.decode("utf-8"))