-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtests.py
4069 lines (3253 loc) · 197 KB
/
tests.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
from django.db.models import CharField, TextField
from signbank.dictionary.adminviews import *
from signbank.dictionary.forms import GlossCreateForm, FieldChoiceForm
from signbank.dictionary.models import *
from signbank.tools import get_selected_datasets_for_user
from signbank.settings.base import *
from django.utils.translation import override, gettext_lazy as _, activate
from django.contrib.auth.models import User, Permission, Group
from django.test import TestCase, RequestFactory
from django.contrib.admin.sites import AdminSite
from django.test.client import RequestFactory, encode_multipart
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.test import Client
from pathlib import Path
from os import path
from guardian.shortcuts import assign_perm, get_user_perms
from signbank.video.models import GlossVideo
from signbank.dictionary.views import gloss_api_get_sign_name_and_media_info
class BasicCRUDTests(TestCase):
def setUp(self):
# a new test user is created for use during the tests
self.user = User.objects.create_user('test-user', '[email protected]', 'test-user')
self.user.user_permissions.add(Permission.objects.get(name='Can change gloss'))
self.user.user_permissions.add(Permission.objects.get(name='Can change morpheme'))
self.user.save()
self.userprofile = UserProfile(user=self.user)
self.userprofile.save()
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
self.userprofile.selected_datasets.add(test_dataset)
self.userprofile.save()
self.handedness_fieldchoice_1 = FieldChoice.objects.filter(field='Handedness', machine_value__gt=1).first()
self.handedness_fieldchoice_2 = FieldChoice.objects.filter(field='Handedness', machine_value__gt=1).last()
print(self.handedness_fieldchoice_1, self.handedness_fieldchoice_2)
self.locprim_fieldchoice_1 = FieldChoice.objects.filter(field='Location', machine_value__gt=1).first()
self.locprim_fieldchoice_2 = FieldChoice.objects.filter(field='Location', machine_value__gt=1).last()
def test_CRUD(self):
# Is the morpheme there before?
found = 0
total_nr_of_morphemes = 0
for morpheme in Morpheme.objects.filter(handedness=self.handedness_fieldchoice_1):
if morpheme.idgloss == 'thisisatemporarytestlemmaidglosstranslation':
found += 1
total_nr_of_morphemes += 1
self.assertEqual(found, 0)
# Create the morphemes
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
# Create a lemma
new_lemma = LemmaIdgloss(dataset=test_dataset)
new_lemma.save()
# Create lemma idgloss translations for all languages
for language in test_dataset.translation_languages.all():
new_lemmaidglosstranslation = LemmaIdglossTranslation(text="thisisatemporarytestlemmaidglosstranslation",
lemma=new_lemma, language=language)
new_lemmaidglosstranslation.save()
# Create the morpheme
new_morpheme = Morpheme()
new_morpheme.handedness = self.handedness_fieldchoice_1
new_morpheme.lemma = new_lemma
new_morpheme.save()
# Is the morpheme there now?
found = 0
for morpheme in Morpheme.objects.filter(handedness=self.handedness_fieldchoice_1):
if morpheme.idgloss == 'thisisatemporarytestlemmaidglosstranslation':
found += 1
self.assertEqual(found, 1)
# The handedness before was 4
self.assertEqual(new_morpheme.handedness, self.handedness_fieldchoice_1)
# If you run an update post request, you can change the morpheme
new_value_handedness = '_'+str(self.handedness_fieldchoice_2.machine_value)
print(new_value_handedness)
client = Client()
client.login(username='test-user', password='test-user')
client.post('/dictionary/update/morpheme/'+str(new_morpheme.pk),
{'id': 'handedness', 'value': new_value_handedness})
changed_morpheme = Morpheme.objects.get(pk = new_morpheme.pk)
print(changed_morpheme)
self.assertEqual(changed_morpheme.handedness, self.handedness_fieldchoice_2)
# set up keyword search parameter for default language
default_language = Language.objects.get(id=get_default_language_id())
keyword_search_field_prefix = "keyword_"
keyword_field_name = keyword_search_field_prefix + default_language.language_code_2char
# We can even add and remove stuff to the keyword table
# to start with, both tables are empty in the test database
self.assertEqual(Keyword.objects.all().count(), 0)
self.assertEqual(Translation.objects.all().count(), 0)
# add five keywords to the translations of this gloss
client.post('/dictionary/update/morpheme/'+str(new_morpheme.pk),
{'id': keyword_field_name, 'value': 'a, b, c, d, e'})
all_keywords = Keyword.objects.all()
for k in all_keywords:
print('test_CRUD update1 keyword: ', k)
all_translations = Translation.objects.all()
for t in all_translations:
print('test_CRUD update1 morpheme translation: ', t)
self.assertEqual(Keyword.objects.all().count(), 5)
self.assertEqual(Translation.objects.all().count(), 5)
# update the morpheme to only have three of the translations
# the keyword table still has the same data, but only three translations are associated with the morpheme
client.post('/dictionary/update/morpheme/'+str(new_morpheme.pk),
{'id': keyword_field_name, 'value': 'a, b, c'})
all_keywords = Keyword.objects.all()
for k in all_keywords:
print('test_CRUD update2 keyword: ', k)
all_translations = Translation.objects.all()
for t in all_translations:
print('test_CRUD update2 morpheme translation: ', t)
self.assertEqual(Keyword.objects.all().count(), 5)
self.assertEqual(Translation.objects.all().count(), 3)
# Throwing stuff away with the update functionality
client.post(settings.PREFIX_URL + '/dictionary/update/morpheme/'+str(new_morpheme.pk),
{'id': 'deletegloss', 'value': 'confirmed'})
found = 0
for morpheme in Morpheme.objects.filter(handedness=self.handedness_fieldchoice_1):
if morpheme.idgloss == 'thisisatemporarytestgloss':
found += 1
self.assertEqual(found, 0)
def test_createGloss(self):
# Create Client and log in
client = Client()
logged_in = client.login(username='test-user', password='test-user')
assign_perm('dictionary.add_gloss', self.user)
self.user.save()
# Check whether the user is logged in
self.assertTrue(logged_in)
# Get the test dataset
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
# Construct the Create Gloss form data
create_gloss_form_data = {'dataset': test_dataset.id, 'select_or_new_lemma': "new"}
for language in test_dataset.translation_languages.all():
create_gloss_form_data[GlossCreateForm.gloss_create_field_prefix + language.language_code_2char] = \
"annotationidglosstranslation_test_" + language.language_code_2char
create_gloss_form_data[LemmaCreateForm.lemma_create_field_prefix + language.language_code_2char] = \
"lemmaidglosstranslation_test_" + language.language_code_2char
# User does not have permission to change dataset. Creating a gloss should fail.
response = client.post('/dictionary/update/gloss/', create_gloss_form_data)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "You are not authorized to change the selected dataset.")
# Give the test user permission to change a dataset
assign_perm('change_dataset', self.user, test_dataset)
response = client.post('/dictionary/update/gloss/', create_gloss_form_data)
glosses = Gloss.objects.filter(lemma__dataset=test_dataset)
for language in test_dataset.translation_languages.all():
glosses = glosses.filter(annotationidglosstranslation__language=language,
annotationidglosstranslation__text__exact="annotationidglosstranslation_test_"
+ language.language_code_2char)
glosses = glosses.filter(lemma__lemmaidglosstranslation__language=language,
lemma__lemmaidglosstranslation__text__exact="lemmaidglosstranslation_test_"
+ language.language_code_2char)
self.assertEqual(len(glosses), 1)
self.assertRedirects(response, reverse('dictionary:admin_gloss_view', kwargs={'pk': glosses[0].id})+'?edit')
def testSearchForGlosses(self):
# Create a client and log in
client = Client()
client.login(username='test-user', password='test-user')
# Give the test user permission to search glosses
assign_perm('dictionary.search_gloss', self.user)
# Create the glosses
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
default_language = test_dataset.default_language
# Create a lemma
new_lemma = LemmaIdgloss(dataset=test_dataset)
new_lemma.save()
# Create lemma idgloss translations
for language in test_dataset.translation_languages.all():
new_lemmaidglosstranslation = LemmaIdglossTranslation(text="thisisatemporarytestlemmaidglosstranslation_"+language.language_code_2char,
lemma=new_lemma, language=language)
new_lemmaidglosstranslation.save()
new_gloss = Gloss()
new_gloss.handedness = self.handedness_fieldchoice_1
new_gloss.inWeb = False
new_gloss.lemma = new_lemma
new_gloss.save()
# make some annotations for the new gloss
test_annotation_translation_index = '1'
for language in test_dataset.translation_languages.all():
annotationIdgloss = AnnotationIdglossTranslation()
annotationIdgloss.gloss = new_gloss
annotationIdgloss.language = language
annotationIdgloss.text = 'thisisatemporarytestgloss' + test_annotation_translation_index
annotationIdgloss.save()
new_gloss = Gloss()
new_gloss.handedness = self.handedness_fieldchoice_1
new_gloss.inWeb = False
new_gloss.lemma = new_lemma
new_gloss.save()
# make some annotations for the new gloss
test_annotation_translation_index = '2'
for language in test_dataset.translation_languages.all():
annotationIdgloss = AnnotationIdglossTranslation()
annotationIdgloss.gloss = new_gloss
annotationIdgloss.language = language
annotationIdgloss.text = 'thisisatemporarytestgloss' + test_annotation_translation_index
annotationIdgloss.save()
new_gloss = Gloss()
new_gloss.handedness = self.handedness_fieldchoice_2
new_gloss.inWeb = False
new_gloss.lemma = new_lemma
new_gloss.save()
# make some annotations for the new gloss
test_annotation_translation_index = '3'
for language in test_dataset.translation_languages.all():
annotationIdgloss = AnnotationIdglossTranslation()
annotationIdgloss.gloss = new_gloss
annotationIdgloss.language = language
annotationIdgloss.text = 'thisisatemporarytestgloss' + test_annotation_translation_index
annotationIdgloss.save()
all_glosses = Gloss.objects.all()
for ag in all_glosses:
try:
print('testSearchForGlosses created gloss: ',
ag.annotationidglosstranslation_set.get(language=default_language).text)
except ObjectDoesNotExist:
print('testSearchForGlosses created gloss has empty annotation translation')
# Search
search_value_handedness = str(self.handedness_fieldchoice_1.machine_value)
assign_perm('view_dataset', self.user, test_dataset)
response = client.get('/signs/search/',{'handedness[]': search_value_handedness})
self.assertEqual(len(response.context['object_list']), 2)
other_search_value_handedness = str(self.handedness_fieldchoice_2.machine_value)
response = client.get('/signs/search/',{'handedness[]': other_search_value_handedness})
self.assertEqual(len(response.context['object_list']), 1)
def test_package_function(self):
# Create a client and log in
client = Client()
client.login(username='test-user', password='test-user')
#Get a dataset
dataset_name = settings.DEFAULT_DATASET
# Give the test user permission to change a dataset
test_dataset = Dataset.objects.get(name=dataset_name)
assign_perm('view_dataset', self.user, test_dataset)
assign_perm('change_dataset', self.user, test_dataset)
assign_perm('dictionary.search_gloss', self.user)
assign_perm('dictionary.add_gloss', self.user)
assign_perm('dictionary.change_gloss', self.user)
self.user.save()
# Create a lemma in order to store the dataset with the new gloss
new_lemma = LemmaIdgloss(dataset=test_dataset)
new_lemma.save()
# Create a lemma idgloss translation
default_language = Language.objects.get(id=get_default_language_id())
new_lemmaidglosstranslation = LemmaIdglossTranslation(text="thisisatemporarytestlemmaidglosstranslation",
lemma=new_lemma, language=default_language)
new_lemmaidglosstranslation.save()
# #Create the gloss
new_gloss = Morpheme()
# to test the package functionality of phonology fields, add some to settings.API_FIELDS
# for this test, the local settings file has added these two fields
# they are visible in the result if they appear in API_FIELDS
new_gloss.handedness = self.handedness_fieldchoice_1
new_gloss.locprim = self.locprim_fieldchoice_1
new_gloss.lemma = new_lemma
new_gloss.save()
for language in test_dataset.translation_languages.all():
annotationIdgloss = AnnotationIdglossTranslation()
annotationIdgloss.gloss = new_gloss
annotationIdgloss.language = language
annotationIdgloss.text = 'thisisatemporarytestgloss'
annotationIdgloss.save()
# set up keyword search parameter for default language
keyword_search_field_prefix = "keyword_"
keyword_field_name = keyword_search_field_prefix + default_language.language_code_2char
# keywords: this is merely part of the setup for the test
# add five keywords to the translations of this gloss
client.post('/dictionary/update/morpheme/'+str(new_gloss.pk),{'id': keyword_field_name,'value':'a, b, c, d, e'})
changed_gloss = Morpheme.objects.get(pk = new_gloss.pk)
# this calculates the data retrieved by get_gloss_data for packages
# it shows the format/display of the returned gloss fields
# note that the value of the phonology fields are numerical rather than human readable
result = changed_gloss.get_fields_dict(settings.API_FIELDS)
print('test_package_function: settings.API_FIELDS: ', settings.API_FIELDS)
print('test_package_function: get_fields_dict: ', result)
#Deprecated?
class BasicQueryTests(TestCase):
# Search with a search string
def setUp(self):
# a new test user is created for use during the tests
self.user = User.objects.create_user('test-user', '[email protected]', 'test-user')
self.user.user_permissions.add(Permission.objects.get(name='Can change gloss'))
self.user.save()
self.userprofile = UserProfile(user=self.user)
self.userprofile.save()
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
self.userprofile.selected_datasets.add(test_dataset)
self.userprofile.save()
self.handedness_fieldchoice_1 = FieldChoice.objects.filter(field='Handedness', machine_value__gt=1).first()
self.handedness_fieldchoice_2 = FieldChoice.objects.filter(field='Handedness', machine_value__gt=1).last()
def testSearchForGlosses(self):
#Create a client and log in
# client = Client()
client = Client(enforce_csrf_checks=True)
client.login(username='test-user', password='test-user')
#Get a dataset
dataset_name = settings.DEFAULT_DATASET
# Give the test user permission to change a dataset
test_dataset = Dataset.objects.get(name=dataset_name)
assign_perm('view_dataset', self.user, test_dataset)
assign_perm('change_dataset', self.user, test_dataset)
assign_perm('dictionary.search_gloss', self.user)
self.user.save()
# Create a lemma in order to store the dataset with the new gloss
new_lemma = LemmaIdgloss(dataset=test_dataset)
new_lemma.save()
# Create a lemma idgloss translation
default_language = Language.objects.get(id=get_default_language_id())
new_lemmaidglosstranslation = LemmaIdglossTranslation(text="thisisatemporarytestlemmaidglosstranslation",
lemma=new_lemma, language=default_language)
new_lemmaidglosstranslation.save()
# #Create the gloss
new_gloss = Gloss()
new_gloss.handedness = self.handedness_fieldchoice_1
new_gloss.lemma = new_lemma
new_gloss.save()
for language in test_dataset.translation_languages.all():
annotationIdgloss = AnnotationIdglossTranslation()
annotationIdgloss.gloss = new_gloss
annotationIdgloss.language = language
annotationIdgloss.text = 'thisisatemporarytestgloss'
annotationIdgloss.save()
# set the language for glosssearch field name
gloss_search_field_prefix = "glosssearch_"
glosssearch_field_name = gloss_search_field_prefix + default_language.language_code_2char
#Search
search_handedness_value = str(self.handedness_fieldchoice_1.machine_value)
response = client.get('/signs/search/?handedness[]='+search_handedness_value+'&'+glosssearch_field_name+'=test', follow=True)
self.assertEqual(len(response.context['object_list']), 1)
class ECVsNonEmptyTests(TestCase):
def setUp(self):
# a new test user is created for use during the tests
self.user = User.objects.create_user('test-user', '[email protected]', 'test-user')
def test_ECV_files_nonempty(self):
# test to see if there are glosses in all ecv files
# note: only the files in the ecv folder are checked for non-emptiness
# it is not checked whether there is an ecv file for all datasets
# ecv files for non-existing datasets are reported if empty
location_ecv_files = ECV_FOLDER
print('Checking for empty ECV files in location: ', location_ecv_files)
ecv_folder_exists = os.path.exists(location_ecv_files)
if not ecv_folder_exists:
print('The ECV folder is not in the correct location: ', location_ecv_files)
return
found_errors = False
from xml.etree import ElementTree
for filename in os.listdir(location_ecv_files):
fname, ext = os.path.splitext(os.path.basename(filename))
filetree = ElementTree.parse(location_ecv_files + os.sep + filename)
filetreeroot = filetree.getroot()
entry_nodes = filetreeroot.findall("./CONTROLLED_VOCABULARY/CV_ENTRY_ML")
# get the dataset using filter (returns a list)
try:
dataset_of_filename = Dataset.objects.get(acronym__iexact=fname)
except ObjectDoesNotExist:
uppercase_fname = fname.upper()
try:
fname_nounderscore = uppercase_fname.replace("_"," ")
dataset_of_filename = Dataset.objects.get(acronym__iexact=fname_nounderscore)
except ObjectDoesNotExist:
print('WARNING: ECV FILENAME DOES NOT MATCH DATASET ACRONYM: ', filename)
continue
if not len(entry_nodes):
# no glosses in the ecv
print('EMPTY ECV FILE FOUND: ', filename)
found_errors = True
self.assertEqual(found_errors, False)
class ImportExportTests(TestCase):
# Three test case scenario's for exporting ECV via the DatasetListView with DEFAULT_DATASET
# /datasets/available/?dataset_acronym=DEFAULT_DATASET&export_ecv=ECV
# 1. The user is logged in and has permission to change dataset
# 2. The user is logged in but does not have permission to change dataset
# 3. The user is not logged in
def setUp(self):
# create a new temp dataset with fields fetched from default dataset
default_dataset = Dataset.objects.get(acronym=settings.DEFAULT_DATASET_ACRONYM)
signlanguage = SignLanguage.objects.get(name=default_dataset.signlanguage.name)
translation_languages = default_dataset.translation_languages.all()
# the id is computed because datasets exist in the test database and we want an unused one
# this also ignores any datasets created during tests
used_dataset_ids = [ds.id for ds in Dataset.objects.all()]
max_used_dataset_id = max(used_dataset_ids)
# Create a temporary dataset that resembles the default dataset
new_dataset = Dataset(id=max_used_dataset_id+1,
acronym = settings.TEST_DATASET_ACRONYM,
name=settings.TEST_DATASET_ACRONYM,
default_language=default_dataset.default_language,
signlanguage = signlanguage)
new_dataset.save()
for language in translation_languages:
new_dataset.translation_languages.add(language)
# save the newly created dataset for the tests of this class
self.test_dataset = new_dataset
# a new test user is created for use during the tests
self.user = User.objects.create_user('test-user', '[email protected]', 'test-user')
def test_DatasetListView_ECV_export_empty_dataset(self):
print('Test DatasetListView export_ecv with empty dataset')
# Give the test user permission to change a dataset
assign_perm('change_dataset', self.user, self.test_dataset)
print('User has permmission to change dataset.')
client = Client(enforce_csrf_checks=False, json_encoder=DjangoJSONEncoder)
client.login(username='test-user', password='test-user')
url = '/datasets/available?dataset_acronym=' + self.test_dataset.acronym + '&export_ecv=ECV'
response = client.get(url, follow=True)
self.assertTrue("The dataset is empty, export ECV is not available." in str(response.content))
def test_DatasetListView_ECV_export_permission_change_dataset(self):
print('Test DatasetListView export_ecv with permission change_dataset')
print('Test Dataset is: ', self.test_dataset.acronym)
location_ecv_files = ECV_FOLDER
dataset_ecv_folder_exists = os.path.exists(location_ecv_files)
if not dataset_ecv_folder_exists:
print('The ecv folder is missing: ', location_ecv_files)
return
# Give the test user permission to change a dataset
assign_perm('change_dataset', self.user, self.test_dataset)
print('User has permmission to change dataset.')
client = Client(enforce_csrf_checks=False, json_encoder=DjangoJSONEncoder)
client.login(username='test-user', password='test-user')
# create a gloss and put it in the dataset so we can export it.
# this has many steps
# Create a lemma first
new_lemma = LemmaIdgloss(dataset=self.test_dataset)
new_lemma.save()
# Create a lemma idgloss translation
language = self.test_dataset.default_language
new_lemmaidglosstranslation = LemmaIdglossTranslation(text="thisisatemporarytestlemmaidglosstranslation",
lemma=new_lemma, language=language)
new_lemmaidglosstranslation.save()
#Create the gloss
new_gloss = Gloss()
new_gloss.lemma = new_lemma
new_gloss.save()
# fill in the annotation translations for the new gloss
for language in self.test_dataset.translation_languages.all():
annotationIdgloss = AnnotationIdglossTranslation()
annotationIdgloss.gloss = new_gloss
annotationIdgloss.language = language
annotationIdgloss.text = 'thisisatemporarytestgloss'
annotationIdgloss.save()
url = '/datasets/available?dataset_acronym=' + self.test_dataset.acronym + '&export_ecv=ECV'
response = client.get(url, follow=True)
self.assertTrue("ECV successfully updated." in str(response.content))
location_ecv_files = ECV_FOLDER
for filename in os.listdir(location_ecv_files):
if filename == self.test_dataset.acronym.lower() + '.ecv':
filename_path = os.path.join(location_ecv_files, filename)
os.remove(filename_path)
print('Temp ecv file removed.')
def test_DatasetListView_ECV_export_no_permission_change_dataset(self):
print('Test DatasetListView export_ecv without permission')
print('Test Dataset is: ', self.test_dataset.acronym)
client = Client(enforce_csrf_checks=False, json_encoder=DjangoJSONEncoder)
client.login(username='test-user', password='test-user')
url = '/datasets/available?dataset_acronym=' + self.test_dataset.acronym + '&export_ecv=ECV'
response = client.get(url, follow=True)
self.assertTrue("No permission to export dataset." in str(response.content))
def test_DatasetListView_not_logged_in_ECV_export(self):
print('Test DatasetListView export_ecv anonymous user not logged in')
print('Test Dataset is: ', self.test_dataset.acronym)
client = Client()
url = '/datasets/available?dataset_acronym=' + self.test_dataset.acronym + '&export_ecv=ECV'
response = client.get(url, follow=True)
self.assertTrue("Please login to use this functionality." in str(response.content))
def test_Export_csv(self):
client = Client()
logged_in = client.login(username=self.user.username, password='test-user')
# Check whether the user is logged in
self.assertTrue(logged_in)
print('Test Dataset is: ', self.test_dataset.acronym)
# Give the test user permission to change a dataset
assign_perm('change_dataset', self.user, self.test_dataset)
print('User has permmission to change dataset.')
assign_perm('dictionary.export_csv', self.user)
print('User has permmission to export csv.')
response = client.get('/signs/search/',
{'format': 'CSV'}, follow=True)
streaming_rows = b''.join(response.streaming_content)
self.assertEqual(response['Content-Type'], "text/csv")
self.assertIn(bytes('Signbank ID,', 'utf-8'), streaming_rows)
self.assertIn(bytes(',Dataset', 'utf-8'), streaming_rows)
def test_Import_csv_update_gloss_for_lemma(self):
"""
This method will test the last stage (#2) importing of a csv with changes to Lemma Idgloss Translations
:return:
"""
client = Client()
logged_in = client.login(username=self.user.username, password='test-user')
# Check whether the user is logged in
self.assertTrue(logged_in)
print('Test Dataset is: ', self.test_dataset.acronym)
# Give the test user permission to change a dataset
assign_perm('change_dataset', self.user, self.test_dataset)
print('User has permmission to change dataset.')
# Create test lemma idgloss
lemma = LemmaIdgloss(dataset=self.test_dataset)
lemma.save()
# Create test lemma idgloss translations
lemma_idgloss_translation_prefix = 'test_lemma_translation_'
test_translation_index = 1
for language in self.test_dataset.translation_languages.all():
lemma_translation = LemmaIdglossTranslation(lemma=lemma, language=language,
text='{}{}_{}'.format(lemma_idgloss_translation_prefix,
language.language_code_2char, test_translation_index))
lemma_translation.save()
# Create test gloss
gloss = Gloss(lemma=lemma)
gloss.save()
# Prepare form data for making A NEW LemmaIdgloss + LemmaIdglossTranslations
test_translation_index = 2
form_data = {'update_or_create': 'update'}
for language in self.test_dataset.translation_languages.all():
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
form_name = '{}.Lemma ID Gloss ({})'.format(gloss.id, language_name)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_translation_index)
print('Form data test 1 of test_Import_csv_update_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_update'), form_data, follow=True)
self.assertContains(response, 'Attempt to update Lemma translations')
# Prepare form data for linking to AN EXISTING LemmaIdgloss + LemmaIdglossTranslations
test_translation_index = 1
form_data = {'update_or_create': 'update'}
for language in self.test_dataset.translation_languages.all():
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
form_name = '{}.Lemma ID Gloss ({})'.format(gloss.id, language_name)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_translation_index)
print('Form data test 2 of test_Import_csv_update_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_update'), form_data, follow=True)
self.assertEqual(response.status_code, 200)
count_dataset_translation_languages = self.test_dataset.translation_languages.all().count()
print('Number of translation languages for the test dataset: ', count_dataset_translation_languages)
# Prepare form data for linking to SEVERAL EXISTING LemmaIdgloss + LemmaIdglossTranslations
form_data = {'update_or_create': 'update'}
for index, language in enumerate(self.test_dataset.translation_languages.all()):
if index == 0:
test_translation_index = 1
else:
test_translation_index = 2
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
form_name = '{}.Lemma ID Gloss ({})'.format(gloss.id, language_name)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_translation_index)
print('Form data test 3 of test_Import_csv_update_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_update'), form_data, follow=True)
if count_dataset_translation_languages > 1:
print('More than one translation language, attempt to update a lemma translation')
self.assertContains(response, 'Attempt to update Lemma translations')
else:
print('Only one translation language, no changes found')
self.assertContains(response, 'No changes were found.')
# Prepare form data for linking to SEVERAL EXISTING LemmaIdgloss + LemmaIdglossTranslations
form_data = {'update_or_create': 'update'}
for index, language in enumerate(self.test_dataset.translation_languages.all()):
if index == 0:
test_translation_index = 1
else:
test_translation_index = 3
language_name = getattr(language, settings.DEFAULT_LANGUAGE_HEADER_COLUMN['English'])
form_name = '{}.Lemma ID Gloss ({})'.format(gloss.id, language_name)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_translation_index)
print('Form data test 4 of test_Import_csv_update_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_update'), form_data, follow=True)
if count_dataset_translation_languages > 1:
print('More than one translation language, attempt to update a lemma translation')
self.assertContains(response, 'Attempt to update Lemma translations')
else:
print('Only one translation language, no changes found')
self.assertContains(response, 'No changes were found.')
def test_Import_csv_new_gloss_for_lemma(self):
"""
This method will test the last stage (#2) importing of a csv with a new gloss with Lemma Idgloss Translations
:return:
"""
client = Client()
logged_in = client.login(username=self.user.username, password='test-user')
# Check whether the user is logged in
self.assertTrue(logged_in)
print('Test Dataset is: ', self.test_dataset.acronym)
# Give the test user permission to change a dataset
assign_perm('change_dataset', self.user, self.test_dataset)
print('User has permmission to change dataset.')
gloss_id = 1
lemma_idgloss_translation_prefix = 'test_lemma_translation_'
annotation_idgloss_translation_prefix = 'test_annotation_translation_'
# Prepare form data for making A NEW LemmaIdgloss + LemmaIdglossTranslations
test_lemma_translation_index = 1
test_annotation_translation_index = 1
form_data = {'update_or_create': 'create', '{}.dataset'.format(gloss_id): self.test_dataset.acronym}
for language in self.test_dataset.translation_languages.all():
form_name = '{}.lemma_id_gloss_{}'.format(gloss_id, language.language_code_2char)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_lemma_translation_index)
form_name = '{}.annotation_id_gloss_{}'.format(gloss_id, language.language_code_2char)
form_data[form_name] = '{}{}_{}'.format(annotation_idgloss_translation_prefix, language.language_code_2char,
test_annotation_translation_index)
print('Form data test 1 of test_Import_csv_new_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_create'), form_data)
self.assertContains(response, 'Changes are live.')
# Prepare form data for linking to AN EXISTING LemmaIdgloss + LemmaIdglossTranslations
test_annotation_translation_index = 2
form_data = {'update_or_create': 'create', '{}.dataset'.format(gloss_id): self.test_dataset.acronym}
for language in self.test_dataset.translation_languages.all():
form_name = '{}.lemma_id_gloss_{}'.format(gloss_id, language.language_code_2char)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_lemma_translation_index)
form_name = '{}.annotation_id_gloss_{}'.format(gloss_id, language.language_code_2char)
form_data[form_name] = '{}{}_{}'.format(annotation_idgloss_translation_prefix, language.language_code_2char,
test_annotation_translation_index)
print('Form data test 2 of test_Import_csv_new_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_create'), form_data)
self.assertContains(response, 'Changes are live.')
count_dataset_translation_languages = self.test_dataset.translation_languages.all().count()
print('Number of translation languages for the test dataset: ', count_dataset_translation_languages)
# Prepare form data for linking to SEVERAL EXISTING LemmaIdgloss + LemmaIdglossTranslations
test_annotation_translation_index = 3
form_data = {'update_or_create': 'create', '{}.dataset'.format(gloss_id): self.test_dataset.acronym}
for index, language in enumerate(self.test_dataset.translation_languages.all()):
if index == 0:
test_lemma_translation_index = 1
else:
test_lemma_translation_index = 2
form_name = '{}.lemma_id_gloss_{}'.format(gloss_id, language.language_code_2char)
form_data[form_name] = '{}{}_{}'.format(lemma_idgloss_translation_prefix, language.language_code_2char,
test_lemma_translation_index)
form_name = '{}.annotation_id_gloss_{}'.format(gloss_id, language.language_code_2char)
form_data[form_name] = '{}{}_{}'.format(annotation_idgloss_translation_prefix, language.language_code_2char,
test_annotation_translation_index)
print('Form data test 3 of test_Import_csv_new_gloss_for_lemma: \n', form_data)
response = client.post(reverse_lazy('import_csv_create'), form_data, follow=True)
if count_dataset_translation_languages > 1:
print('More than one translation language, attempt to update to combination of existing and new lemma translations')
self.assertContains(response, "the combination of Lemma ID Gloss translations should either refer")
else:
print('Only one translation language, only the annotation translation is changed.')
self.assertContains(response, 'Changes are live.')
class VideoTests(TestCase):
def setUp(self):
# a new test user is created for use during the tests
self.user = User.objects.create_user('test-user', '[email protected]', 'test-user')
self.handedness_fieldchoice_1 = FieldChoice.objects.filter(field='Handedness', machine_value__gt=1).first()
self.handedness_fieldchoice_2 = FieldChoice.objects.filter(field='Handedness', machine_value__gt=1).last()
def test_create_and_delete_video(self):
client = Client()
logged_in = client.login(username='test-user', password='test-user')
# Check whether the user is logged in
self.assertTrue(logged_in)
NAME = 'thisisatemporarytestlemmaidglosstranslation'
# Create the glosses
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
default_language = Language.objects.get(id=settings.DEFAULT_DATASET_LANGUAGE_ID)
assign_perm('change_dataset', self.user, test_dataset)
print('User granted permmission to change dataset.')
# Create a lemma
new_lemma = LemmaIdgloss(dataset=test_dataset)
new_lemma.save()
# Create a lemma idgloss translation
new_lemmaidglosstranslation = LemmaIdglossTranslation(text="thisisatemporarytestlemmaidglosstranslation",
lemma=new_lemma, language=default_language)
new_lemmaidglosstranslation.save()
#Create the gloss
new_gloss = Gloss()
new_gloss.handedness = self.handedness_fieldchoice_1
new_gloss.lemma = new_lemma
new_gloss.save()
client = Client()
client.login(username='test-user', password='test-user')
video_url = '/dictionary/protected_media/glossvideo/'+test_dataset.acronym+'/'+NAME[0:2]+'/'+NAME+'-'+str(new_gloss.pk)+'.mp4'
#We expect no video before
response = client.get(video_url)
if response.status_code == 200:
print('The test video already exists in the archive: ', video_url)
self.assertEqual(response.status_code,200)
test_video_file_exists = True
else:
print('The test video does not exist in the archive: ', video_url)
self.assertEqual(response.status_code,302)
# Upload the video
print('Uploading the test video.')
try:
videofile = open(settings.WRITABLE_FOLDER+'test_data/video.mp4', 'rb')
test_video_file_exists = True
except (FileNotFoundError, PermissionError):
test_video_file_exists = False
videofile = ''
print('The test video is missing: ', settings.WRITABLE_FOLDER+'test_data/video.mp4')
if test_video_file_exists:
response = client.post('/video/upload/', {'object_id': new_gloss.pk,
'videofile': videofile,
'object_type': 'gloss_video',
'redirect': '{{PREFIX_URL}}/dictionary/gloss/'+str(new_gloss.pk)+'/?edit'},
follow=True)
self.assertEqual(response.status_code, 200)
if not test_video_file_exists:
return
# We expect a video now
print('Try to view the video: ', video_url)
response = client.get(video_url, follow=True)
self.assertEqual(response.status_code, 200)
# You can't see it if you log out
client.logout()
print('User has logged out.')
print('Attempt to see video. Must log in.')
response = client.get(video_url)
self.assertEqual(response.status_code,200)
# Remove the video
client.login(username='test-user',password='test-user')
print('User has logged back in.')
print('Delete the uploaded video.')
response = client.post('/video/delete/'+str(new_gloss.pk))
delete_response = response.status_code
print('Status after deleting: ', delete_response)
if delete_response != '200':
print("Error deleting the video! Check System folder permissions!")
else:
# We expect no video anymore
print('Attempt to see video. It is not found.')
response = client.get(video_url)
print('status code: ', response.status_code)
self.assertEqual(response.status_code, '302')
def test_create_and_delete_utf8_video(self):
client = Client()
logged_in = client.login(username='test-user', password='test-user')
# Check whether the user is logged in
self.assertTrue(logged_in)
NAME = 'XXtéstlemmä%20~山脉%20' # %20 is an url encoded space
# Create the glosses
dataset_name = settings.DEFAULT_DATASET
test_dataset = Dataset.objects.get(name=dataset_name)
default_language = Language.objects.get(id=settings.DEFAULT_DATASET_LANGUAGE_ID)
assign_perm('change_dataset', self.user, test_dataset)
print('User granted permmission to change dataset.')
# Create a lemma
new_lemma = LemmaIdgloss(dataset=test_dataset)
new_lemma.save()
# Create a lemma idgloss translation
new_lemmaidglosstranslation = LemmaIdglossTranslation(text=NAME,
lemma=new_lemma, language=default_language)
new_lemmaidglosstranslation.save()
# Create the gloss
new_gloss = Gloss()
new_gloss.handedness = self.handedness_fieldchoice_1
new_gloss.lemma = new_lemma
new_gloss.save()
client = Client()
client.login(username='test-user', password='test-user')
video_url = '/dictionary/protected_media/glossvideo/'+test_dataset.acronym+'/'+NAME[0:2]+'/'+NAME+'-'+str(new_gloss.pk)+'.mp4'
if hasattr(settings, 'ESCAPE_UPLOADED_VIDEO_FILE_PATH') and settings.ESCAPE_UPLOADED_VIDEO_FILE_PATH:
# If the file name is escaped, the url should be escaped twice:
# the file may contain percent encodings,
# so in the path the percent should be encoded
from django.utils.encoding import escape_uri_path
video_url = escape_uri_path(video_url)
video_url = video_url.replace('%', '%25')
# We expect no video before
response = client.get(video_url)
if response.status_code == 200:
print('The test video already exists in the archive: ', video_url)
self.assertEqual(response.status_code, 200)
test_video_file_exists = True
else:
print('The test video does not exist in the archive: ', video_url)
self.assertEqual(response.status_code, 302)
# Upload the video
try:
videofile = open(settings.WRITABLE_FOLDER+'test_data/video.mp4', 'rb')
test_video_file_exists = True
except (FileNotFoundError, PermissionError):
test_video_file_exists = False
videofile = ''
print('The test video is missing: ', settings.WRITABLE_FOLDER+'test_data/video.mp4')
if test_video_file_exists:
response = client.post('/video/upload/', {'object_id': new_gloss.pk,
'videofile': videofile,
'object_type': 'gloss_video',
'redirect': '{{PREFIX_URL}}/dictionary/gloss/'+str(new_gloss.pk)+'/?edit'},
follow=True)
self.assertEqual(response.status_code, 200)
if not test_video_file_exists:
return
# We expect a video now
print('Try to view the video: ', video_url)
response = client.get(video_url, follow=True)
print("Video url second test: {}".format(video_url))
print("Video upload response second test: {}".format(response))
self.assertEqual(response.status_code,200)
# You can't see it if you log out
client.logout()
print('User has logged out.')
print('Attempt to see video. Must log in.')