-
Notifications
You must be signed in to change notification settings - Fork 7
/
test_app.py
1322 lines (1218 loc) · 57.2 KB
/
test_app.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 copy
import flask
from html.parser import HTMLParser
import json
import pytest
import re
from toolforge_i18n import lang_mw_to_bcp47
import werkzeug
import app as lexeme_forms
import matching
from templates import templates_without_redirects
def test_form2input_basic():
markup = lexeme_forms.form2input({'advanced': False}, {'example': 'Left [placeholder] right.'})
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" required spellcheck="true"> right.'
def test_form2input_advanced():
markup = lexeme_forms.form2input({'advanced': True}, {'example': 'Left [placeholder] right.'})
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" spellcheck="true"> right.'
def test_form2input_optional():
markup = lexeme_forms.form2input({'advanced': False}, {'example': 'Left [placeholder] right.', 'optional': True})
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" spellcheck="true"> right.'
def test_form2input_first():
markup = lexeme_forms.form2input({'advanced': True}, {'example': 'Left [placeholder] right.'}, first=True)
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" autofocus spellcheck="true"> right.'
def test_form2input_readonly():
markup = lexeme_forms.form2input({'advanced': False}, {'example': 'Left [placeholder] right.'}, readonly=True)
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" required disabled spellcheck="true"> right.'
def test_form2input_preserve_value():
markup = lexeme_forms.form2input({'advanced': True}, {'example': 'Left [placeholder] right.', 'value': 'value'})
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" value="value" spellcheck="true"> right.'
def test_form2input_escape_value():
markup = lexeme_forms.form2input({'advanced': True}, {'example': 'Left [placeholder] right.', 'value': '"<>&'})
assert str(markup) == r'Left <input type="text" name="form_representation" placeholder="placeholder" pattern="[^\/]+(?:\/[^\/]+)*" value=""<>&" spellcheck="true"> right.'
def test_form2input_invalid():
with pytest.raises(Exception) as excinfo:
markup = lexeme_forms.form2input({'advanced': True}, {'example': 'No placeholder.'}) # noqa:F841
assert 'missing [placeholder]' in str(excinfo.value)
@pytest.mark.parametrize('example, expected_prefix, expected_placeholder, expected_suffix', [
('Left [placeholder] right.', 'Left ', 'placeholder', ' right.'),
('[placeholder] right.', '', 'placeholder', ' right.'),
('Left [placeholder]', 'Left ', 'placeholder', ''),
('[placeholder]', '', 'placeholder', ''),
('Left [] right.', 'Left ', '', ' right.'),
])
def test_split_example(example, expected_prefix, expected_placeholder, expected_suffix):
form = {'example': example}
(actual_prefix, actual_placeholder, actual_suffix) = lexeme_forms.split_example(form)
assert (expected_prefix, expected_placeholder, expected_suffix) \
== (actual_prefix, actual_placeholder, actual_suffix)
@pytest.mark.parametrize('example', [
'Left right.',
'Left [placeholder right.',
'Left placeholder] right.',
'Left ]placeholder[ right.',
])
def test_split_example_error(example):
form = {'example': example}
with pytest.raises(Exception):
lexeme_forms.split_example(form)
def test_csrf_token_generate():
with lexeme_forms.app.test_request_context():
token = lexeme_forms.csrf_token()
assert token != ''
def test_csrf_token_save():
with lexeme_forms.app.test_request_context() as context:
token = lexeme_forms.csrf_token()
assert token == context.session['_csrf_token']
def test_csrf_token_load():
with lexeme_forms.app.test_request_context() as context:
context.session['_csrf_token'] = 'test token'
assert lexeme_forms.csrf_token() == 'test token'
def test_template_group():
with lexeme_forms.app.test_request_context():
flask.g.html_language_codes = []
group = lexeme_forms.template_group({'language_code': 'de'})
assert group == '<span lang="de" dir="ltr">Deutsch (<span lang=zxx>de</span>)</span>'
def test_template_group_test():
with lexeme_forms.app.test_request_context():
flask.g.html_language_codes = []
group = lexeme_forms.template_group({'language_code': 'de', 'test': True})
assert group == '<span lang="de" dir="ltr">Deutsch (<span lang=zxx>de</span>)</span>, test.wikidata.org'
@pytest.mark.parametrize('number', range(-1, 5))
def test_message(language_code, number):
with lexeme_forms.app.test_request_context():
flask.g.interface_language_code = language_code
flask.g.qqx = False
flask.g.html_language_codes = [lang_mw_to_bcp47(language_code)]
message = lexeme_forms.message( # noqa: F841
'description-with-forms-and-senses',
description='',
num_forms=number,
num_senses=number,
)
# should not have failed
def test_if_no_such_template_redirect_known_template():
assert lexeme_forms.if_no_such_template_redirect('english-noun') is None
def test_if_no_such_template_redirect_renamed_template():
with lexeme_forms.app.test_client() as client:
response = client.get('/template/dutch-feminine-noun/')
assert response.status_code == 307
assert response.headers['location'].endswith('/template/dutch-noun-feminine/')
def test_if_no_such_template_redirect_unknown_template():
template_name = 'no-such-template'
with lexeme_forms.app.test_client() as client:
response = client.get(f'/template/{template_name}/')
assert 'alert' in response.text
assert template_name in response.text
def test_if_has_duplicates_redirect_checkbox_checked():
assert lexeme_forms.if_has_duplicates_redirect(
{},
False,
werkzeug.datastructures.ImmutableMultiDict({'no_duplicate': True}),
) is None
def test_if_has_duplicates_redirect_lexeme_id_specified():
assert lexeme_forms.if_has_duplicates_redirect(
{},
False,
werkzeug.datastructures.ImmutableMultiDict({'lexeme_id': 'L123'}),
) is None
def test_if_has_duplicates_redirect_lexeme_id_blank(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'find_duplicates', lambda template, form_data: ['duplicate'])
monkeypatch.setattr(lexeme_forms, 'add_form_data_to_template', lambda form_data, template: True)
monkeypatch.setattr(flask, 'render_template', lambda template_file_name, **kwargs: True)
assert lexeme_forms.if_has_duplicates_redirect(
minimal_template,
False,
werkzeug.datastructures.ImmutableMultiDict({'lexeme_id': ''}),
) is not None
def test_if_has_duplicates_redirect_some_duplicates(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'find_duplicates', lambda template, form_data: ['duplicate'])
monkeypatch.setattr(lexeme_forms, 'add_form_data_to_template', lambda form_data, template: True)
monkeypatch.setattr(flask, 'render_template', lambda template_file_name, **kwargs: 'rendered duplicates')
assert lexeme_forms.if_has_duplicates_redirect(
minimal_template,
False,
werkzeug.datastructures.ImmutableMultiDict(),
) == 'rendered duplicates'
def test_if_has_duplicates_redirect_no_duplicates(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'find_duplicates', lambda template, form_data: [])
assert lexeme_forms.if_has_duplicates_redirect(
{},
False,
werkzeug.datastructures.ImmutableMultiDict(),
) is None
def test_if_has_duplicates_redirect_submitted_form_representations(monkeypatch):
def render_template(template_file_name, **kwargs):
assert template_file_name == 'template.html'
assert kwargs['submitted_form_representations'] == ['noun', 'nouns']
return 'rendered duplicates'
monkeypatch.setattr(lexeme_forms, 'find_duplicates', lambda template, form_data: ['duplicate'])
monkeypatch.setattr(lexeme_forms, 'add_form_data_to_template', lambda form_data, template: True)
monkeypatch.setattr(flask, 'render_template', render_template)
assert lexeme_forms.if_has_duplicates_redirect(
copy.deepcopy(templates_without_redirects['english-noun']),
False,
werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun'), ('form_representation', 'nouns')]),
) == 'rendered duplicates'
def test_get_lemma_first_form_representation():
template = templates_without_redirects['english-noun']
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun'), ('form_representation', 'nouns')])
lemma = lexeme_forms.get_lemma(template, form_data)
assert lemma == 'noun'
def test_get_lemma_second_form_representation():
template = templates_without_redirects['english-noun']
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', ''), ('form_representation', 'nouns')])
lemma = lexeme_forms.get_lemma(template, form_data)
assert lemma == 'nouns'
def test_get_lemma_no_form_representation():
template = templates_without_redirects['english-noun']
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', ''), ('form_representation', '')])
lemma = lexeme_forms.get_lemma(template, form_data)
assert lemma is None
def test_get_lemma_first_marked_form_representation():
template = {'forms': [
{},
{'lemma': True},
{'lemma': True},
]}
form_data = werkzeug.datastructures.ImmutableMultiDict([
('form_representation', 'a'),
('form_representation', 'b'),
('form_representation', 'c'),
])
lemma = lexeme_forms.get_lemma(template, form_data)
assert lemma == 'b'
def test_get_lemma_second_marked_form_representation():
template = {'forms': [
{},
{'lemma': True},
{'lemma': True},
]}
form_data = werkzeug.datastructures.ImmutableMultiDict([
('form_representation', 'a'),
('form_representation', ''),
('form_representation', 'c'),
])
lemma = lexeme_forms.get_lemma(template, form_data)
assert lemma == 'c'
def test_get_lemma_no_marked_form_representation():
template = {'forms': [
{},
{'lemma': True},
{'lemma': True},
]}
form_data = werkzeug.datastructures.ImmutableMultiDict([
('form_representation', 'a'),
('form_representation', ''),
('form_representation', ''),
])
lemma = lexeme_forms.get_lemma(template, form_data)
assert lemma == 'a'
def test_build_lemmas():
template = templates_without_redirects['english-noun']
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun')])
lemmas = lexeme_forms.build_lemmas(template, form_data)
assert lemmas == {'en': {'language': 'en', 'value': 'noun'}}
def test_get_duplicates_api_json(monkeypatch):
duplicates = [{'id': 'L1', 'uri': 'http://www.wikidata.org/wiki/Lexeme:L1', 'label': 'lemma', 'description': 'a lexeme', 'forms_count': None, 'senses_count': None}]
monkeypatch.setattr(lexeme_forms, 'get_duplicates', lambda wiki, language_code, lemma: duplicates)
with lexeme_forms.app.test_client() as client:
response = client.get('/api/v1/duplicates/www/en/lemma')
assert response.content_type == 'application/json'
assert json.loads(response.get_data(as_text=True)) == duplicates
def test_get_duplicates_api_html_two(monkeypatch):
duplicates = [{'id': 'L1', 'uri': 'http://www.wikidata.org/wiki/Lexeme:L1', 'label': 'test1 lemma', 'description': 'a test1 lexeme', 'forms_count': None, 'senses_count': None},
{'id': 'L2', 'uri': 'http://www.wikidata.org/wiki/Lexeme:L2', 'label': 'test2 lemma', 'description': 'a test2 lexeme', 'forms_count': None, 'senses_count': None}]
monkeypatch.setattr(lexeme_forms, 'get_duplicates', lambda wiki, language_code, lemma: duplicates)
with lexeme_forms.app.test_client() as client:
with client.session_transaction() as session:
session['interface_language_code'] = 'de'
response = client.get('/api/v1/duplicates/www/de/lemma', headers={'Accept': 'text/html'})
assert response.content_type == 'text/html; charset=utf-8'
response_text = response.get_data(as_text=True)
assert 'haben das gleiche Lemma' in response_text
assert 'kreuze das Kästchen' in response_text
assert 'test1 lemma' in response_text
assert 'a test1 lexeme' in response_text
assert 'test2 lemma' in response_text
assert 'a test2 lexeme' in response_text
def test_get_duplicates_api_html_one(monkeypatch):
duplicates = [{'id': 'L1', 'uri': 'http://www.wikidata.org/wiki/Lexeme:L1', 'label': 'test lemma', 'description': 'a test lexeme', 'forms_count': None, 'senses_count': None}]
monkeypatch.setattr(lexeme_forms, 'get_duplicates', lambda wiki, language_code, lemma: duplicates)
with lexeme_forms.app.test_client() as client:
with client.session_transaction() as session:
session['interface_language_code'] = 'de'
response = client.get('/api/v1/duplicates/www/de/lemma', headers={'Accept': 'text/html'})
assert response.content_type == 'text/html; charset=utf-8'
response_text = response.get_data(as_text=True)
assert 'hat das gleiche Lemma' in response_text
assert 'kreuze das Kästchen' in response_text
assert 'test lemma' in response_text
assert 'a test lexeme' in response_text
def test_get_duplicates_api_html_empty(monkeypatch):
duplicates = []
monkeypatch.setattr(lexeme_forms, 'get_duplicates', lambda wiki, language_code, lemma: duplicates)
with lexeme_forms.app.test_client() as client:
response = client.get('/api/v1/duplicates/www/de/lemma', headers={'Accept': 'text/html'})
assert response.content_type == 'text/html; charset=utf-8'
assert response.get_data(as_text=True) == ''
minimal_template = {
'@template_name': 'minimal-template',
'language_code': 'en',
}
def test_if_needs_csrf_redirect_no_token(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'add_form_data_to_template', lambda form_data, template: True)
monkeypatch.setattr(flask, 'render_template', lambda template_file_name, **kwargs: 'rendered template')
with lexeme_forms.app.test_request_context():
response = lexeme_forms.if_needs_csrf_redirect(minimal_template, False, {})
assert response == 'rendered template'
# TODO instead of monkeypatching, assert that form_data is correctly preserved (possibly in separate test)
def test_if_needs_csrf_redirect_wrong_token(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'add_form_data_to_template', lambda form_data, template: True)
monkeypatch.setattr(flask, 'render_template', lambda template_file_name, **kwargs: 'rendered template')
with lexeme_forms.app.test_request_context() as context:
context.session['_csrf_token'] = 'token 1'
response = lexeme_forms.if_needs_csrf_redirect(minimal_template, False, {'_csrf_token': 'token 2'})
assert response == 'rendered template'
def test_if_needs_csrf_redirect_correct_token(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'add_form_data_to_template', lambda form_data, template: True)
monkeypatch.setattr(flask, 'render_template', lambda template_file_name, **kwargs: 'rendered template')
with lexeme_forms.app.test_request_context() as context:
context.session['_csrf_token'] = 'token'
response = lexeme_forms.if_needs_csrf_redirect(minimal_template, False, {'_csrf_token': 'token'})
assert response is None
def test_add_form_data_to_template():
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun'), ('form_representation', 'nouns')])
template = {
'forms': [
{
'label': 'singular',
'example': 'One [thing].',
'grammatical_features_item_ids': ['Q110786'],
'value': 'Noun',
},
{
'label': 'plural',
'example': 'Two [things]',
'grammatical_features_item_ids': ['Q146786'],
},
],
'other_data': 'preserve',
}
new_template = lexeme_forms.add_form_data_to_template(form_data, template)
assert new_template == {
'forms': [
{
'label': 'singular',
'example': 'One [thing].',
'grammatical_features_item_ids': ['Q110786'],
'value': 'noun',
},
{
'label': 'plural',
'example': 'Two [things]',
'grammatical_features_item_ids': ['Q146786'],
'value': 'nouns',
},
],
'other_data': 'preserve',
}
def test_add_form_data_to_template_no_overwrite():
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun'), ('form_representation', 'nouns')])
template = {
'forms': [
{
'label': 'singular',
'example': 'One [thing].',
'grammatical_features_item_ids': ['Q110786'],
'value': 'Noun',
},
{
'label': 'plural',
'example': 'Two [things]',
'grammatical_features_item_ids': ['Q146786'],
},
],
'other_data': 'preserve',
}
new_template = lexeme_forms.add_form_data_to_template(form_data, template, overwrite=False)
assert new_template == {
'forms': [
{
'label': 'singular',
'example': 'One [thing].',
'grammatical_features_item_ids': ['Q110786'],
'value': 'Noun',
},
{
'label': 'plural',
'example': 'Two [things]',
'grammatical_features_item_ids': ['Q146786'],
'value': 'nouns',
},
],
'other_data': 'preserve',
}
def test_add_form_data_to_template_lexeme_id():
form_data = werkzeug.datastructures.ImmutableMultiDict([('lexeme_id', 'L123')])
template = {'forms': []}
new_template = lexeme_forms.add_form_data_to_template(form_data, template)
assert new_template['lexeme_id'] == 'L123'
def test_add_form_data_to_template_generated_via():
form_data = werkzeug.datastructures.ImmutableMultiDict([('generated_via', 'something')])
template = {'forms': []}
new_template = lexeme_forms.add_form_data_to_template(form_data, template)
assert new_template['generated_via'] == 'something'
def test_add_form_data_to_template_target_hash():
form_data = werkzeug.datastructures.ImmutableMultiDict([('target_hash', 'something')])
template = {'forms': []}
new_template = lexeme_forms.add_form_data_to_template(form_data, template)
assert new_template['target_hash'] == 'something'
def test_add_form_data_to_template_no_template_modification():
form_data = werkzeug.datastructures.ImmutableMultiDict([('lexeme_id', 'L123')])
template = {'forms': []}
new_template = lexeme_forms.add_form_data_to_template(form_data, template)
assert template is not new_template
assert 'lexeme_id' not in template
def test_current_url_index(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/')
with lexeme_forms.app.test_request_context('/'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/'
def test_current_url_template(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/')
with lexeme_forms.app.test_request_context('/template/foo/'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/template/foo/'
def test_current_url_template_advanced(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/')
with lexeme_forms.app.test_request_context('/template/foo/advanced/'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/template/foo/advanced/'
def test_current_url_application_root(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/foo/')
with lexeme_forms.app.test_request_context('/template/bar/'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/foo/template/bar/'
def test_current_url_arglist(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/')
with lexeme_forms.app.test_request_context('/template/foo/?form_representation=X&form_representation=Y'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/template/foo/?form_representation=X&form_representation=Y'
def test_current_url_space(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/')
with lexeme_forms.app.test_request_context('/template/foo/?form_representation=X%20Y%20Z'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/template/foo/?form_representation=X%20Y%20Z'
def test_current_url_encoded(monkeypatch):
monkeypatch.setitem(lexeme_forms.app.config, 'APPLICATION_ROOT', '/')
with lexeme_forms.app.test_request_context('/template/bokm%C3%A5l-noun-masculine/'):
current_url = lexeme_forms.current_url()
assert current_url == 'http://localhost/template/bokm%C3%A5l-noun-masculine/'
def test_build_lexeme():
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
},
{
'grammatical_features_item_ids': ['Q146786'],
},
],
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun'), ('form_representation', 'nouns')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'noun'}},
'grammaticalFeatures': ['Q110786'],
'claims': {},
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'nouns'}},
'grammaticalFeatures': ['Q146786'],
'claims': {},
},
],
'lemmas': {'en': {'language': 'en', 'value': 'noun'}},
'language': 'Q1860',
'lexicalCategory': 'Q1084',
'claims': {},
}
def test_build_lexeme_with_empty_lexeme_id():
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
},
],
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('lexeme_id', ''), ('form_representation', 'noun')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'noun'}},
'grammaticalFeatures': ['Q110786'],
'claims': {},
},
],
'lemmas': {'en': {'language': 'en', 'value': 'noun'}},
'language': 'Q1860',
'lexicalCategory': 'Q1084',
'claims': {},
}
def test_build_lexeme_with_nonempty_lexeme_id(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'get_lexeme_data', lambda lexeme_id, wiki: {'language': 'Q1860', 'lexicalCategory': 'Q1084'})
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
},
],
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('lexeme_id', 'L123'), ('form_representation', 'noun')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'noun'}},
'grammaticalFeatures': ['Q110786'],
'claims': {},
},
],
'id': 'L123',
'claims': {},
}
def test_build_lexeme_blank_form(monkeypatch):
monkeypatch.setattr(lexeme_forms, 'get_lexeme_data', lambda lexeme_id, wiki: {'language': 'Q1860', 'lexicalCategory': 'Q1084'})
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
},
{
'grammatical_features_item_ids': ['Q146786'],
},
],
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('lexeme_id', 'L123'), ('form_representation', ''), ('form_representation', 'nouns')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'nouns'}},
'grammaticalFeatures': ['Q146786'],
'claims': {},
},
],
'id': 'L123',
'claims': {},
}
def test_build_lexeme_with_statements():
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
'statements': 'singular test statements',
},
{
'grammatical_features_item_ids': ['Q146786'],
'statements': 'plural test statements',
},
],
'statements': 'lexeme test statements',
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun'), ('form_representation', 'nouns')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'noun'}},
'grammaticalFeatures': ['Q110786'],
'claims': 'singular test statements',
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'nouns'}},
'grammaticalFeatures': ['Q146786'],
'claims': 'plural test statements',
},
],
'lemmas': {'en': {'language': 'en', 'value': 'noun'}},
'language': 'Q1860',
'lexicalCategory': 'Q1084',
'claims': 'lexeme test statements',
}
def test_build_lexeme_with_variants():
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
},
{
'grammatical_features_item_ids': ['Q146786'],
},
],
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'noun/NOUN'), ('form_representation', 'nouns/NOUNS/nounS')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'noun'}},
'grammaticalFeatures': ['Q110786'],
'claims': {},
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'NOUN'}},
'grammaticalFeatures': ['Q110786'],
'claims': {},
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'nouns'}},
'grammaticalFeatures': ['Q146786'],
'claims': {},
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'NOUNS'}},
'grammaticalFeatures': ['Q146786'],
'claims': {},
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'nounS'}},
'grammaticalFeatures': ['Q146786'],
'claims': {},
},
],
'lemmas': {'en': {'language': 'en', 'value': 'noun'}},
'language': 'Q1860',
'lexicalCategory': 'Q1084',
'claims': {},
}
def test_build_lexeme_with_statements_for_existing_lexeme(monkeypatch):
p5185 = [
{
'mainsnak': {
'snaktype': 'value',
'property': 'P5185',
'datatype': 'wikibase-item',
'datavalue': {
'type': 'wikibase-entityid',
'value': {
'entity-type': 'item',
'id': 'Q499327',
},
},
},
'type': 'statement',
'rank': 'normal',
}
]
p31 = [
{
'mainsnak': {
'snaktype': 'value',
'property': 'P31',
'datatype': 'wikibase-item',
'datavalue': {
'type': 'wikibase-entityid',
'value': {
'entity-type': 'item',
'id': 'Q604984',
},
},
},
'type': 'statement',
'rank': 'normal',
}
]
monkeypatch.setattr(lexeme_forms, 'get_lexeme_data', lambda lexeme_id, wiki: {
'language': 'Q1860',
'lexicalCategory': 'Q1084',
'claims': {
'P5185': p5185,
},
})
template = {
'language_item_id': 'Q1860',
'language_code': 'en',
'lexical_category_item_id': 'Q1084',
'forms': [
{
'grammatical_features_item_ids': ['Q110786'],
'statements': 'singular test statements',
},
{
'grammatical_features_item_ids': ['Q146786'],
'statements': 'plural test statements',
},
],
'statements': {
'P5185': p5185,
'P31': p31,
},
}
form_data = werkzeug.datastructures.ImmutableMultiDict([('lexeme_id', 'L123'), ('form_representation', 'noun'), ('form_representation', 'nouns')])
lexeme_data = lexeme_forms.build_lexeme(template, form_data)
assert lexeme_data == {
'id': 'L123',
'type': 'lexeme',
'forms': [
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'noun'}},
'grammaticalFeatures': ['Q110786'],
'claims': 'singular test statements',
},
{
'add': '',
'representations': {'en': {'language': 'en', 'value': 'nouns'}},
'grammaticalFeatures': ['Q146786'],
'claims': 'plural test statements',
},
],
'claims': {
'P31': p31,
},
}
def test_build_summary_localhost():
template = {
'@template_name': 'foo',
}
form_data = {}
with lexeme_forms.app.test_request_context(base_url='http://localhost/'):
summary = lexeme_forms.build_summary(template, form_data)
assert summary == 'foo'
def test_build_summary_internet():
template = {
'@template_name': 'foo',
}
form_data = {}
with lexeme_forms.app.test_request_context(base_url='https://example.com/lexeme-forms/'):
summary = lexeme_forms.build_summary(template, form_data)
assert summary == 'foo'
def test_build_summary_toolforge_lexeme_forms():
template = {
'@template_name': 'foo',
}
form_data = {}
with lexeme_forms.app.test_request_context(base_url='https://lexeme-forms.toolforge.org/'):
summary = lexeme_forms.build_summary(template, form_data)
assert summary == '[[toolforge:lexeme-forms/template/foo/|foo]]'
def test_build_summary_toolforge_other():
template = {
'@template_name': 'foo',
}
form_data = {}
with lexeme_forms.app.test_request_context(base_url='https://other.toolforge.org/'):
summary = lexeme_forms.build_summary(template, form_data)
assert summary == '[[toolforge:other/template/foo/|foo]]'
def test_build_summary_generated_via():
template = {
'@template_name': 'foo',
}
form_data = {
'generated_via': '[[toolforge:other/bar|other tool, bar]]'
}
with lexeme_forms.app.test_request_context(base_url='https://lexeme-forms.toolforge.org/'):
summary = lexeme_forms.build_summary(template, form_data)
assert summary == '[[toolforge:lexeme-forms/template/foo/|foo]], generated via [[toolforge:other/bar|other tool, bar]]'
@pytest.mark.parametrize('uri, hash, expected', [
('https://example.com/', None, 'https://example.com/'),
('https://example.com/', 'abc', 'https://example.com/#abc'),
])
def test_add_hash_to_uri(uri, hash, expected):
assert lexeme_forms.add_hash_to_uri(uri, hash) == expected
def test_get_all_templates_api():
with lexeme_forms.app.test_client() as client:
response = client.get('/api/v1/template/')
assert response.status_code == 200
assert response.content_type == 'application/json'
for template in json.loads(response.get_data(as_text=True)).values():
assert isinstance(template, (str, list)) or '@attribution' in template
def test_get_template_api_exists():
with lexeme_forms.app.test_client() as client:
response = client.get('/api/v1/template/german-noun-feminine')
assert response.status_code == 200
assert response.content_type == 'application/json'
template = json.loads(response.get_data(as_text=True))
assert '@attribution' in template
def test_get_template_api_redirect():
with lexeme_forms.app.test_client() as client:
response = client.get('/api/v1/template/dutch-feminine-noun')
assert response.status_code == 307
assert response.headers['location'].endswith('/api/v1/template/dutch-noun-feminine')
def test_get_template_api_missing():
with lexeme_forms.app.test_client() as client:
response = client.get('/api/v1/template/german-noun')
assert response.status_code == 404
# we don’t say that this is JSON,
# but for the benefit of clients who try to deserialize the response without checking the headers,
# we still want to reply with valid JSON
json.loads(response.get_data(as_text=True))
# the previous statement should not have thrown an exception
def test_update_lexeme_add_dwarves_dwarrows():
lexeme_data = {
'lemmas': {'en': {'language': 'en', 'value': 'dwarf'}},
'forms': [
{'id': 'L22936-F1', 'representations': {'en': {'language': 'en', 'value': 'dwarf'}}, 'grammaticalFeatures': ['Q110786']},
{'id': 'L22936-F2', 'representations': {'en': {'language': 'en', 'value': 'dwarfs'}}, 'grammaticalFeatures': ['Q146786']},
],
}
template = copy.deepcopy(templates_without_redirects['english-noun'])
template['lexeme_revision'] = 123
template['forms'][0]['lexeme_forms'] = [lexeme_data['forms'][0]]
template['forms'][1]['lexeme_forms'] = [lexeme_data['forms'][1]]
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'dwarf'), ('form_representation', 'dwarfs/dwarves/dwarrows')])
updated_lexeme_data = lexeme_forms.update_lexeme(lexeme_data, template, form_data, 'en')
assert updated_lexeme_data == {
'lemmas': {'en': {'language': 'en', 'value': 'dwarf'}},
'forms': [
{'id': 'L22936-F1', 'representations': {'en': {'language': 'en', 'value': 'dwarf'}}, 'grammaticalFeatures': ['Q110786']},
{'id': 'L22936-F2', 'representations': {'en': {'language': 'en', 'value': 'dwarfs'}}, 'grammaticalFeatures': ['Q146786']},
{'add': '', 'representations': {'en': {'language': 'en', 'value': 'dwarves'}}, 'grammaticalFeatures': ['Q146786'], 'claims': {}},
{'add': '', 'representations': {'en': {'language': 'en', 'value': 'dwarrows'}}, 'grammaticalFeatures': ['Q146786'], 'claims': {}},
],
'base_revision_id': 123,
}
def test_update_lexeme_match_forms():
lexeme_data = {
'lemmas': {'en': {'language': 'en', 'value': 'dwarf'}},
'forms': [
{'id': 'L22936-F1', 'representations': {'en': {'language': 'en', 'value': 'dwarf'}}, 'grammaticalFeatures': []},
{'id': 'L22936-F2', 'representations': {'en': {'language': 'en', 'value': 'dwarfs'}}, 'grammaticalFeatures': []},
{'id': 'L22936-F3', 'representations': {'en': {'language': 'en', 'value': 'dwarves'}}, 'grammaticalFeatures': []},
{'id': 'L22936-F4', 'representations': {'en': {'language': 'en', 'value': 'dwarrows'}}, 'grammaticalFeatures': []},
],
}
template = copy.deepcopy(templates_without_redirects['english-noun'])
template['lexeme_revision'] = 123
template['unmatched_lexeme_forms'] = lexeme_data['forms'][:]
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'L22936-F1'), ('form_representation', 'L22936-F2/L22936-F3/L22936-F4')])
updated_lexeme_data = lexeme_forms.update_lexeme(lexeme_data, template, form_data, 'en')
assert updated_lexeme_data == {
'lemmas': {'en': {'language': 'en', 'value': 'dwarf'}},
'forms': [
{'id': 'L22936-F1', 'representations': {'en': {'language': 'en', 'value': 'dwarf'}}, 'grammaticalFeatures': ['Q110786']},
{'id': 'L22936-F2', 'representations': {'en': {'language': 'en', 'value': 'dwarfs'}}, 'grammaticalFeatures': ['Q146786']},
{'id': 'L22936-F3', 'representations': {'en': {'language': 'en', 'value': 'dwarves'}}, 'grammaticalFeatures': ['Q146786']},
{'id': 'L22936-F4', 'representations': {'en': {'language': 'en', 'value': 'dwarrows'}}, 'grammaticalFeatures': ['Q146786']},
],
'base_revision_id': 123,
}
def test_update_lexeme_match_forms_optional_features():
lexeme_data = {
'lemmas': {'de': {'language': 'de', 'value': 'Berlin'}},
'forms': [
{'id': 'L297059-F1', 'representations': {'de': {'language': 'de', 'value': 'Berlin'}}, 'grammaticalFeatures': ['Q131105']},
{'id': 'L297059-F2', 'representations': {'de': {'language': 'de', 'value': 'Berlins'}}, 'grammaticalFeatures': ['Q146233']},
{'id': 'L297059-F3', 'representations': {'de': {'language': 'de', 'value': 'Berlin'}}, 'grammaticalFeatures': ['Q145599']},
{'id': 'L297059-F4', 'representations': {'de': {'language': 'de', 'value': 'Berlin'}}, 'grammaticalFeatures': ['Q146078']},
],
}
template = copy.deepcopy(templates_without_redirects['german-noun-neuter-toponym'])
template['lexeme_revision'] = 123
template['forms'][0]['lexeme_forms'] = [lexeme_data['forms'][0]]
template['forms'][1]['lexeme_forms'] = [lexeme_data['forms'][1]]
template['forms'][2]['lexeme_forms'] = [lexeme_data['forms'][2]]
template['forms'][3]['lexeme_forms'] = [lexeme_data['forms'][3]]
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'Berlin'), ('form_representation', 'Berlins'), ('form_representation', 'Berlin'), ('form_representation', 'Berlin')])
updated_lexeme_data = lexeme_forms.update_lexeme(lexeme_data, template, form_data, 'de')
assert updated_lexeme_data == {
'lemmas': {'de': {'language': 'de', 'value': 'Berlin'}},
'forms': [
{'id': 'L297059-F1', 'representations': {'de': {'language': 'de', 'value': 'Berlin'}}, 'grammaticalFeatures': ['Q131105', 'Q110786']},
{'id': 'L297059-F2', 'representations': {'de': {'language': 'de', 'value': 'Berlins'}}, 'grammaticalFeatures': ['Q146233', 'Q110786']},
{'id': 'L297059-F3', 'representations': {'de': {'language': 'de', 'value': 'Berlin'}}, 'grammaticalFeatures': ['Q145599', 'Q110786']},
{'id': 'L297059-F4', 'representations': {'de': {'language': 'de', 'value': 'Berlin'}}, 'grammaticalFeatures': ['Q146078', 'Q110786']},
],
'base_revision_id': 123,
}
def test_update_lexeme_edit_lemma():
lexeme_data = {
'lemmas': {'en': {'language': 'en', 'value': 'fuschia'}},
'forms': [
{'id': 'L3280-F1', 'representations': {'en': {'language': 'en', 'value': 'fuschia'}}, 'grammaticalFeatures': ['Q3482678']},
],
}
template = copy.deepcopy(templates_without_redirects['english-adjective'])
template['lexeme_revision'] = 123
template['forms'][0]['lexeme_forms'] = [lexeme_data['forms'][0]]
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'fuchsia')])
updated_lexeme_data = lexeme_forms.update_lexeme(lexeme_data, template, form_data, 'en')
assert updated_lexeme_data == {
'lemmas': {'en': {'language': 'en', 'value': 'fuchsia'}},
'forms': [
{'id': 'L3280-F1', 'representations': {'en': {'language': 'en', 'value': 'fuchsia'}}, 'grammaticalFeatures': ['Q3482678']},
],
'base_revision_id': 123,
}
def test_update_lexeme_edit_lemma_new_form():
lexeme_data = {
'lemmas': {'en': {'language': 'en', 'value': 'fuschia'}},
'forms': [],
}
template = copy.deepcopy(templates_without_redirects['english-adjective'])
template['lexeme_revision'] = 123
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'fuchsia')])
updated_lexeme_data = lexeme_forms.update_lexeme(lexeme_data, template, form_data, 'en')
assert updated_lexeme_data == {
'lemmas': {'en': {'language': 'en', 'value': 'fuchsia'}},
'forms': [
{'add': '', 'claims': {}, 'representations': {'en': {'language': 'en', 'value': 'fuchsia'}}, 'grammaticalFeatures': ['Q3482678']},
],
'base_revision_id': 123,
}
def test_update_lexeme_edit_lemma_nonfirst_form():
lexeme_data = {
'lemmas': {'en': {'language': 'en', 'value': 'roofs'}},
'forms': [],
}
template = copy.deepcopy(templates_without_redirects['english-noun'])
template['forms'][1]['lemma'] = True
template['lexeme_revision'] = 123
form_data = werkzeug.datastructures.ImmutableMultiDict([('form_representation', 'roof'), ('form_representation', 'rooves')])
updated_lexeme_data = lexeme_forms.update_lexeme(lexeme_data, template, form_data, 'en')
assert updated_lexeme_data == {
'lemmas': {'en': {'language': 'en', 'value': 'rooves'}},
'forms': [
{'add': '', 'claims': {}, 'representations': {'en': {'language': 'en', 'value': 'roof'}}, 'grammaticalFeatures': ['Q110786']},
{'add': '', 'claims': {}, 'representations': {'en': {'language': 'en', 'value': 'rooves'}}, 'grammaticalFeatures': ['Q146786']},
],
'base_revision_id': 123,
}