-
Notifications
You must be signed in to change notification settings - Fork 14
/
test_parameters.py
2301 lines (1985 loc) · 75.1 KB
/
test_parameters.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 os
import json
import datetime
from collections import OrderedDict
from random import shuffle
import pytest
import numpy as np
import marshmallow as ma
from paramtools import (
ParamToolsError,
ValidationError,
SparseValueObjectsException,
InconsistentLabelsException,
collision_list,
ParameterNameCollisionException,
register_custom_type,
Parameters,
Values,
Slice,
)
from paramtools.contrib import Bool_
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
@pytest.fixture
def defaults_spec_path():
return os.path.join(CURRENT_PATH, "defaults.json")
@pytest.fixture
def extend_ex_path():
return os.path.join(CURRENT_PATH, "extend_ex.json")
@pytest.fixture
def array_first_defaults(defaults_spec_path):
with open(defaults_spec_path) as f:
r = json.loads(f.read())
r.pop("float_list_param")
r.pop("simple_int_list_param")
r.pop("float_list_when_param")
r.pop("when_array_param")
return r
@pytest.fixture
def TestParams(defaults_spec_path):
class _TestParams(Parameters):
defaults = defaults_spec_path
return _TestParams
@pytest.fixture(scope="function")
def af_params(array_first_defaults):
class AFParams(Parameters):
defaults = array_first_defaults
_af_params = AFParams(
initial_state={"label0": "zero", "label1": 1}, array_first=True
)
return _af_params
def test_init(TestParams):
params = TestParams()
assert params
assert params._data
for param in params._data:
assert getattr(params, param)
assert params.label_grid
assert params.label_grid == params._stateless_label_grid
class TestSchema:
def test_empty_schema(self):
class Params(Parameters):
array_first = True
defaults = {
"hello_world": {
"title": "Hello, World!",
"description": "Simplest config possible.",
"type": "str",
"value": "hello world",
}
}
params = Params()
assert params.hello_world == "hello world"
assert params.label_grid == {}
def test_schema_just_labels(self):
class Params(Parameters):
array_first = True
defaults = {
"schema": {
"labels": {
"somelabel": {
"type": "int",
"validators": {"range": {"min": 0, "max": 2}},
}
}
},
"hello_world": {
"title": "Hello, World!",
"description": "Simplest config possible.",
"type": "str",
"value": "hello world",
},
}
params = Params()
assert params.hello_world == "hello world"
assert params.label_grid == {"somelabel": [0, 1, 2]}
def test_schema_just_additional_members(self):
class Params(Parameters):
array_first = True
defaults = {
"schema": {
"additional_members": {"additional": {"type": "str"}}
},
"hello_world": {
"title": "Hello, World!",
"description": "Simplest config possible.",
"additional": "I'm extra",
"type": "str",
"value": "hello world",
},
}
params = Params()
assert params.hello_world == "hello world"
assert params.label_grid == {}
def test_schema_not_dropped(self, defaults_spec_path):
with open(defaults_spec_path, "r") as f:
defaults_ = json.loads(f.read())
class TestParams(Parameters):
defaults = defaults_
TestParams()
assert defaults_["schema"]
def test_schema_with_errors(self):
class Params1(Parameters):
array_first = True
defaults = {
"schema": {
"additional_members": {"additional": {"type": 1234}}
}
}
with pytest.raises(ma.ValidationError):
Params1()
class Params2(Parameters):
array_first = True
defaults = {
"schema": {
"additional_members_123": {"additional": {"type": "str"}}
}
}
with pytest.raises(ma.ValidationError):
Params2()
def test_operators_spec(self):
class Params1(Parameters):
array_first = False
defaults = {
"schema": {
"labels": {
"mylabel": {
"type": "int",
"validators": {"range": {"min": 0, "max": 10}},
},
"somelabel": {
"type": "int",
"validators": {"range": {"min": 0, "max": 10}},
},
},
"operators": {
"array_first": False,
"label_to_extend": "somelabel",
},
}
}
params = Params1(array_first=True, label_to_extend="mylabel")
assert params.array_first
assert params.label_to_extend == "mylabel"
assert params.operators == {
"array_first": True,
"label_to_extend": "mylabel",
"uses_extend_func": False,
}
assert params.dump()["schema"]["operators"] == params.operators
Params1.array_first = True
params = Params1()
assert params.array_first
assert params.label_to_extend == "somelabel"
assert params.operators == {
"array_first": True,
"label_to_extend": "somelabel",
"uses_extend_func": False,
}
assert params.dump()["schema"]["operators"] == params.operators
class Params2(Parameters):
defaults = {"schema": {"operators": {"array_first": True}}}
params = Params2()
assert params.array_first
assert params.label_to_extend is None
assert params.operators == {
"array_first": True,
"label_to_extend": None,
"uses_extend_func": False,
}
assert params.dump()["schema"]["operators"] == params.operators
class Params3(Parameters):
array_first = True
label_to_extend = "hello"
defaults = {"schema": {"operators": {"array_first": True}}}
params = Params3(array_first=False, label_to_extend=None)
assert params.operators == {
"array_first": False,
"label_to_extend": None,
"uses_extend_func": False,
}
assert params.dump()["schema"]["operators"] == params.operators
params.array_first = True
assert params.dump()["schema"]["operators"] == params.operators
def test_when_schema(self):
class Params(Parameters):
defaults = {
"param": {
"title": "",
"description": "",
"type": "int",
"value": 0,
"validators": {
"when": {
"param": "default",
"is": {"less_than": 0, "greater_than": 1},
"then": {"range": {"min": 0}},
"otherwise": {"range": {"min": "default"}},
}
},
}
}
with pytest.raises(ma.ValidationError):
Params()
def test_custom_fields(self):
class Custom(ma.Schema):
hello = ma.fields.Boolean()
world = Bool_() # Tests data is serialized.
register_custom_type("custom_type", ma.fields.Nested(Custom()))
class Params(Parameters):
defaults = {
"schema": {
"labels": {"custom_label": {"type": "custom_type"}},
"additional_members": {"custom": {"type": "custom_type"}},
},
"param": {
"title": "",
"description": "",
"type": "int",
"value": [{"custom_label": {"hello": True}, "value": 0}],
"custom": {"hello": True, "world": True},
},
}
params = Params()
assert params
assert params._data["param"]["custom"] == {
"hello": True,
"world": True,
}
assert params.adjust(
{
"param": [
{
"custom_label": {"hello": True, "world": True},
"value": 1,
}
]
}
)
assert params.sel["param"].isel[:] == [
{"custom_label": {"hello": True}, "value": 0},
{"custom_label": {"hello": True, "world": True}, "value": 1},
]
class BadSpec(Parameters):
field_map = {"custom_type": ma.fields.Nested(Custom)}
defaults = {
"schema": {
"additional_members": {"custom": {"type": "custom_type"}}
},
"param": {
"title": "",
"description": "",
"type": "int",
"value": 0,
"custom": {"hello": 123, "world": "whoops"},
},
}
with pytest.raises(ma.ValidationError):
BadSpec()
class TestValues:
def test(self, TestParams, defaults_spec_path):
params = TestParams()
assert isinstance(params.sel["min_int_param"], Values)
assert isinstance(params.sel["min_int_param"]["label0"], Slice)
with pytest.raises(AttributeError):
params["min_int_param"]
class TestAccess:
def test_specification(self, TestParams, defaults_spec_path):
params = TestParams()
spec1 = params.specification()
with open(defaults_spec_path) as f:
exp = json.loads(f.read())
exp.pop("schema")
assert set(spec1.keys()) == set(exp.keys())
assert spec1["min_int_param"] == exp["min_int_param"]["value"]
def test_is_ordered(self, TestParams):
params = TestParams()
spec1 = params.specification()
assert isinstance(spec1, OrderedDict)
spec2 = params.specification(meta_data=True, serializable=True)
assert isinstance(spec2, OrderedDict)
def test_specification_query(self, TestParams):
params = TestParams()
spec1 = params.specification()
exp = {
"min_int_param": [{"label0": "one", "label1": 2, "value": 2}],
"max_int_param": [{"label0": "one", "label1": 2, "value": 4}],
}
spec2 = params.specification(label0="one")
# check that specification method got only the value item with label0="one"
assert spec2["min_int_param"] == exp["min_int_param"]
assert spec2["max_int_param"] == exp["max_int_param"]
# check that get method got only value item with label0="one"
params.set_state(label0="one")
assert params.min_int_param == exp["min_int_param"]
assert params.max_int_param == exp["max_int_param"]
# check that specification method gets other data, not containing a label0
# label.
for param, data in spec1.items():
if all("label0" not in val_item for val_item in data):
assert spec2[param] == data
params.delete({"str_choice_param": None})
assert "str_choice_param" not in params.specification()
assert "str_choice_param" in params.specification(include_empty=True)
def test_serializable(self, TestParams, defaults_spec_path):
params = TestParams()
assert json.dumps(params.specification(serializable=True))
assert json.dumps(
params.specification(serializable=True, meta_data=True)
)
spec = params.specification(serializable=True)
# Make sure "value" is removed when meta_data is False
for value in spec.values():
assert "value" not in value
with open(defaults_spec_path) as f:
exp = json.loads(f.read())
exp.pop("schema")
spec = params.specification(serializable=True, meta_data=True)
assert spec == params._defaults_schema.dump(
params._defaults_schema.load(exp)
)
def test_dump(self, TestParams, defaults_spec_path):
params1 = TestParams()
spec = params1.specification(serializable=True, meta_data=True)
schema = params1._schema
dumped = params1.dump()
assert dumped == {**spec, **{"schema": schema}}
class TestParams2(Parameters):
defaults = dumped
params2 = TestParams2()
assert params2.dump() == dumped
def test_dump_with_labels(self, TestParams, defaults_spec_path):
params1 = TestParams()
spec = params1.specification(
serializable=True,
include_empty=True,
meta_data=True,
label0="one",
sort_values=True,
)
schema = params1._schema
params1.set_state(label0="one")
dumped = params1.dump(sort_values=True)
assert dumped == {**spec, **{"schema": schema}}
class TestParams2(Parameters):
defaults = dumped
params2 = TestParams2()
params2.set_state(label0="one")
assert params2.dump() == dumped
def test_iterable(self, TestParams):
params = TestParams()
act = set([])
for param in params:
act.add(param)
assert set(params._data.keys()) == act
assert set(params._data.keys()) == set(params.keys())
for param, data in params.items():
np.testing.assert_equal(data, getattr(params, param))
def test_sort_values(self, TestParams):
"""Ensure sort runs and is stable"""
sorted_tp = TestParams()
sorted_tp.sort_values()
assert sorted_tp.dump(sort_values=False) == TestParams().dump(
sort_values=False
)
shuffled_tp = TestParams()
for param in shuffled_tp:
shuffle(shuffled_tp._data[param]["value"])
shuffled_tp.sel._cache = {}
assert sorted_tp.dump(sort_values=False) != shuffled_tp.dump(
sort_values=False
)
shuffled_tp.sort_values()
assert sorted_tp.dump(sort_values=False) == shuffled_tp.dump(
sort_values=False
)
# Test attribute is updated, too.
for param in sorted_tp:
assert getattr(sorted_tp, param) == getattr(shuffled_tp, param)
def test_sort_values_no_labels(self):
class Params(Parameters):
defaults = {
"test": {
"title": "test",
"description": "",
"type": "int",
"value": 2,
}
}
params = Params()
assert params.sort_values() == params._data
assert params.sort_values({"test": params.test})
assert params.dump()
def test_sort_values_correctness(self):
"""Ensure sort is correct"""
exp = [
{"value": 1},
{"label0": 1, "label1": "one", "value": 1},
{"label0": 1, "label1": "two", "value": 1},
{"label0": 2, "label1": "one", "value": 1},
{"label0": 2, "label1": "two", "value": 1},
{"label0": 3, "label1": "one", "value": 1},
]
shuffled = copy.deepcopy(exp)
shuffle(shuffled)
class Params(Parameters):
defaults = {
"schema": {
"labels": {
"label0": {
"type": "int",
"validators": {"range": {"min": 0, "max": 3}},
},
"label1": {
"type": "str",
"validators": {
"choice": {"choices": ["one", "two"]}
},
},
}
},
"param": {
"title": "test",
"description": "",
"type": "int",
"value": shuffled,
},
}
params = Params(sort_values=False)
assert params.param != exp and params.param == shuffled
params.sort_values()
assert params.param == exp
# test passing in a data object
params = Params(sort_values=False)
assert params.param != exp and params.param == shuffled
data1 = {"param": params.param}
params.sort_values(data1, has_meta_data=False)
data1 = copy.deepcopy(data1)
data2 = {"param": {"value": params.param}}
params.sort_values(data2, has_meta_data=True)
data2 = copy.deepcopy(data2)
params.sort_values()
assert data1["param"] == data2["param"]["value"] == params.param
with pytest.raises(ParamToolsError):
params.sort_values(has_meta_data=False)
def test_dump_sort_values(self, TestParams):
"""Test sort_values keyword in dump()"""
tp = TestParams()
for param in tp:
shuffle(tp._data[param]["value"])
tp.sel._cache = {}
shuffled_dump = tp.dump(sort_values=False)
sorted_dump = tp.dump(sort_values=True)
assert sorted_dump != shuffled_dump
sorted_tp = TestParams()
sorted_tp.sort_values()
assert sorted_tp.dump(sort_values=False) == sorted_dump
# Test that sort works when state is activated
state_tp = TestParams()
for param in tp:
shuffle(state_tp._data[param]["value"])
state_tp.set_state(label0="zero", label2=1)
state_dump = copy.deepcopy(state_tp.dump(sort_values=False))
class NoStateParams(Parameters):
defaults = state_dump
nostate_tp = NoStateParams(sort_values=False)
assert nostate_tp.dump(sort_values=False) == state_dump
assert not nostate_tp.view_state()
assert state_tp.view_state()
assert nostate_tp.dump(sort_values=True) == state_tp.dump(
sort_values=True
)
def test_sort_values_w_array(self, extend_ex_path):
"""Test sort values with array first config"""
class ExtParams(Parameters):
defaults = extend_ex_path
label_to_extend = "d0"
array_first = True
# Test that param attributes are not updated when
# array first is True
params = ExtParams()
params.extend_param = "don't update me"
params.sort_values()
assert params.extend_param == "don't update me"
def test_sort_values_with_state(self, extend_ex_path):
class ExtParams(Parameters):
defaults = extend_ex_path
label_to_extend = "d0"
array_first = False
params = ExtParams()
params.set_state(d0=[6, 7, 8, 9])
params.sort_values()
assert params.extend_param == [
{"d0": 6, "d1": "c1", "value": 5, "_auto": True},
{"d0": 6, "d1": "c2", "value": 6, "_auto": True},
{"d0": 7, "d1": "c1", "value": 7},
{"d0": 7, "d1": "c2", "value": 8},
{"d0": 8, "d1": "c1", "value": 7, "_auto": True},
{"d0": 8, "d1": "c2", "value": 8, "_auto": True},
{"d0": 9, "d1": "c1", "value": 7, "_auto": True},
{"d0": 9, "d1": "c2", "value": 8, "_auto": True},
]
class TestAdjust:
def test_adjust_int_param(self, TestParams):
params = TestParams()
params.set_state(label0="one", label1=2)
adjustment = {
"min_int_param": [{"label0": "one", "label1": 2, "value": 3}]
}
params.adjust(adjustment)
assert params.min_int_param == adjustment["min_int_param"]
def test_simultaneous_adjust(self, TestParams):
"""
Adjust min_int_param above original max_int_param value at same time as
max_int_param value is adjusted up. This tests that the new param is
compared against the adjusted reference param if the reference param is
specified.
"""
params = TestParams()
params.set_state(label0="zero", label1=1)
adjustment = {
"min_int_param": [{"label0": "zero", "label1": 1, "value": 4}],
"max_int_param": [{"label0": "zero", "label1": 1, "value": 5}],
}
params.adjust(adjustment)
assert params.min_int_param == adjustment["min_int_param"]
assert params.max_int_param == adjustment["max_int_param"]
def test_transaction(self, TestParams):
"""
Use transaction manager to defer schema level validation until all adjustments
are complete.
"""
params = TestParams()
params.set_state(label0="zero", label1=1)
adjustment = {
"min_int_param": [{"label0": "zero", "label1": 1, "value": 4}],
"max_int_param": [{"label0": "zero", "label1": 1, "value": 5}],
}
with params.transaction(defer_validation=True):
params.adjust({"min_int_param": adjustment["min_int_param"]})
params.adjust({"max_int_param": adjustment["max_int_param"]})
assert params.min_int_param == adjustment["min_int_param"]
assert params.max_int_param == adjustment["max_int_param"]
def test_transaction_with_when_parameter(self, TestParams):
"""
When validator returns None when validate_schema is False for performance
reasons.
"""
params = TestParams()
with params.transaction(defer_validation=True):
params.adjust({"when_param": 2, "str_choice_param": "value1"})
assert params.when_param == [{"value": 2}]
def test_adjust_many_labels(self, TestParams):
"""
Adjust min_int_param above original max_int_param value at same time as
max_int_param value is adjusted up. This tests that the new param is
compared against the adjusted reference param if the reference param is
specified.
"""
params = TestParams()
params.set_state(label0="zero", label1=1)
adjustment = {
"min_int_param": [{"label0": "one", "label1": 2, "value": 2}],
"int_default_param": 5,
"date_param": [
{"label0": "zero", "label1": 1, "value": "2018-01-17"}
],
}
params.adjust(adjustment)
# min_int_param is adjusted in the _data attribute but the instance
# attribute min_int_param is not.
spec = params.specification(use_state=False, label0="one", label1=2)
assert spec["min_int_param"] == adjustment["min_int_param"]
assert params.min_int_param == [
{"label0": "zero", "label1": 1, "value": 1}
]
assert params.int_default_param == [
{"value": adjustment["int_default_param"]}
]
assert params.date_param == [
{
"value": datetime.date(2018, 1, 17),
"label1": 1,
"label0": "zero",
}
]
def test_adjust_none_basic(self, TestParams):
params = TestParams()
adj = {
"min_int_param": [{"label0": "one", "label1": 2, "value": None}],
"str_choice_param": [{"value": None}],
}
params.adjust(adj)
print(params.str_choice_param)
assert len(params.min_int_param) == 1
assert len(params.str_choice_param) == 0
def test_adjust_none_many_values(self, TestParams):
params = TestParams()
adj = {"int_dense_array_param": [{"value": None}]}
params.adjust(adj)
assert len(params._data["int_dense_array_param"]["value"]) == 0
assert len(params.int_dense_array_param) == 0
params = TestParams()
adj = {"int_dense_array_param": [{"label0": "zero", "value": None}]}
params.adjust(adj)
assert len(params._data["int_dense_array_param"]["value"]) == 18
assert len(params.int_dense_array_param) == 18
assert (
len(
params.specification(
use_state=False, include_empty=True, label0="zero"
)["int_dense_array_param"]
)
== 0
)
assert (
len(
params.specification(
use_state=False, include_empty=True, label0="one"
)["int_dense_array_param"]
)
== 18
)
def test_delete(self, TestParams):
params = TestParams()
adj = {
"min_int_param": [{"label0": "one", "label1": 2, "value": 2}],
"str_choice_param": None,
}
params.delete(adj)
assert len(params.min_int_param) == 1
assert len(params.str_choice_param) == 0
params = TestParams()
adj = {"int_dense_array_param": None}
params.delete(adj)
assert len(params._data["int_dense_array_param"]["value"]) == 0
assert len(params.int_dense_array_param) == 0
params = TestParams()
adj = {"int_dense_array_param": [{"label0": "zero", "value": 2}]}
params.delete(adj)
assert len(params._data["int_dense_array_param"]["value"]) == 18
assert len(params.int_dense_array_param) == 18
assert (
len(
params.specification(
use_state=False, include_empty=True, label0="zero"
)["int_dense_array_param"]
)
== 0
)
assert (
len(
params.specification(
use_state=False, include_empty=True, label0="one"
)["int_dense_array_param"]
)
== 18
)
def test_adjust_when_param(self, TestParams):
params = TestParams()
params.adjust({"when_param": 2, "str_choice_param": "value1"})
assert params.when_param == [{"value": 2}]
params = TestParams()
params.adjust({"when_param": 0})
assert params.when_param == [{"value": 0}]
def test_adjust_when_array_param(self, TestParams):
params = TestParams()
params.adjust({"when_array_param": [0, 1, 0, 0]})
assert params.when_array_param == [{"value": [0, 1, 0, 0]}]
def test_adjust_float_list_when_param(self, TestParams):
params = TestParams()
params.adjust({"float_list_when_param": [0, 2.0, 2.0, 2.0]})
assert params.float_list_when_param == [
{"label0": "zero", "value": [0, 2.0, 2.0, 2.0]}
]
class TestValidationMessages:
def test_attributes(self, TestParams):
params = TestParams()
assert params.errors == {}
assert params.warnings == {}
def test_errors(self, TestParams):
params = TestParams()
adj = {"min_int_param": [{"value": "abc"}]}
with pytest.raises(ValidationError) as excinfo:
params.adjust(adj)
exp_user_message = {"min_int_param": ["Not a valid integer: abc."]}
assert json.loads(excinfo.value.args[0]) == {
"errors": exp_user_message
}
exp_internal_message = {
"min_int_param": [["Not a valid integer: abc."]]
}
assert excinfo.value.messages["errors"] == exp_internal_message
exp_labels = {"min_int_param": [{}]}
assert excinfo.value.labels["errors"] == exp_labels
params = TestParams()
adj = {"min_int_param": "abc"}
with pytest.raises(ValidationError) as excinfo:
params.adjust(adj)
def test_label_errors(self, TestParams):
params = TestParams()
params.adjust(
{"min_int_param": [{"value": 2, "label1": 6}]}, raise_errors=False
)
assert params.errors["min_int_param"] == [
"Input 6 must be less than 5."
]
params = TestParams()
params.adjust(
{"min_int_param": [{"value": 2, "label1": -1}]}, raise_errors=False
)
assert params.errors["min_int_param"] == [
"Input -1 must be greater than 0."
]
def test_errors_choice_param(self, TestParams):
params = TestParams()
adjustment = {"str_choice_param": [{"value": "not a valid choice"}]}
with pytest.raises(ValidationError) as excinfo:
params.adjust(adjustment)
msg = [
'str_choice_param "not a valid choice" must be in list of choices value0, '
"value1."
]
assert (
json.loads(excinfo.value.args[0])["errors"]["str_choice_param"]
== msg
)
params = TestParams()
adjustment = {"str_choice_param": [{"value": 4}]}
params = TestParams()
with pytest.raises(ValidationError) as excinfo:
params.adjust(adjustment)
msg = ["Not a valid string."]
assert (
json.loads(excinfo.value.args[0])["errors"]["str_choice_param"]
== msg
)
params = TestParams()
params.adjust(adjustment, raise_errors=False)
msg = ["Not a valid string."]
assert params.errors["str_choice_param"] == msg
params = TestParams()
with pytest.raises(ValidationError) as excinfo:
params.adjust(adjustment)
msg = ["Not a valid string."]
assert (
json.loads(excinfo.value.args[0])["errors"]["str_choice_param"]
== msg
)
params = TestParams()
params.adjust(adjustment, raise_errors=False)
params.errors["str_choice_param"] == ["Not a valid string."]
def test_errors_default_reference_param(self, TestParams):
params = TestParams()
params.set_state(label0="zero", label1=1)
# value under the default.
curr = params.int_default_param[0]["value"]
adjustment = {"int_default_param": [{"value": curr - 1}]}
params.adjust(adjustment, raise_errors=False)
exp = [f"int_default_param {curr-1} < min 2 default"]
assert params.errors["int_default_param"] == exp
def test_errors_int_param(self, TestParams):
params = TestParams()
adjustment = {
"min_int_param": [{"label0": "zero", "label1": 1, "value": 2.5}]
}
params.adjust(adjustment, raise_errors=False)
exp = {"min_int_param": ["Not a valid integer: 2.5."]}
assert params.errors == exp
def test_errors_multiple_params(self, TestParams):
params = TestParams()
adjustment = {
"min_int_param": [
{"label0": "zero", "label1": 1, "value": "not a number"},
{"label0": "one", "label1": 2, "value": "still not a number"},
],
"date_param": [
{"label0": "zero", "label1": 1, "value": "not a date"}
],
}
params.adjust(adjustment, raise_errors=False)
exp = {
"min_int_param": [
"Not a valid integer: not a number.",
"Not a valid integer: still not a number.",
],
"date_param": ["Not a valid date: not a date."],
}
assert params.errors == exp
def test_list_type_errors(self, TestParams):
params = TestParams()
adj = {
"float_list_param": [
{"value": ["abc", 0, "def", 1], "label0": "zero", "label1": 1},
{"value": [-1, "ijk"], "label0": "one", "label1": 2},
]
}
with pytest.raises(ValidationError) as excinfo:
params.adjust(adj)
exp_user_message = {
"float_list_param": [
"Not a valid number: abc.",
"Not a valid number: def.",
"Not a valid number: ijk.",
]
}
assert json.loads(excinfo.value.args[0]) == {
"errors": exp_user_message
}
exp_internal_message = {
"float_list_param": [
["Not a valid number: abc.", "Not a valid number: def."],
["Not a valid number: ijk."],
]
}
assert excinfo.value.messages["errors"] == exp_internal_message
exp_labels = {
"float_list_param": [
{"label0": "zero", "label1": 1},
{"label0": "one", "label1": 2},
]
}
assert excinfo.value.labels["errors"] == exp_labels
params = TestParams()
adjustment = {"float_param": [2.5]}