forked from oppia/oppia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema_utils_test.py
1250 lines (1135 loc) · 46.6 KB
/
schema_utils_test.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
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for object schema definitions."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
import inspect
from core.domain import email_manager
from core.tests import test_utils
import feconf
import python_utils
import schema_utils
from typing import Any, Dict, List, Text, Tuple, Union # isort:skip # pylint: disable=unused-import
SCHEMA_KEY_ITEMS = schema_utils.SCHEMA_KEY_ITEMS
SCHEMA_KEY_LEN = schema_utils.SCHEMA_KEY_LEN
SCHEMA_KEY_PROPERTIES = schema_utils.SCHEMA_KEY_PROPERTIES
SCHEMA_KEY_TYPE = schema_utils.SCHEMA_KEY_TYPE
SCHEMA_KEY_POST_NORMALIZERS = schema_utils.SCHEMA_KEY_POST_NORMALIZERS
SCHEMA_KEY_CHOICES = schema_utils.SCHEMA_KEY_CHOICES
SCHEMA_KEY_NAME = schema_utils.SCHEMA_KEY_NAME
SCHEMA_KEY_SCHEMA = schema_utils.SCHEMA_KEY_SCHEMA
SCHEMA_KEY_OBJ_TYPE = schema_utils.SCHEMA_KEY_OBJ_TYPE
SCHEMA_KEY_VALIDATORS = schema_utils.SCHEMA_KEY_VALIDATORS
SCHEMA_KEY_DEFAULT_VALUE = schema_utils.SCHEMA_KEY_DEFAULT_VALUE
SCHEMA_KEY_VALIDATION_METHOD = schema_utils.SCHEMA_KEY_VALIDATION_METHOD
SCHEMA_KEY_OBJECT_CLASS = schema_utils.SCHEMA_KEY_OBJECT_CLASS
SCHEMA_KEY_DESCRIPTION = 'description'
SCHEMA_KEY_UI_CONFIG = 'ui_config'
# This key is used for 'type: custom' objects, as a way of indicating how
# default ui_config values defined in objects.py should be replaced. The value
# is a dictionary mapping the accessor of the object value to the ui_config.
# For example, for SubtitledHtml (defined as a dict), to replace the ui_config
# of the inner html schema, the accessor/key would be 'html'. Note that the
# existing ui_config is not replaced or deleted - the frontend needs to handle
# the override of the ui_config, usually in a custom object editor.
SCHEMA_KEY_REPLACEMENT_UI_CONFIG = 'replacement_ui_config'
# The following keys are always accepted as optional keys in any schema.
OPTIONAL_SCHEMA_KEYS = [
SCHEMA_KEY_CHOICES, SCHEMA_KEY_POST_NORMALIZERS, SCHEMA_KEY_UI_CONFIG,
SCHEMA_KEY_VALIDATORS, SCHEMA_KEY_DEFAULT_VALUE]
SCHEMA_TYPE_BOOL = schema_utils.SCHEMA_TYPE_BOOL
# 'Custom' objects undergo an entirely separate normalization process, defined
# in the relevant extensions/objects/models/objects.py class.
SCHEMA_TYPE_CUSTOM = schema_utils.SCHEMA_TYPE_CUSTOM
SCHEMA_TYPE_DICT = schema_utils.SCHEMA_TYPE_DICT
SCHEMA_TYPE_FLOAT = schema_utils.SCHEMA_TYPE_FLOAT
SCHEMA_TYPE_HTML = schema_utils.SCHEMA_TYPE_HTML
SCHEMA_TYPE_INT = schema_utils.SCHEMA_TYPE_INT
SCHEMA_TYPE_LIST = schema_utils.SCHEMA_TYPE_LIST
SCHEMA_TYPE_BASESTRING = schema_utils.SCHEMA_TYPE_BASESTRING
SCHEMA_TYPE_UNICODE = schema_utils.SCHEMA_TYPE_UNICODE
SCHEMA_TYPE_UNICODE_OR_NONE = schema_utils.SCHEMA_TYPE_UNICODE_OR_NONE
SCHEMA_TYPE_OBJECT_DICT = schema_utils.SCHEMA_TYPE_OBJECT_DICT
ALLOWED_SCHEMA_TYPES = [
SCHEMA_TYPE_BOOL, SCHEMA_TYPE_CUSTOM, SCHEMA_TYPE_DICT, SCHEMA_TYPE_FLOAT,
SCHEMA_TYPE_HTML, SCHEMA_TYPE_INT, SCHEMA_TYPE_LIST, SCHEMA_TYPE_BASESTRING,
SCHEMA_TYPE_UNICODE, SCHEMA_TYPE_UNICODE_OR_NONE, SCHEMA_TYPE_OBJECT_DICT]
ALLOWED_CUSTOM_OBJ_TYPES = [
'Filepath', 'LogicQuestion', 'MathExpressionContent', 'MusicPhrase',
'ParameterName', 'SanitizedUrl', 'Graph', 'ImageWithRegions',
'ListOfTabs', 'SkillSelector', 'SubtitledHtml', 'SubtitledUnicode',
'SvgFilename', 'CustomOskLetters']
# Schemas for the UI config for the various types. All of these configuration
# options are optional additions to the schema, and, if omitted, should not
# result in any errors.
# Note to developers: please keep this in sync with
# https://github.com/oppia/oppia/wiki/Schema-Based-Forms
UI_CONFIG_SPECS = {
SCHEMA_TYPE_BOOL: {},
SCHEMA_TYPE_DICT: {},
SCHEMA_TYPE_FLOAT: {},
SCHEMA_TYPE_HTML: {
'hide_complex_extensions': {
'type': SCHEMA_TYPE_BOOL,
},
'placeholder': {
'type': SCHEMA_TYPE_UNICODE,
}
},
SCHEMA_TYPE_INT: {},
SCHEMA_TYPE_LIST: {
'add_element_text': {
'type': SCHEMA_TYPE_UNICODE
}
},
SCHEMA_TYPE_UNICODE: {
'rows': {
'type': SCHEMA_TYPE_INT,
'validators': [{
'id': 'is_at_least',
'min_value': 1,
}]
},
'coding_mode': {
'type': SCHEMA_TYPE_UNICODE,
'choices': ['none', 'python', 'coffeescript'],
},
'placeholder': {
'type': SCHEMA_TYPE_UNICODE,
},
},
} # type: Dict[Text, Dict[Text, Any]]
# Schemas for validators for the various types.
VALIDATOR_SPECS = {
SCHEMA_TYPE_BOOL: {},
SCHEMA_TYPE_DICT: {},
SCHEMA_TYPE_FLOAT: {
'is_at_least': {
'min_value': {
'type': SCHEMA_TYPE_FLOAT
}
},
'is_at_most': {
'max_value': {
'type': SCHEMA_TYPE_FLOAT
}
},
},
SCHEMA_TYPE_HTML: {},
SCHEMA_TYPE_INT: {
'is_at_least': {
'min_value': {
'type': SCHEMA_TYPE_INT
}
},
'is_at_most': {
'max_value': {
'type': SCHEMA_TYPE_INT
}
},
},
SCHEMA_TYPE_LIST: {
'has_length_at_least': {
'min_value': {
'type': SCHEMA_TYPE_INT,
'validators': [{
'id': 'is_at_least',
'min_value': 1,
}],
}
},
'has_length_at_most': {
'max_value': {
'type': SCHEMA_TYPE_INT,
'validators': [{
'id': 'is_at_least',
'min_value': 1,
}],
}
},
'is_uniquified': {}
},
SCHEMA_TYPE_UNICODE: {
'matches_regex': {
'regex': {
'type': SCHEMA_TYPE_UNICODE,
'validators': [{
'id': 'is_regex',
}]
}
},
'is_nonempty': {},
'is_regex': {},
'is_valid_email': {},
'is_valid_user_id': {},
'is_valid_math_expression': {
'algebraic': {
'type': SCHEMA_TYPE_BOOL
}
},
'is_valid_algebraic_expression': {},
'is_valid_numeric_expression': {},
'is_valid_math_equation': {},
'is_supported_audio_language_code': {},
'is_url_fragment': {},
'has_length_at_most': {
'max_value': {
'type': SCHEMA_TYPE_INT
}
}
},
} # type: Dict[Text, Dict[Text, Any]]
def _validate_ui_config(obj_type, ui_config):
# type: (Text, Dict[Text, Any]) -> None
"""Validates the value of a UI configuration.
Args:
obj_type: str. UI config spec type.
ui_config: dict. The UI config that needs to be validated.
Raises:
AssertionError. The object fails to validate against the schema.
"""
reference_dict = UI_CONFIG_SPECS[obj_type]
assert set(ui_config.keys()) <= set(reference_dict.keys()), (
'Missing keys: %s, Extra keys: %s' % (
list(set(reference_dict.keys()) - set(ui_config.keys())),
list(set(ui_config.keys()) - set(reference_dict.keys()))))
for key, value in ui_config.items():
schema_utils.normalize_against_schema(
value, reference_dict[key])
def _validate_validator(obj_type, validator):
# type: (Text, Dict[Text, Any]) -> None
"""Validates the value of a 'validator' field.
Args:
obj_type: str. The type of the object.
validator: dict. The Specs that needs to be validated.
Raises:
AssertionError. The object fails to validate against the schema.
"""
reference_dict = VALIDATOR_SPECS[obj_type]
assert 'id' in validator, 'id is not present in validator'
assert validator['id'] in reference_dict, (
'%s is not present in reference_dict' % validator['id'])
customization_keys = list(validator.keys())
customization_keys.remove('id')
assert (
set(customization_keys) ==
set(reference_dict[validator['id']].keys())), (
'Missing keys: %s, Extra keys: %s' % (
list(
set(reference_dict[validator['id']].keys()) -
set(customization_keys)),
list(
set(customization_keys) -
set(reference_dict[validator['id']].keys()))))
for key in customization_keys:
value = validator[key]
schema = reference_dict[validator['id']][key]
try:
schema_utils.normalize_against_schema(value, schema)
except Exception as e:
raise AssertionError(e)
# Check that the id corresponds to a valid normalizer function.
validator_fn = schema_utils.get_validator(validator['id'])
assert set(inspect.getargspec(validator_fn).args) == set(
customization_keys + ['obj']), (
'Missing keys: %s, Extra keys: %s' % (
list(
set(customization_keys + ['obj']) -
set(inspect.getargspec(validator_fn).args)),
list(
set(inspect.getargspec(validator_fn).args) -
set(customization_keys + ['obj']))))
def _validate_dict_keys(dict_to_check, required_keys, optional_keys):
# type: (Dict[Text, Any], List[Text], List[Text]) -> None
"""Checks that all of the required keys, and possibly some of the optional
keys, are in the given dict.
Args:
dict_to_check: dict. The dict which needs to be validated.
required_keys: list. Keys which are required to be in the dictionary.
optional_keys: list. Keys which are optional in the dictionary.
Raises:
AssertionError. The dict is missing required keys.
AssertionError. The dict contains extra keys.
"""
assert set(required_keys) <= set(dict_to_check.keys()), (
'Missing keys: %s' % dict_to_check)
assert set(dict_to_check.keys()) <= set(required_keys + optional_keys), (
'Extra keys: %s' % dict_to_check)
def validate_schema(schema):
# type: (Dict[Text, Any]) -> None
"""Validates a schema.
This is meant to be a utility function that should be used by tests to
ensure that all schema definitions in the codebase are valid.
Each schema is a dict with at least a key called 'type'. The 'type' can
take one of the SCHEMA_TYPE_* values declared above. In addition, there
may be additional keys for specific types:
- 'list' requires an additional 'items' property, which specifies the type
of the elements in the list. It also allows for an optional 'len'
property which specifies the len of the list.
- 'dict' requires an additional 'properties' property, which specifies the
names of the keys in the dict, and schema definitions for their values.
- 'object_dict' requires any of the one additional schema keys either
'validation_method' or 'object_class'.
validation_method, takes the method which is written in
domain_obejcts_vaildator.
object_class, takes a domain class as its value.
There may also be an optional 'post_normalizers' key whose value is a list
of normalizers.
Args:
schema: dict. The schema that needs to be validated.
Raises:
AssertionError. The schema is not valid.
"""
assert isinstance(schema, dict), ('Expected dict, got %s' % schema)
assert SCHEMA_KEY_TYPE in schema, (
'%s is not present in schema key types' % SCHEMA_KEY_TYPE)
assert schema[SCHEMA_KEY_TYPE] in ALLOWED_SCHEMA_TYPES, (
'%s is not an allowed schema type' % schema[SCHEMA_KEY_TYPE])
if schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_CUSTOM:
_validate_dict_keys(
schema,
[SCHEMA_KEY_TYPE, SCHEMA_KEY_OBJ_TYPE],
[SCHEMA_KEY_REPLACEMENT_UI_CONFIG])
assert schema[SCHEMA_KEY_OBJ_TYPE] in ALLOWED_CUSTOM_OBJ_TYPES, schema
elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_LIST:
_validate_dict_keys(
schema,
[SCHEMA_KEY_ITEMS, SCHEMA_KEY_TYPE],
OPTIONAL_SCHEMA_KEYS + [SCHEMA_KEY_LEN])
validate_schema(schema[SCHEMA_KEY_ITEMS])
if SCHEMA_KEY_LEN in schema:
assert isinstance(schema[SCHEMA_KEY_LEN], int), (
'Expected int, got %s' % schema[SCHEMA_KEY_LEN])
assert schema[SCHEMA_KEY_LEN] > 0, (
'Expected length greater than 0, got %s' % (
schema[SCHEMA_KEY_LEN]))
elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_DICT:
_validate_dict_keys(
schema,
[SCHEMA_KEY_PROPERTIES, SCHEMA_KEY_TYPE],
OPTIONAL_SCHEMA_KEYS)
assert isinstance(schema[SCHEMA_KEY_PROPERTIES], list), (
'Expected list, got %s' % schema[SCHEMA_KEY_LEN])
for prop in schema[SCHEMA_KEY_PROPERTIES]:
_validate_dict_keys(
prop,
[SCHEMA_KEY_NAME, SCHEMA_KEY_SCHEMA],
[SCHEMA_KEY_DESCRIPTION])
assert isinstance(prop[SCHEMA_KEY_NAME], python_utils.BASESTRING), (
'Expected %s, got %s' % (
python_utils.BASESTRING, prop[SCHEMA_KEY_NAME]))
validate_schema(prop[SCHEMA_KEY_SCHEMA])
if SCHEMA_KEY_DESCRIPTION in prop:
assert isinstance(
prop[SCHEMA_KEY_DESCRIPTION], python_utils.BASESTRING), (
'Expected %s, got %s' % (
python_utils.BASESTRING,
prop[SCHEMA_KEY_DESCRIPTION]))
elif schema[SCHEMA_KEY_TYPE] == SCHEMA_TYPE_OBJECT_DICT:
_validate_dict_keys(
schema,
[SCHEMA_KEY_TYPE],
[SCHEMA_KEY_VALIDATION_METHOD, SCHEMA_KEY_OBJECT_CLASS] +
OPTIONAL_SCHEMA_KEYS
)
else:
_validate_dict_keys(schema, [SCHEMA_KEY_TYPE], OPTIONAL_SCHEMA_KEYS)
if SCHEMA_KEY_UI_CONFIG in schema:
_validate_ui_config(
schema[SCHEMA_KEY_TYPE], schema[SCHEMA_KEY_UI_CONFIG])
if SCHEMA_KEY_POST_NORMALIZERS in schema:
assert isinstance(schema[SCHEMA_KEY_POST_NORMALIZERS], list), (
'Expected list, got %s' % schema[SCHEMA_KEY_POST_NORMALIZERS])
for post_normalizer in schema[SCHEMA_KEY_POST_NORMALIZERS]:
assert isinstance(post_normalizer, dict), (
'Expected dict, got %s' % post_normalizer)
assert 'id' in post_normalizer, (
'id is not present in %s' % post_normalizer)
# Check that the id corresponds to a valid normalizer function.
schema_utils.Normalizers.get(post_normalizer['id'])
# TODO(sll): Check the arguments too.
if SCHEMA_KEY_VALIDATORS in schema:
assert isinstance(schema[SCHEMA_KEY_VALIDATORS], list), (
'Expected list, got %s' % schema[SCHEMA_KEY_VALIDATORS])
for validator in schema[SCHEMA_KEY_VALIDATORS]:
assert isinstance(validator, dict), (
'Expected dict, got %s' % schema[SCHEMA_KEY_VALIDATORS])
assert 'id' in validator, (
'id is not present in %s' % validator)
_validate_validator(schema[SCHEMA_KEY_TYPE], validator)
class SchemaValidationUnitTests(test_utils.GenericTestBase):
"""Test validation of schemas."""
GLOBAL_VALIDATORS_SCHEMA = {
'type': schema_utils.SCHEMA_TYPE_DICT,
'properties': [{
'name': 'unicodeListProp',
'schema': {
'type': schema_utils.SCHEMA_TYPE_LIST,
'items': {
'type': schema_utils.SCHEMA_TYPE_UNICODE
}
},
}, {
'name': 'unicodeProp',
'schema': {
'type': schema_utils.SCHEMA_TYPE_UNICODE
},
}]
}
GLOBAL_VALIDATORS = [{
'id': 'does_not_contain_email'
}] # List[Dict[Text, Any]]
def arbitary_method(self, obj):
# type: (Dict[Any, Any]) -> None
"""Only required for testing.
Args:
obj: dict. Argument which needs to be validated.
"""
if 'any_arg' not in obj:
raise Exception('Missing \'any_arg\'.')
def test_schemas_are_correctly_validated(self):
# type: () -> None
"""Test validation of schemas."""
invalid_schemas_with_error_messages = [
([
'type'
], r'Expected dict, got \[u\'type\'\]'),
({
'type': 'invalid'
}, 'invalid is not an allowed schema type'),
({
'type': 'dict',
}, 'Missing keys: {u\'type\': u\'dict\'}'),
({
'type': 'list',
'items': {}
}, 'type is not present in schema key types'),
({
'type': 'list',
'items': {
'type': 'unicode'
},
'len': -1
}, 'Expected length greater than 0, got -1'),
({
'type': 'list',
'items': {
'type': 'unicode'
},
'len': 0
}, 'Expected length greater than 0, got 0'),
({
'type': 'list',
'items': {
'type': 'unicode'
},
'validators': [{
'id': 'has_length_at_most',
'max_value': 0
}]
},
r'Validation failed: is_at_least \({u\'min_value\': 1}\) for '
r'object 0'),
({
'type': 'dict',
'items': {
'type': 'float'
}
},
r'Missing keys: {u\'items\': {u\'type\': u\'float\'}, '
r'u\'type\': u\'dict\'}'),
({
'type': 'dict',
'properties': {
123: {
'type': 'unicode'
}
}
}, 'u\'len\''),
({
'type': 'unicode',
'validators': [{
'id': 'fake_validator',
}]
}, 'fake_validator is not present in reference_dict'),
({
'type': 'unicode',
'validators': [{
'id': 'is_nonempty',
'fake_arg': 'unused_value',
}]
}, r'Missing keys: \[\], Extra keys: \[u\'fake_arg\'\]'),
({
'type': 'unicode',
'validators': [{
'id': 'matches_regex',
}]
}, r'Missing keys: \[u\'regex\'\], Extra keys: \[\]'),
({
'type': 'float',
'validators': [{
'id': 'is_at_least',
'min_value': 'value_of_wrong_type',
}]
}, 'Could not convert unicode to float: value_of_wrong_type'),
({
'type': 'unicode',
'ui_config': {
'rows': -1,
}
},
r'Validation failed: is_at_least \({u\'min_value\': 1}\) for '
r'object -1'),
({
'type': 'unicode',
'ui_config': {
'coding_mode': 'invalid_mode',
}
},
r'Received invalid_mode which is not in the allowed range of '
r'choices: \[u\'none\', u\'python\', u\'coffeescript\'\]')]
valid_schemas = [{
'type': 'float'
}, {
'type': 'bool'
}, {
'type': 'dict',
'properties': [{
'name': 'str_property',
'schema': {
'type': 'unicode'
}
}]
}, {
'type': 'list',
'items': {
'type': 'list',
'items': {
'type': 'list',
'items': {
'type': 'bool'
},
'len': 100
}
}
}, {
'type': 'list',
'items': {
'type': 'unicode'
},
'validators': [{
'id': 'has_length_at_most',
'max_value': 3
}]
}, {
'type': 'float',
'validators': [{
'id': 'is_at_least',
'min_value': 3.0,
}]
}, {
'type': 'unicode',
'ui_config': {
'rows': 5,
}
}, {
'type': 'unicode',
'ui_config': {
'coding_mode': 'python',
}
}, {
'type': 'object_dict',
'validation_method': self.arbitary_method
}] # type: List[Dict[Text, Any]]
for schema in valid_schemas:
validate_schema(schema)
for schemas, error_msg in invalid_schemas_with_error_messages:
with self.assertRaisesRegexp((AssertionError, KeyError), error_msg): # type: ignore[no-untyped-call]
validate_schema(schemas) # type: ignore[arg-type]
def test_normalize_against_schema_raises_exception(self):
# type: () -> None
"""Tests if normalize against schema raises exception
for invalid key.
"""
with self.assertRaisesRegexp(Exception, 'Invalid schema type: invalid'): # type: ignore[no-untyped-call]
schema = {SCHEMA_KEY_TYPE: 'invalid'}
schema_utils.normalize_against_schema('obj', schema)
def test_is_nonempty_validator(self):
# type: () -> None
"""Tests if static method is_nonempty returns true iff obj
is not an empty str.
"""
is_nonempty = schema_utils.get_validator('is_nonempty')
self.assertTrue(is_nonempty('non-empty string'))
self.assertTrue(is_nonempty(' '))
self.assertTrue(is_nonempty(' '))
self.assertFalse(is_nonempty(''))
def test_is_at_most_validator(self):
# type: () -> None
"""Tests if static method is_at_most returns true iff obj
is at most a value.
"""
is_at_most = schema_utils.get_validator('is_at_most')
self.assertTrue(is_at_most(2, 3))
self.assertTrue(is_at_most(2, 2)) # boundary
self.assertFalse(is_at_most(2, 1))
def test_has_length_at_least_validator(self):
# type: () -> None
"""Tests if static method has_length_at_least returns true iff
given list has length of at least the given value.
"""
has_len_at_least = schema_utils.get_validator('has_length_at_least')
self.assertTrue(has_len_at_least(['elem'], 0))
self.assertTrue(has_len_at_least(['elem'], 1)) # boundary
self.assertFalse(has_len_at_least(['elem'], 2))
def test_get_raises_invalid_validator_id(self):
# type: () -> None
"""Tests if class method 'get' in _Validator raises exception
for invalid validator id.
"""
with self.assertRaisesRegexp( # type: ignore[no-untyped-call]
Exception,
'Invalid validator id: some invalid validator method name'):
schema_utils.get_validator('some invalid validator method name')
def test_is_valid_algebraic_expression_validator(self):
# type: () -> None
"""Tests for the is_valid_algebraic_expression static method with
algebraic type.
"""
is_valid_algebraic_expression = schema_utils.get_validator(
'is_valid_algebraic_expression')
self.assertTrue(is_valid_algebraic_expression('a+b*2'))
self.assertFalse(is_valid_algebraic_expression('3+4/2'))
def test_is_valid_numeric_expression_validator(self):
# type: () -> None
"""Tests for the is_valid_numeric_expression static method with
numeric type.
"""
is_valid_numeric_expression = schema_utils.get_validator(
'is_valid_numeric_expression')
self.assertFalse(is_valid_numeric_expression('a+b*2'))
self.assertTrue(is_valid_numeric_expression('3+4/2'))
def test_is_valid_math_equation_validator(self):
# type: () -> None
"""Tests for the is_valid_math_equation static method."""
is_valid_math_equation = schema_utils.get_validator(
'is_valid_math_equation')
self.assertTrue(is_valid_math_equation('a+b=c'))
self.assertTrue(is_valid_math_equation('x^2+y^2=z^2'))
self.assertTrue(is_valid_math_equation('y = m*x + b'))
self.assertTrue(is_valid_math_equation('alpha^a + beta^b = gamma^(-c)'))
self.assertTrue(is_valid_math_equation('a+b=0'))
self.assertTrue(is_valid_math_equation('0=a+b'))
self.assertTrue(is_valid_math_equation('(a/b)+c=(4^3)*a'))
self.assertTrue(is_valid_math_equation('2^alpha-(-3) = 3'))
self.assertTrue(is_valid_math_equation('(a+b)^2 = a^2 + b^2 + 2*a*b'))
self.assertTrue(is_valid_math_equation('(a+b)^2 = a^2 + b^2 + 2ab'))
self.assertTrue(is_valid_math_equation('x/a + y/b = 1'))
self.assertTrue(is_valid_math_equation('3 = -5 + pi^x'))
self.assertTrue(is_valid_math_equation('0.4 + 0.5 = alpha * 4'))
self.assertTrue(is_valid_math_equation('sqrt(a+b)=c - gamma/2.4'))
self.assertTrue(is_valid_math_equation('abs(35 - x) = 22.3'))
self.assertFalse(is_valid_math_equation('3 -= 2/a'))
self.assertFalse(is_valid_math_equation('3 == 2/a'))
self.assertFalse(is_valid_math_equation('x + y = '))
self.assertFalse(is_valid_math_equation('(a+b = 0)'))
self.assertFalse(is_valid_math_equation('pi = 3.1415'))
self.assertFalse(is_valid_math_equation('a+b=0=a-b'))
self.assertFalse(is_valid_math_equation('alpha - beta/c'))
self.assertFalse(is_valid_math_equation('2^alpha-(-3*) = 3'))
self.assertFalse(is_valid_math_equation('a~b = 0'))
self.assertFalse(is_valid_math_equation('a+b<=0'))
self.assertFalse(is_valid_math_equation('a+b>=0'))
self.assertFalse(is_valid_math_equation('a+b<0'))
self.assertFalse(is_valid_math_equation('a+b>0'))
self.assertFalse(is_valid_math_equation('5+3=8'))
self.assertFalse(is_valid_math_equation('(a+(b)=0'))
self.assertFalse(is_valid_math_equation('a+b=c:)'))
def test_is_supported_audio_language_code(self):
# type: () -> None
is_supported_audio_language_code = schema_utils.get_validator(
'is_supported_audio_language_code')
self.assertTrue(is_supported_audio_language_code('en'))
self.assertTrue(is_supported_audio_language_code('fr'))
self.assertTrue(is_supported_audio_language_code('de'))
self.assertFalse(is_supported_audio_language_code(''))
self.assertFalse(is_supported_audio_language_code('zz'))
self.assertFalse(is_supported_audio_language_code('test'))
def test_is_url_fragment(self):
# type: () -> None
validate_url_fragment = schema_utils.get_validator(
'is_url_fragment')
self.assertTrue(validate_url_fragment('math'))
self.assertTrue(validate_url_fragment('computer-science'))
self.assertTrue(validate_url_fragment('bio-tech'))
self.assertFalse(validate_url_fragment(''))
self.assertFalse(validate_url_fragment('Abc'))
self.assertFalse(validate_url_fragment('!@#$%^&*()_+='))
def test_global_validators_raise_exception_when_error_in_dict(self):
# type: () -> None
with self.assertRaisesRegexp( # type: ignore[no-untyped-call]
AssertionError,
r'^Validation failed: does_not_contain_email .* email@email.com$'
):
obj = {
'unicodeListProp': ['not email', 'not email 2'],
'unicodeProp': 'email@email.com'
}
schema_utils.normalize_against_schema(
obj, self.GLOBAL_VALIDATORS_SCHEMA,
global_validators=self.GLOBAL_VALIDATORS
)
def test_global_validators_raise_exception_when_error_in_list(self):
# type: () -> None
with self.assertRaisesRegexp( # type: ignore[no-untyped-call]
AssertionError,
r'^Validation failed: does_not_contain_email .* email2@email.com$'
):
obj = {
'unicodeListProp': ['email2@email.com', 'not email 2'],
'unicodeProp': 'not email'
}
schema_utils.normalize_against_schema(
obj, self.GLOBAL_VALIDATORS_SCHEMA,
global_validators=self.GLOBAL_VALIDATORS
)
def test_global_validators_pass_when_no_error(self):
# type: () -> None
obj = {
'unicodeListProp': ['not email', 'not email 2'],
'unicodeProp': 'not email'
}
normalized_obj = schema_utils.normalize_against_schema(
obj, self.GLOBAL_VALIDATORS_SCHEMA,
global_validators=self.GLOBAL_VALIDATORS
)
self.assertEqual(obj, normalized_obj)
class SchemaNormalizationUnitTests(test_utils.GenericTestBase):
"""Test schema-based normalization of objects."""
def check_normalization(
self, schema, mappings, invalid_items_with_error_messages):
# type: (Dict[Text, Any], List[Tuple[Any, Any]], List[Tuple[Any, Text]]) -> None
"""Validates the schema and tests that values are normalized correctly.
Args:
schema: dict. The schema to normalize the value
against. Each schema is a dict with at least a key called
'type'. The 'type' can take one of the SCHEMA_TYPE_* values
declared above.
mappings: list(tuple). A list of 2-element tuples.
The first element of each item is expected to be normalized to
the second.
invalid_items_with_error_messages: list(tuple(*, str)). A list of
values with their corresponding messages. Each value is expected
to raise an AssertionError when normalized.
"""
validate_schema(schema)
for raw_value, expected_value in mappings:
self.assertEqual(
schema_utils.normalize_against_schema(raw_value, schema),
expected_value)
for value, error_msg in invalid_items_with_error_messages:
with self.assertRaisesRegexp(Exception, error_msg): # type: ignore[no-untyped-call]
schema_utils.normalize_against_schema(value, schema)
def test_float_schema(self):
# type: () -> None
schema = {
'type': schema_utils.SCHEMA_TYPE_FLOAT,
}
mappings = [(1.2, 1.2), (3, 3.0), (-1, -1.0), ('1', 1.0)]
invalid_values_with_error_messages = [
([13], r'Could not convert list to float: \[13\]'),
('abc', 'Could not convert unicode to float: abc'),
(None, 'Could not convert NoneType to float: None')]
self.check_normalization(
schema, mappings, invalid_values_with_error_messages)
def test_int_schema(self):
# type: () -> None
schema = {
'type': schema_utils.SCHEMA_TYPE_INT,
}
mappings = [(1.2, 1), (3.7, 3), (-1, -1), ('1', 1)]
invalid_values_with_error_messages = [
([13], r'Could not convert list to int: \[13\]'),
('abc', 'Could not convert unicode to int: abc'),
(None, 'Could not convert NoneType to int: None')]
self.check_normalization(
schema, mappings, invalid_values_with_error_messages)
def test_unicode_or_none_schema(self):
# type: () -> None
schema = {
'type': schema_utils.SCHEMA_TYPE_UNICODE_OR_NONE,
}
mappings = [('a', 'a'), ('', ''), (b'bytes', 'bytes'), (None, None)]
invalid_values_with_error_messages = [
([], r'Expected unicode string or None, received'),
] # type: List[Tuple[List[Any], Text]]
self.check_normalization(
schema, mappings, invalid_values_with_error_messages)
def test_list_schema_with_len(self):
# type: () -> None
schema = {
'type': schema_utils.SCHEMA_TYPE_LIST,
'items': {
'type': schema_utils.SCHEMA_TYPE_UNICODE,
},
'len': 2,
}
mappings = [
(['a', 'b'], ['a', 'b']),
(['abc', ''], ['abc', '']),
(['adaA13', '13'], ['adaA13', '13'])]
invalid_values_with_error_messages = [
(['1', 13], 'Expected unicode string, received 13'),
({'a': 'b'}, r'Expected list, received {u\'a\': u\'b\'}'),
({}, 'Expected list, received {}'),
(None, 'Expected list, received None'),
(123, 'Expected list, received 123'),
('abc', 'Expected list, received abc'),
(['c'], 'Expected length of 2 got 1'),
([], 'Expected length of 2 got 0')]
self.check_normalization(
schema, mappings, invalid_values_with_error_messages)
def test_html_schema(self):
# type: () -> None
"""Tests for valid html schema, an html string. Note that
html.cleaner() is called in normalize_against_schema.
"""
schema = {
'type': schema_utils.SCHEMA_TYPE_HTML,
}
mappings = [
('<script></script>', ''),
(b'<script></script>', ''),
(
'<a class="webLink" href="https'
'://www.oppia.com/"><img src="images/oppia.png"></a>',
'<a href="https://www.oppia.com/"></a>')]
invalid_values_with_error_messages = [
(
['<script></script>', '<script></script>'],
r'Expected unicode HTML string, received \[u\'<script></script>'
r'\', u\'<script></script>\'\]')]
self.check_normalization(
schema, mappings, invalid_values_with_error_messages)
def test_schema_key_post_normalizers(self):
# type: () -> None
"""Test post normalizers in schema using basic html schema."""
schema_1 = {
'type': schema_utils.SCHEMA_TYPE_HTML,
'post_normalizers': [
{'id': 'normalize_spaces'}, # html strings with no extra spaces
]
}
obj_1 = 'a a'
normalize_obj_1 = schema_utils.normalize_against_schema(obj_1, schema_1)
self.assertEqual(u'a a', normalize_obj_1)
schema_2 = {
'type': schema_utils.SCHEMA_TYPE_HTML,
'post_normalizers': [
{'id': 'sanitize_url'}
]
}
obj_2 = 'http://www.oppia.org/splash/<script>'
normalize_obj_2 = schema_utils.normalize_against_schema(obj_2, schema_2)
self.assertEqual(u'http://www.oppia.org/splash/', normalize_obj_2)
def test_list_schema(self):
# type: () -> None
schema = {
'type': schema_utils.SCHEMA_TYPE_LIST,
'items': {
'type': schema_utils.SCHEMA_TYPE_UNICODE,
}
}
mappings = [
(['a', 'b'], ['a', 'b']),
(['c'], ['c']),
(['abc', ''], ['abc', '']),
([], []),
(['adaA13', '13'], ['adaA13', '13'])]
invalid_values_with_error_messages = [
(['1', 13], 'Expected unicode string, received 13'),
({'a': 'b'}, r'Expected list, received {u\'a\': u\'b\'}'),
({}, 'Expected list, received {}'),
(None, 'Expected list, received None'),
(123, 'Expected list, received 123'),
('abc', 'Expected list, received abc')]
self.check_normalization(
schema, mappings, invalid_values_with_error_messages)
def test_dict_schema(self):
# type: () -> None
schema = {
'type': schema_utils.SCHEMA_TYPE_DICT,
'properties': [{
'name': 'unicodeListProp',
'schema': {
'type': schema_utils.SCHEMA_TYPE_LIST,
'items': {
'type': schema_utils.SCHEMA_TYPE_UNICODE
}
},
}, {
'name': 'intProp',
'schema': {
'type': schema_utils.SCHEMA_TYPE_INT
},
}, {
'name': 'dictProp',
'schema': {
'type': schema_utils.SCHEMA_TYPE_DICT,
'properties': [{
'name': 'floatProp',
'schema': {
'type': schema_utils.SCHEMA_TYPE_FLOAT
}
}]
}
}]
}
mappings = [({
'unicodeListProp': [],
'intProp': 1,
'dictProp': {
'floatProp': 3
}
}, {
'unicodeListProp': [],
'intProp': 1,
'dictProp': {
'floatProp': 3.0
}
}), ({
'intProp': 10,
'unicodeListProp': ['abc', 'def'],
'dictProp': {
'floatProp': -1.0
}
}, {
'intProp': 10,