-
Notifications
You must be signed in to change notification settings - Fork 586
/
Copy pathtest_admin.py
1982 lines (1729 loc) · 84.4 KB
/
test_admin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import django
import django.core.files
from django.apps import apps
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import helpers
from django.contrib.admin.templatetags.admin_urls import admin_urlname
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.messages import ERROR, get_messages
from django.forms.models import model_to_dict as model_to_dict_django
from django.http import HttpRequest, HttpResponseForbidden
from django.test import RequestFactory, TestCase
from django.urls import reverse
from easy_thumbnails.files import get_thumbnailer
from easy_thumbnails.options import ThumbnailOptions
from filer import settings as filer_settings
from filer.admin import tools
from filer.admin.folderadmin import FolderAdmin
from filer.models import abstract
from filer.models.filemodels import File
from filer.models.foldermodels import Folder, FolderPermission
from filer.models.virtualitems import FolderRoot
from filer.settings import DEFERRED_THUMBNAIL_SIZES, FILER_IMAGE_MODEL
from filer.templatetags.filer_admin_tags import file_icon_url, get_aspect_ratio_and_download_url
from filer.thumbnail_processors import normalize_subject_location
from filer.utils.loader import load_model
from tests.helpers import SettingsOverride, create_folder_structure, create_image, create_superuser
from tests.utils.extended_app.models import ExtImage, Video
Image = load_model(FILER_IMAGE_MODEL)
User = get_user_model()
def model_to_dict(instance, **kwargs):
if kwargs.pop('all'):
kwargs['fields'] = [field.name for field in instance._meta.fields]
return model_to_dict_django(instance, **kwargs)
class FilerFolderAdminUrlsTests(TestCase):
def setUp(self):
self.superuser = create_superuser()
self.client.login(username='admin', password='secret')
def tearDown(self):
self.client.logout()
def test_filer_app_index_get(self):
response = self.client.get(reverse('admin:app_list', args=('filer',)))
self.assertEqual(response.status_code, 200)
def test_filer_make_root_folder_get(self):
response = self.client.get(reverse('admin:filer-directory_listing-make_root_folder') + "?_popup=1")
self.assertEqual(response.status_code, 200)
def test_filer_make_root_folder_get_no_param(self):
response = self.client.get(reverse('admin:filer-directory_listing-make_root_folder'))
self.assertEqual(response.status_code, 200)
def test_filer_make_root_folder_post(self):
FOLDER_NAME = "root folder 1"
self.assertEqual(Folder.objects.count(), 0)
response = self.client.post(
reverse('admin:filer-directory_listing-make_root_folder'), {
"name": FOLDER_NAME,
}
)
self.assertEqual(Folder.objects.count(), 1)
self.assertEqual(Folder.objects.all()[0].name, FOLDER_NAME)
# TODO: not sure why the status code is 200
self.assertEqual(response.status_code, 200)
def test_filer_remember_last_opened_directory(self):
folder = Folder.objects.create(name='remember me please')
get_last_folder = lambda: self.client.get(reverse('admin:filer-directory_listing-last'), follow=True) # noqa
self.client.get(reverse('admin:filer-directory_listing', kwargs={'folder_id': folder.id}))
self.assertEqual(int(self.client.session['filer_last_folder_id']), folder.id)
self.assertEqual(get_last_folder().context['folder'], folder)
# let's test fallback
folder.delete()
self.assertTrue(isinstance(get_last_folder().context['folder'], FolderRoot))
def test_filer_directory_listing_root_empty_get(self):
response = self.client.get(reverse('admin:filer-directory_listing-root'))
self.assertEqual(response.status_code, 200)
def test_filer_directory_listing_root_get(self):
create_folder_structure(depth=3, sibling=2, parent=None)
response = self.client.get(reverse('admin:filer-directory_listing-root'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['folder'].children.count(), 6)
def test_filer_directory_listing_performance(self):
# Any number of images > then the number of allowed queries to ensure that images do not trigger individual
# queries.
images = 10
thumbnail_urls = []
for i in range(images):
filename = f'test_image_{i}.jpg'
os_filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, filename)
create_image().save(os_filename, 'JPEG')
with open(os_filename, 'rb') as f:
file_obj = django.core.files.File(f, name=filename)
image_obj = Image.objects.create(owner=self.superuser, original_filename=filename, file=file_obj, mime_type='image/jpeg')
image_obj.save()
thumbnailer = get_thumbnailer(image_obj)
thumbnail_options = ThumbnailOptions({"size": (40, 40), "crop": True})
thumbnail_urls.append(thumbnailer.get_thumbnail(thumbnail_options).url)
self.assertEqual(Image.objects.count(), images)
with self.assertNumQueries(7):
# Expected queries:
# 1. Authentication check
# 2.-5. Loading the user clipboard
# 6. Loading directory data and thumbnails (1 query)
# 7. Selecting file and owner data
response = self.client.get(reverse('admin:filer-directory_listing-unfiled_images'))
self.assertContains(response, "test_image_0.jpg")
self.assertContains(response, "/media/my-preferred-base-url-for-source-files/")
self.assertContains(response, "/media/my-preferred-base-url-for-thumbnails/")
for thumbnail_url in thumbnail_urls:
self.assertContains(response, thumbnail_url)
def test_validate_no_duplicate_folders(self):
FOLDER_NAME = "root folder 1"
self.assertEqual(Folder.objects.count(), 0)
response = self.client.post(
reverse('admin:filer-directory_listing-make_root_folder'), {
"name": FOLDER_NAME,
"_popup": 1
}
)
self.assertEqual(Folder.objects.count(), 1)
self.assertEqual(Folder.objects.all()[0].name, FOLDER_NAME)
# and create another one
response = self.client.post(
reverse('admin:filer-directory_listing-make_root_folder'),
{"name": FOLDER_NAME, "_popup": 1}
)
# second folder didn't get created
self.assertEqual(Folder.objects.count(), 1)
self.assertContains(response, 'Folder with this name already exists')
def test_validate_no_duplicate_folders_on_rename(self):
self.assertEqual(Folder.objects.count(), 0)
response = self.client.post(
reverse('admin:filer-directory_listing-make_root_folder'), {
"name": "foo",
"_popup": 1
}
)
self.assertEqual(Folder.objects.count(), 1)
self.assertEqual(Folder.objects.all()[0].name, "foo")
# and create another one
response = self.client.post(
reverse('admin:filer-directory_listing-make_root_folder'), {
"name": "bar",
"_popup": 1
}
)
self.assertEqual(Folder.objects.count(), 2)
bar = Folder.objects.get(name="bar")
admin_url = reverse("admin:filer_folder_change", args=(bar.pk, ))
response = self.client.post(admin_url, {"name": "foo", "_popup": 1})
self.assertContains(response, 'Folder with this name already exists')
# refresh from db and validate that it's name didn't change
bar = Folder.objects.get(pk=bar.pk)
self.assertEqual(bar.name, "bar")
def test_change_folder_owner_keep_name(self):
folder = Folder.objects.create(name='foobar')
another_superuser = User.objects.create_superuser(
'gigi', 'admin@ignore.com', 'secret')
admin_url = reverse("admin:filer_folder_change", args=(folder.pk, ))
response = self.client.post(admin_url, {
'owner': another_superuser.pk,
'name': 'foobar',
'_continue': 'Save and continue editing'
})
# successful POST returns a redirect
self.assertEqual(response.status_code, 302)
folder = Folder.objects.get(pk=folder.pk)
self.assertEqual(folder.owner.pk, another_superuser.pk)
def test_folder_admin_uses_admin_context(self):
folder = Folder.objects.create(name='foo')
url = reverse('admin:filer-directory_listing', kwargs={
'folder_id': folder.id})
response = self.client.get(url)
self.assertTrue('site_header' in response.context)
self.assertTrue('site_title' in response.context)
def test_folder_list_actions(self):
Folder.objects.create(name='foo')
actions = [
'Delete selected files and/or folders',
'Move selected files and/or folders',
'Copy selected files and/or folders',
'Resize selected images',
'Rename files',
]
with SettingsOverride(filer_settings, FILER_ENABLE_PERMISSIONS=False):
response = self.client.get(reverse('admin:filer-directory_listing-root'))
for action in actions:
self.assertContains(response, action)
actions_with_permissions = [
'Disable permissions for selected files',
'Enable permissions for selected files',
]
with SettingsOverride(filer_settings, FILER_ENABLE_PERMISSIONS=True):
response = self.client.get(reverse('admin:filer-directory_listing-root'))
for action in (actions_with_permissions + actions):
self.assertContains(response, action)
def test_filer_list_type_query_string(self):
response = self.client.get(reverse('admin:filer-directory_listing-root') + "?_list_type=th")
self.assertContains(response, 'navigator-thumbnail-list')
response = self.client.get(reverse('admin:filer-directory_listing-root') + "?_list_type=tb")
self.assertContains(response, 'navigator-table')
def test_filer_list_type_setting(self):
with SettingsOverride(filer_settings, FILER_FOLDER_ADMIN_DEFAULT_LIST_TYPE='th'):
response = self.client.get(reverse('admin:filer-directory_listing-root'))
self.assertContains(response, 'navigator-thumbnail-list')
def test_filer_list_type_setting_when_user_set_wrong_choice(self):
# If choice not exists then it should set table view as default
with SettingsOverride(settings, FILER_FOLDER_ADMIN_DEFAULT_LIST_TYPE='qwerty'):
# `settings` instead of `filer_settings` to give chance filer_settings
# conditional to fire up
response = self.client.get(reverse('admin:filer-directory_listing-root'))
self.assertContains(response, 'navigator-table')
def test_filer_list_type_setting_when_use_wrong_query_string_choice(self):
# If list type in query string not exists show default list type
with SettingsOverride(filer_settings, FILER_FOLDER_ADMIN_DEFAULT_LIST_TYPE='th'):
response = self.client.get(reverse('admin:filer-directory_listing-root') + "?_list_type=qwerty")
self.assertContains(response, 'navigator-thumbnail-list')
class FilerImageAdminUrlsTests(TestCase):
def setUp(self):
self.superuser = create_superuser()
self.client.login(username='admin', password='secret')
self.img = create_image()
self.image_name = 'test_file.jpg'
self.filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, self.image_name)
self.img.save(self.filename, 'JPEG')
with open(self.filename, 'rb') as upload:
self.file_object = Image.objects.create(file=django.core.files.File(upload, name=self.image_name))
def tearDown(self):
self.client.logout()
os.remove(self.filename)
def test_icon_view_sizes(self):
"""Redirects are issued for accepted thumbnail sizes and 404 otherwise"""
test_set = tuple((size, 302) for size in DEFERRED_THUMBNAIL_SIZES)
test_set += (50, 404), (90, 404), (640, 404)
for size, expected_status in test_set:
url = reverse('admin:filer_file_fileicon', kwargs={
'file_id': self.file_object.pk,
'size': size,
})
response = self.client.get(url)
self.assertEqual(response.status_code, expected_status)
if response.status_code == 302: # redirect
# Redirects to a media file
self.assertIn("/media/", response["Location"])
# Does not redirect to a static file
self.assertNotIn("/static/", response["Location"])
def test_missing_file(self):
"""Directory shows static icon for missing files"""
image = Image.objects.create(
owner=self.superuser,
original_filename="some-image.jpg",
)
url = reverse('admin:filer_file_fileicon', kwargs={
'file_id': image.pk,
'size': 80,
})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
self.assertIn("icons/file-missing.svg", response["Location"])
def test_icon_view_non_image(self):
"""Getting an icon for a non-image results in a 404"""
file = File.objects.create(
owner=self.superuser,
original_filename="some-file.xyz",
)
url = reverse('admin:filer_file_fileicon', kwargs={
'file_id': file.pk,
'size': 80,
})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_detail_view_missing_file(self):
"""Detail view shows static icon for missing file"""
image = Image.objects.create(
owner=self.superuser,
original_filename="some-image.jpg",
)
image._width = 50
image._height = 200
image.save()
url = reverse(admin_urlname(Image._meta, 'change'), kwargs={
'object_id': image.pk,
})
response = self.client.get(url)
self.assertContains(response, "icons/file-missing.svg")
self.assertContains(response, 'width="210"')
self.assertContains(response, 'height="210"')
self.assertContains(response, 'alt="File is missing"')
def test_image_expand_link_in_change_view(self):
files = [
# Files can use the same contents for this test - it's the mime type that counts
File.objects.create(owner=self.superuser, original_filename='some-file.txt', file=self.file_object.file),
Image.objects.create(owner=self.superuser, original_filename='some-image.jpg'), # missing file
Image.objects.create(owner=self.superuser, original_filename='some-image.jpg', file=self.file_object.file),
Image.objects.create(owner=self.superuser, original_filename='some-image.svg', file=self.file_object.file),
]
test_set = [
(files[0], 'text/plain', None),
(files[1], 'image/jpeg', None),
(files[2], 'image/jpeg', files[2].file.url),
(files[3], 'image/svg+xml', reverse(admin_urlname(Image._meta, 'expand'), args=(files[3].pk,))),
]
for file, mime_type, expected_url in test_set:
file.mime_type = mime_type
file.save()
models = [File]
if isinstance(file, Image):
models.append(Image)
for model in models:
response = self.client.get(reverse(admin_urlname(model._meta, 'change'),
kwargs={'object_id': file.pk}))
if expected_url:
self.assertContains(response, f'href="{expected_url}"')
else:
self.assertNotContains(response, 'filer-icon-expand')
def test_image_expand_view(self):
url = reverse(admin_urlname(Image._meta, 'expand'), kwargs={
'file_id': self.file_object.pk
})
original_url = self.file_object.url
response = self.client.get(url)
self.assertEqual(url, self.file_object.get_admin_expand_view_url())
self.assertContains(
response,
f"""<img id="img" src="{original_url}" onclick="this.classList.toggle('zoom')"/>"""
)
class FilerClipboardAdminUrlsTests(TestCase):
def setUp(self):
self.superuser = create_superuser()
self.client.login(username='admin', password='secret')
self.img = create_image()
self.image_name = 'test_file.jpg'
self.filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, self.image_name)
self.img.save(self.filename, 'JPEG')
self.video = create_image()
self.video_name = 'test_file.mov'
self.video_filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, self.video_name)
self.video.save(self.video_filename, 'JPEG')
self.binary_name = 'aaa.bin'
self.binary_filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, self.binary_name)
with open(self.binary_filename, 'wb') as fh:
fh.write(bytearray(100 * b'a'))
super().setUp()
def tearDown(self):
self.client.logout()
os.remove(self.filename)
os.remove(self.video_filename)
super().tearDown()
def test_filer_upload_file(self, extra_headers={}):
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload', kwargs={'folder_id': folder.pk})
post_data = {
'Filename': self.image_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
self.client.post(url, post_data, **extra_headers)
self.assertEqual(Image.objects.count(), 1)
self.assertEqual(Image.objects.all()[0].original_filename,
self.image_name)
def test_filer_upload_video(self, extra_headers={}):
with SettingsOverride(filer_settings, FILER_FILE_MODELS=(
'extended_app.ExtImage',
'extended_app.Video',
'filer.Image',
'filer.File'
)):
self.assertEqual(Video.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.video_filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload', kwargs={'folder_id': folder.pk})
post_data = {
'Filename': self.video_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
self.client.post(url, post_data, **extra_headers)
self.assertEqual(Video.objects.count(), 1)
self.assertEqual(Video.objects.all()[0].original_filename, self.video_name)
def test_filer_upload_extimage(self, extra_headers={}):
with SettingsOverride(filer_settings, FILER_FILE_MODELS=(
'extended_app.ExtImage',
'extended_app.Video',
'filer.Image',
'filer.File'
)):
self.assertEqual(ExtImage.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload', kwargs={'folder_id': folder.pk})
post_data = {
'Filename': self.image_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
self.client.post(url, post_data, **extra_headers)
self.assertEqual(ExtImage.objects.count(), 1)
self.assertEqual(ExtImage.objects.all()[0].original_filename, self.image_name)
def test_filer_upload_file_no_folder(self, extra_headers={}):
self.assertEqual(Image.objects.count(), 0)
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload')
post_data = {
'Filename': self.image_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
response = self.client.post(url, post_data, **extra_headers) # noqa
self.assertEqual(Image.objects.count(), 1)
stored_image = Image.objects.first()
self.assertEqual(stored_image.original_filename, self.image_name)
self.assertEqual(stored_image.mime_type, 'image/jpeg')
def test_filer_upload_binary_data(self, extra_headers={}):
config = apps.get_app_config("filer")
validators = config.FILE_VALIDATORS # Remember the validators
config.FILE_VALIDATORS = {} # Remove deny for application/octet-stream
self.assertEqual(File.objects.count(), 0)
with open(self.binary_filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload')
post_data = {
'Filename': self.binary_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
self.client.post(url, post_data, **extra_headers)
config.FILE_VALIDATORS = validators # Reset validators
self.assertEqual(Image.objects.count(), 0)
self.assertEqual(File.objects.count(), 1)
stored_file = File.objects.first()
self.assertEqual(stored_file.original_filename, self.binary_name)
self.assertEqual(stored_file.mime_type, 'application/octet-stream')
def test_filer_upload_binary_data_fails_by_default(self, extra_headers={}):
self.assertEqual(File.objects.count(), 0)
with open(self.binary_filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload')
post_data = {
'Filename': self.binary_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
self.client.post(url, post_data, **extra_headers)
self.assertEqual(Image.objects.count(), 0)
self.assertEqual(File.objects.count(), 0)
def test_filer_ajax_upload_file(self):
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk}
) + '?filename=%s' % self.image_name
response = self.client.post( # noqa
url,
data=file_obj.read(),
content_type='image/jpeg',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
self.assertEqual(Image.objects.count(), 1)
stored_image = Image.objects.first()
self.assertEqual(stored_image.original_filename, self.image_name)
self.assertEqual(stored_image.mime_type, 'image/jpeg')
def test_filer_ajax_decompression_bomb(self):
DEFAULT_MAX_IMAGE_PIXELS = abstract.FILER_MAX_IMAGE_PIXELS
abstract.FILER_MAX_IMAGE_PIXELS = 800 * 200 # Triggers error
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk}
) + '?filename=%s' % self.image_name
response = self.client.post(
url,
data=file_obj.read(),
content_type='image/jpeg',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
self.assertEqual(Image.objects.count(), 0)
self.assertIn("error", json.loads(response.content.decode("utf-8")))
messages = list(get_messages(response.wsgi_request))
self.assertEqual(len(messages), 1)
self.assertEqual(messages[0].level, ERROR)
abstract.FILER_MAX_IMAGE_PIXELS = 800 * 300 # Triggers warning
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk}
) + '?filename=%s' % self.image_name
response = self.client.post(
url,
data=file_obj.read(),
content_type='image/jpeg',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
self.assertEqual(response.status_code, 200)
messages = list(get_messages(response.wsgi_request))
self.assertEqual(len(messages), 2) # One more message
self.assertEqual(messages[1].level, ERROR)
self.assertEqual(Image.objects.count(), 0)
abstract.FILER_MAX_IMAGE_PIXELS = DEFAULT_MAX_IMAGE_PIXELS
def test_filer_max_pixel_deactivation(self):
from django.core.checks import Warning
DEFAULT_MAX_IMAGE_PIXELS = abstract.FILER_MAX_IMAGE_PIXELS
abstract.FILER_MAX_IMAGE_PIXELS = None # Deactivate
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk}
) + '?filename=%s' % self.image_name
self.client.post(
url,
data=file_obj.read(),
content_type='image/jpeg',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
self.assertEqual(Image.objects.count(), 1) # Success
check_result = abstract.max_pixel_setting_check(None)
self.assertEqual(len(check_result), 1)
self.assertIsInstance(check_result[0], Warning)
abstract.FILER_MAX_IMAGE_PIXELS = DEFAULT_MAX_IMAGE_PIXELS
def test_filer_ajax_upload_file_using_content_type(self):
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.binary_filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk}
) + '?filename=renamed.pdf'
self.client.post(
url,
data=file_obj.read(),
content_type='application/pdf',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
self.assertEqual(Image.objects.count(), 0)
self.assertEqual(File.objects.count(), 1)
stored_file = File.objects.first()
self.assertEqual(stored_file.original_filename, 'renamed.pdf')
self.assertEqual(stored_file.mime_type, 'application/pdf')
def test_filer_ajax_upload_file_no_folder(self):
self.assertEqual(Image.objects.count(), 0)
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload'
) + '?filename=%s' % self.image_name
self.client.post(
url,
data=file_obj.read(),
content_type='image/jpeg',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
self.assertEqual(Image.objects.count(), 1)
stored_image = Image.objects.first()
self.assertEqual(stored_image.original_filename, self.image_name)
self.assertEqual(stored_image.mime_type, 'image/jpeg')
def test_filer_upload_file_error(self, extra_headers={}):
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse('admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk + 1})
post_data = {
'Filename': self.image_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
response = self.client.post(url, post_data, **extra_headers)
from filer.admin.clipboardadmin import NO_FOLDER_ERROR
self.assertContains(response, NO_FOLDER_ERROR)
self.assertEqual(Image.objects.count(), 0)
def test_filer_ajax_upload_file_error(self):
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={
'folder_id': folder.pk + 1}
) + f'?filename={self.image_name}'
response = self.client.post(
url,
data=file_obj.read(),
content_type='application/octet-stream',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
from filer.admin.clipboardadmin import NO_FOLDER_ERROR
self.assertContains(response, NO_FOLDER_ERROR)
self.assertEqual(Image.objects.count(), 0)
def test_filer_upload_permissions_error(self, extra_headers={}):
self.client.logout()
staff_user = User.objects.create_user(
username='joe_new', password='x', email='joe@mata.com')
staff_user.is_staff = True
staff_user.save()
staff_user.user_permissions.add(*Permission.objects.filter(codename="add_file"))
self.client.login(username='joe_new', password='x')
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
with SettingsOverride(filer_settings, FILER_ENABLE_PERMISSIONS=True):
# give permissions over BAR
FolderPermission.objects.create(
folder=folder,
user=staff_user,
type=FolderPermission.THIS,
can_edit=FolderPermission.DENY,
can_read=FolderPermission.ALLOW,
can_add_children=FolderPermission.DENY)
url = reverse('admin:filer-ajax_upload',
kwargs={'folder_id': folder.pk})
post_data = {
'Filename': self.image_name,
'Filedata': file_obj,
'jsessionid': self.client.session.session_key
}
response = self.client.post(url, post_data, **extra_headers)
from filer.admin.clipboardadmin import NO_PERMISSIONS_FOR_FOLDER
self.assertContains(response, NO_PERMISSIONS_FOR_FOLDER)
self.assertEqual(Image.objects.count(), 0)
def test_filer_ajax_upload_without_permissions_error(self, extra_headers={}):
"""User without add_file permission cannot upload"""
self.client.logout()
staff_user = User.objects.create_user(
username='joe_new', password='x', email='joe@mata.com')
staff_user.is_staff = True
staff_user.save()
self.client.login(username='joe_new', password='x')
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
url = reverse(
'admin:filer-ajax_upload',
kwargs={
'folder_id': folder.pk}
) + f'?filename={self.image_name}'
response = self.client.post(
url,
data=file_obj.read(),
content_type='application/octet-stream',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
from filer.admin.clipboardadmin import NO_PERMISSIONS
self.assertContains(response, NO_PERMISSIONS)
self.assertEqual(Image.objects.count(), 0)
def test_filer_add_file_permissions(self, extra_headers={}):
"""Add_file permissions reflect in has_... methods of File and Folder classes"""
self.client.logout()
staff_user = User.objects.create_user(
username='joe_new', password='x', email='joe@mata.com')
staff_user.is_staff = True
staff_user.save()
self.client.login(username='joe_new', password='x')
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
file_data = django.core.files.base.ContentFile('some data')
file_data.name = self.filename
file = File.objects.create(
owner=self.superuser,
original_filename=self.filename,
file=file_data,
folder=folder
)
file.save()
request = HttpRequest()
setattr(request, "user", staff_user)
self.assertEqual(folder.has_add_children_permission(request), False)
self.assertEqual(file.has_add_children_permission(request), False)
def test_filer_ajax_upload_permissions_error(self, extra_headers={}):
self.client.logout()
staff_user = User.objects.create_user(
username='joe_new', password='x', email='joe@mata.com')
staff_user.is_staff = True
staff_user.save()
staff_user.user_permissions.add(*Permission.objects.filter(codename="add_file"))
self.client.login(username='joe_new', password='x')
self.assertEqual(Image.objects.count(), 0)
folder = Folder.objects.create(name='foo')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh)
with SettingsOverride(filer_settings, FILER_ENABLE_PERMISSIONS=True):
# give permissions over BAR
FolderPermission.objects.create(
folder=folder,
user=staff_user,
type=FolderPermission.THIS,
can_edit=FolderPermission.DENY,
can_read=FolderPermission.ALLOW,
can_add_children=FolderPermission.DENY)
url = reverse(
'admin:filer-ajax_upload',
kwargs={
'folder_id': folder.pk}
) + f'?filename={self.image_name}'
response = self.client.post(
url,
data=file_obj.read(),
content_type='application/octet-stream',
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
)
from filer.admin.clipboardadmin import NO_PERMISSIONS_FOR_FOLDER
self.assertContains(response, NO_PERMISSIONS_FOR_FOLDER)
self.assertEqual(Image.objects.count(), 0)
def test_templatetag_file_icon_url(self):
filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, 'invalid.svg')
with open(filename, 'wb') as fh:
fh.write(b'<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" height="0" width="0"><circle cx="0" cy="0" r="0" stroke="black" stroke-width="3" fill="red" /></svg>')
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh, name=filename)
image_obj = Image.objects.create(owner=self.superuser, original_filename=self.image_name, file=file_obj, mime_type='image/svg+xml')
image_obj.save()
url = file_icon_url(image_obj)
self.assertEqual(url, '/static/filer/icons/file\\u002Dunknown.svg')
class BulkOperationsMixin:
def setUp(self):
self.superuser = create_superuser()
self.client.login(username='admin', password='secret')
self.img = create_image()
self.image_name = 'test_file.jpg'
self.filename = os.path.join(settings.FILE_UPLOAD_TEMP_DIR,
self.image_name)
self.img.save(self.filename, 'JPEG')
self.create_src_and_dst_folders()
self.folder = Folder.objects.create(name="root folder", parent=None)
self.sub_folder1 = Folder.objects.create(name="sub folder 1", parent=self.folder)
self.sub_folder2 = Folder.objects.create(name="sub folder 2", parent=self.folder)
self.image_obj = self.create_image(self.src_folder)
self.create_file(self.folder)
self.create_file(self.folder)
self.create_image(self.folder)
self.create_image(self.sub_folder1)
self.create_file(self.sub_folder1)
self.create_file(self.sub_folder1)
self.create_image(self.sub_folder2)
self.create_image(self.sub_folder2)
def tearDown(self):
self.client.logout()
os.remove(self.filename)
for f in File.objects.all():
f.delete()
for folder in Folder.objects.all():
folder.delete()
def create_src_and_dst_folders(self):
self.src_folder = Folder(name="Src", parent=None)
self.src_folder.save()
self.dst_folder = Folder(name="Dst", parent=None)
self.dst_folder.save()
def create_image(self, folder, filename=None):
filename = filename or 'test_image.jpg'
with open(self.filename, 'rb') as fh:
file_obj = django.core.files.File(fh, name=filename)
image_obj = Image.objects.create(owner=self.superuser, original_filename=self.image_name, file=file_obj, folder=folder, mime_type='image/jpeg')
image_obj.save()
return image_obj
def create_file(self, folder, filename=None):
filename = filename or 'test_file.dat'
file_data = django.core.files.base.ContentFile('some data')
file_data.name = filename
file_obj = File.objects.create(owner=self.superuser, original_filename=filename, file=file_data, folder=folder)
file_obj.save()
return file_obj
class FolderAndFileSortingMixin(BulkOperationsMixin):
def setUp(self):
self.superuser = create_superuser()
self.client.login(username='admin', password='secret')
self.img = create_image()
self.folder_1 = Folder(name='Pictures', parent=None)
self.folder_1.save()
self.nested_folder_2 = Folder(name='Nested 2', parent=self.folder_1)
self.nested_folder_1 = Folder(name='Nested 1', parent=self.folder_1)
self.nested_folder_1.save()
self.nested_folder_2.save()
self.create_file(folder=self.folder_1, filename='background.jpg')
self.create_file(folder=self.folder_1, filename='A_Testfile.jpg')
self.create_file(folder=self.folder_1, filename='Another_Test.jpg')
newspaper_file = self.create_file(folder=self.folder_1, filename='Newspaper.pdf')
newspaper_file.name = 'Zeitung'
newspaper_file.save()
renamed_file = self.create_file(folder=self.folder_1, filename='last_when_sorting_by_filename.jpg')
renamed_file.name = 'A cute dog'
renamed_file.save()
def tearDown(self):
self.client.logout()
for f in File.objects.all():
f.delete()
for folder in Folder.objects.all():
folder.delete()
class FilerFolderAndFileSortingTests(FolderAndFileSortingMixin, TestCase):
# Assert that the folders are correctly sorted
def test_filer_folder_sorting(self):
response = self.client.get(reverse('admin:filer-directory_listing', kwargs={
'folder_id': self.folder_1.pk
}))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['folder_children'].count(), 2)
self.assertEqual(response.context['folder_children'][0].name, 'Nested 1')
self.assertEqual(response.context['folder_children'][1].name, 'Nested 2')
# Default sorting should be alphabetically
def test_filer_directory_listing_default_sorting(self):
response = self.client.get(reverse('admin:filer-directory_listing', kwargs={
'folder_id': self.folder_1.pk
}))
self.assertEqual(response.status_code, 200)
# when using the default sort, the folder_files are of type `list`,
# so we assert the length.
self.assertEqual(len(response.context['folder_files']), 5)
expected_filenames = ['A cute dog', 'A_Testfile.jpg', 'Another_Test.jpg', 'background.jpg', 'Zeitung']
for index, expected_filename in enumerate(expected_filenames):
self.assertEqual(str(response.context['folder_files'][index]), expected_filename)
# Now, all columns with empty name should be alphabetically sorted by their filename,
# after that, at the end of the list, all files with and explicit name should appear;
# however, since we ONLY sort by name, the order of items without name is not defined
# by their filename but rather by their creation date.
# So, the order is expected to be ordered as they are created in the setUp method.
def test_filer_directory_listing_sorting_with_order_by_param(self):
response = self.client.get(reverse('admin:filer-directory_listing', kwargs={
'folder_id': self.folder_1.pk
}), {'order_by': 'name'})
self.assertEqual(response.status_code, 200)
# when using the default sort, the folder_files are of type `list`,
# so we assert the length.
self.assertEqual(len(response.context['folder_files']), 5)
expected_filenames = ['background.jpg', 'A_Testfile.jpg', 'Another_Test.jpg', 'A cute dog', 'Zeitung']
for index, expected_filename in enumerate(expected_filenames):
self.assertEqual(str(response.context['folder_files'][index]), expected_filename)
# Finally, we can define a fallback column to pass into `order_by` so that files without
# any name are still sorted by something (in this case, their original_filename).
# This should yield the expected order as well, but NOT the exact same order as the default sorting,
# since we sort by name FIRST and all items with the same value again by original_filename.
def test_filer_directory_listing_sorting_with_multiple_order_by_params(self):
response = self.client.get(reverse('admin:filer-directory_listing', kwargs={
'folder_id': self.folder_1.pk
}), {'order_by': 'name,original_filename'})
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['folder_files']), 5)
expected_filenames = ['A_Testfile.jpg', 'Another_Test.jpg', 'background.jpg', 'A cute dog', 'Zeitung']
for index, expected_filename in enumerate(expected_filenames):
self.assertEqual(str(response.context['folder_files'][index]), expected_filename)
class FilerBulkOperationsTests(BulkOperationsMixin, TestCase):
def test_move_files_and_folders_action(self):
# TODO: Test recursive (files and folders tree) move
self.assertEqual(self.src_folder.files.count(), 1)
self.assertEqual(self.dst_folder.files.count(), 0)
url = reverse('admin:filer-directory_listing', kwargs={
'folder_id': self.src_folder.id,
})
response = self.client.post(url, {
'action': 'move_files_and_folders',
'post': 'yes',
'destination': self.dst_folder.id,
helpers.ACTION_CHECKBOX_NAME: 'file-%d' % (self.image_obj.id,),
})
self.assertEqual(self.src_folder.files.count(), 0)
self.assertEqual(self.dst_folder.files.count(), 1)
url = reverse('admin:filer-directory_listing', kwargs={
'folder_id': self.dst_folder.id,
})
response = self.client.post(url, { # noqa
'action': 'move_files_and_folders',
'post': 'yes',