-
Notifications
You must be signed in to change notification settings - Fork 64
/
test_model.py
6380 lines (5222 loc) · 212 KB
/
test_model.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
# Copyright 2018 Google LLC
#
# 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
#
# https://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.
import datetime
import pickle
import pytz
import types
import zlib
from unittest import mock
from google.cloud import datastore
from google.cloud.datastore import entity as entity_module
from google.cloud.datastore import key as ds_key_module
from google.cloud.datastore import helpers
from google.cloud.datastore_v1 import types as ds_types
from google.cloud.datastore_v1.types import entity as entity_pb2
import pytest
from google.cloud.ndb import _datastore_types
from google.cloud.ndb import exceptions
from google.cloud.ndb import key as key_module
from google.cloud.ndb import model
from google.cloud.ndb import _options
from google.cloud.ndb import polymodel
from google.cloud.ndb import query as query_module
from google.cloud.ndb import tasklets
from google.cloud.ndb import utils as ndb_utils
from google.cloud.ndb import _legacy_entity_pb
from . import utils
class timezone(datetime.tzinfo):
def __init__(self, offset):
self.offset = datetime.timedelta(hours=offset)
def utcoffset(self, dt):
return self.offset
def dst(self, dt):
return datetime.timedelta(0)
def __eq__(self, other):
return self.offset == other.offset
def test___all__():
utils.verify___all__(model)
def test_Key():
assert model.Key is key_module.Key
def test_BlobKey():
assert model.BlobKey is _datastore_types.BlobKey
def test_GeoPt():
assert model.GeoPt is helpers.GeoPoint
class TestIndexProperty:
@staticmethod
def test_constructor():
index_prop = model.IndexProperty(name="a", direction="asc")
assert index_prop._name == "a"
assert index_prop._direction == "asc"
@staticmethod
def test_name():
index_prop = model.IndexProperty(name="b", direction="asc")
assert index_prop.name == "b"
@staticmethod
def test_direction():
index_prop = model.IndexProperty(name="a", direction="desc")
assert index_prop.direction == "desc"
@staticmethod
def test___repr__():
index_prop = model.IndexProperty(name="c", direction="asc")
assert repr(index_prop) == "IndexProperty(name='c', direction='asc')"
@staticmethod
def test___eq__():
index_prop1 = model.IndexProperty(name="d", direction="asc")
index_prop2 = model.IndexProperty(name="d", direction="desc")
index_prop3 = mock.sentinel.index_prop
assert index_prop1 == index_prop1
assert not index_prop1 == index_prop2
assert not index_prop1 == index_prop3
@staticmethod
def test___ne__():
index_prop1 = model.IndexProperty(name="d", direction="asc")
index_prop2 = model.IndexProperty(name="d", direction="desc")
index_prop3 = mock.sentinel.index_prop
index_prop4 = model.IndexProperty(name="d", direction="asc")
assert not index_prop1 != index_prop1
assert index_prop1 != index_prop2
assert index_prop1 != index_prop3
assert not index_prop1 != index_prop4
@staticmethod
def test___hash__():
index_prop1 = model.IndexProperty(name="zip", direction="asc")
index_prop2 = model.IndexProperty(name="zip", direction="asc")
assert index_prop1 is not index_prop2
assert hash(index_prop1) == hash(index_prop2)
assert hash(index_prop1) == hash(("zip", "asc"))
class TestIndex:
@staticmethod
def test_constructor():
index_prop = model.IndexProperty(name="a", direction="asc")
index = model.Index(kind="IndK", properties=(index_prop,), ancestor=False)
assert index._kind == "IndK"
assert index._properties == (index_prop,)
assert not index._ancestor
@staticmethod
def test_kind():
index = model.Index(kind="OK", properties=(), ancestor=False)
assert index.kind == "OK"
@staticmethod
def test_properties():
index_prop1 = model.IndexProperty(name="a", direction="asc")
index_prop2 = model.IndexProperty(name="b", direction="desc")
index = model.Index(
kind="F", properties=(index_prop1, index_prop2), ancestor=False
)
assert index.properties == (index_prop1, index_prop2)
@staticmethod
def test_ancestor():
index = model.Index(kind="LK", properties=(), ancestor=True)
assert index.ancestor
@staticmethod
def test___repr__():
index_prop = model.IndexProperty(name="a", direction="asc")
index = model.Index(kind="IndK", properties=[index_prop], ancestor=False)
expected = "Index(kind='IndK', properties=[{!r}], ancestor=False)"
expected = expected.format(index_prop)
assert repr(index) == expected
@staticmethod
def test___eq__():
index_props = (model.IndexProperty(name="a", direction="asc"),)
index1 = model.Index(kind="d", properties=index_props, ancestor=False)
index2 = model.Index(kind="d", properties=(), ancestor=False)
index3 = model.Index(kind="d", properties=index_props, ancestor=True)
index4 = model.Index(kind="e", properties=index_props, ancestor=False)
index5 = mock.sentinel.index
assert index1 == index1
assert not index1 == index2
assert not index1 == index3
assert not index1 == index4
assert not index1 == index5
@staticmethod
def test___ne__():
index_props = (model.IndexProperty(name="a", direction="asc"),)
index1 = model.Index(kind="d", properties=index_props, ancestor=False)
index2 = model.Index(kind="d", properties=(), ancestor=False)
index3 = model.Index(kind="d", properties=index_props, ancestor=True)
index4 = model.Index(kind="e", properties=index_props, ancestor=False)
index5 = mock.sentinel.index
index6 = model.Index(kind="d", properties=index_props, ancestor=False)
assert not index1 != index1
assert index1 != index2
assert index1 != index3
assert index1 != index4
assert index1 != index5
assert not index1 != index6
@staticmethod
def test___hash__():
index_props = (model.IndexProperty(name="a", direction="asc"),)
index1 = model.Index(kind="d", properties=index_props, ancestor=False)
index2 = model.Index(kind="d", properties=index_props, ancestor=False)
assert index1 is not index2
assert hash(index1) == hash(index2)
assert hash(index1) == hash(("d", index_props, False))
class TestIndexState:
INDEX = mock.sentinel.index
def test_constructor(self):
index_state = model.IndexState(definition=self.INDEX, state="error", id=42)
assert index_state._definition is self.INDEX
assert index_state._state == "error"
assert index_state._id == 42
def test_definition(self):
index_state = model.IndexState(definition=self.INDEX, state="serving", id=1)
assert index_state.definition is self.INDEX
@staticmethod
def test_state():
index_state = model.IndexState(definition=None, state="deleting", id=1)
assert index_state.state == "deleting"
@staticmethod
def test_id():
index_state = model.IndexState(definition=None, state="error", id=1001)
assert index_state.id == 1001
@staticmethod
def test___repr__():
index_prop = model.IndexProperty(name="a", direction="asc")
index = model.Index(kind="IndK", properties=[index_prop], ancestor=False)
index_state = model.IndexState(definition=index, state="building", id=1337)
expected = (
"IndexState(definition=Index(kind='IndK', properties=["
"IndexProperty(name='a', direction='asc')], ancestor=False), "
"state='building', id=1337)"
)
assert repr(index_state) == expected
def test___eq__(self):
index_state1 = model.IndexState(definition=self.INDEX, state="error", id=20)
index_state2 = model.IndexState(
definition=mock.sentinel.not_index, state="error", id=20
)
index_state3 = model.IndexState(definition=self.INDEX, state="serving", id=20)
index_state4 = model.IndexState(definition=self.INDEX, state="error", id=80)
index_state5 = mock.sentinel.index_state
assert index_state1 == index_state1
assert not index_state1 == index_state2
assert not index_state1 == index_state3
assert not index_state1 == index_state4
assert not index_state1 == index_state5
def test___ne__(self):
index_state1 = model.IndexState(definition=self.INDEX, state="error", id=20)
index_state2 = model.IndexState(
definition=mock.sentinel.not_index, state="error", id=20
)
index_state3 = model.IndexState(definition=self.INDEX, state="serving", id=20)
index_state4 = model.IndexState(definition=self.INDEX, state="error", id=80)
index_state5 = mock.sentinel.index_state
index_state6 = model.IndexState(definition=self.INDEX, state="error", id=20)
assert not index_state1 != index_state1
assert index_state1 != index_state2
assert index_state1 != index_state3
assert index_state1 != index_state4
assert index_state1 != index_state5
assert not index_state1 != index_state6
def test___hash__(self):
index_state1 = model.IndexState(definition=self.INDEX, state="error", id=88)
index_state2 = model.IndexState(definition=self.INDEX, state="error", id=88)
assert index_state1 is not index_state2
assert hash(index_state1) == hash(index_state2)
assert hash(index_state1) == hash((self.INDEX, "error", 88))
class TestModelAdapter:
@staticmethod
def test_constructor():
with pytest.raises(NotImplementedError):
model.ModelAdapter()
def test_make_connection():
with pytest.raises(NotImplementedError):
model.make_connection()
class TestModelAttribute:
@staticmethod
def test_constructor():
attr = model.ModelAttribute()
assert isinstance(attr, model.ModelAttribute)
@staticmethod
def test__fix_up():
attr = model.ModelAttribute()
assert attr._fix_up(model.Model, "birthdate") is None
class Test_BaseValue:
@staticmethod
def test_constructor():
wrapped = model._BaseValue(17)
assert wrapped.b_val == 17
@staticmethod
def test_constructor_invalid_input():
with pytest.raises(TypeError):
model._BaseValue(None)
with pytest.raises(TypeError):
model._BaseValue([1, 2])
@staticmethod
def test___repr__():
wrapped = model._BaseValue("abc")
assert repr(wrapped) == "_BaseValue('abc')"
@staticmethod
def test___eq__():
wrapped1 = model._BaseValue("one val")
wrapped2 = model._BaseValue(25.5)
wrapped3 = mock.sentinel.base_value
assert wrapped1 == wrapped1
assert not wrapped1 == wrapped2
assert not wrapped1 == wrapped3
@staticmethod
def test___ne__():
wrapped1 = model._BaseValue("one val")
wrapped2 = model._BaseValue(25.5)
wrapped3 = mock.sentinel.base_value
wrapped4 = model._BaseValue("one val")
assert not wrapped1 != wrapped1
assert wrapped1 != wrapped2
assert wrapped1 != wrapped3
assert not wrapped1 != wrapped4
@staticmethod
def test___hash__():
wrapped = model._BaseValue((11, 12, 88))
with pytest.raises(TypeError):
hash(wrapped)
class TestProperty:
@staticmethod
def test_constructor_defaults():
prop = model.Property()
# Check that none of the constructor defaults were used.
assert prop.__dict__ == {}
@staticmethod
def _example_validator(prop, value):
return value.lower()
def test__example_validator(self):
value = "AbCde"
validated = self._example_validator(None, value)
assert validated == "abcde"
assert self._example_validator(None, validated) == "abcde"
def test_constructor_explicit(self):
prop = model.Property(
name="val",
indexed=False,
repeated=False,
required=True,
default="zorp",
choices=("zorp", "zap", "zip"),
validator=self._example_validator,
verbose_name="VALUE FOR READING",
write_empty_list=False,
)
assert prop._name == "val"
assert not prop._indexed
assert not prop._repeated
assert prop._required
assert prop._default == "zorp"
assert prop._choices == frozenset(("zorp", "zap", "zip"))
assert prop._validator is self._example_validator
assert prop._verbose_name == "VALUE FOR READING"
assert not prop._write_empty_list
@staticmethod
def test_constructor_invalid_name():
with pytest.raises(TypeError):
model.Property(name=["not", "a", "string"])
with pytest.raises(ValueError):
model.Property(name="has.a.dot")
@staticmethod
def test_constructor_repeated_not_allowed():
with pytest.raises(ValueError):
model.Property(name="a", repeated=True, required=True)
with pytest.raises(ValueError):
model.Property(name="b", repeated=True, default="zim")
@staticmethod
def test_constructor_invalid_choices():
with pytest.raises(TypeError):
model.Property(name="a", choices={"wrong": "container"})
@staticmethod
def test_constructor_invalid_validator():
with pytest.raises(TypeError):
model.Property(name="a", validator=mock.sentinel.validator)
def test_repr(self):
prop = model.Property(
"val",
indexed=False,
repeated=False,
required=True,
default="zorp",
choices=("zorp", "zap", "zip"),
validator=self._example_validator,
verbose_name="VALUE FOR READING",
write_empty_list=False,
)
expected = (
"Property('val', indexed=False, required=True, "
"default='zorp', choices={}, validator={}, "
"verbose_name='VALUE FOR READING')".format(prop._choices, prop._validator)
)
assert repr(prop) == expected
@staticmethod
def test_repr_subclass():
class SimpleProperty(model.Property):
_foo_type = None
_bar = "eleventy"
@ndb_utils.positional(1)
def __init__(self, foo_type, bar):
self._foo_type = foo_type
self._bar = bar
prop = SimpleProperty(foo_type=list, bar="nope")
assert repr(prop) == "SimpleProperty(foo_type=list, bar='nope')"
@staticmethod
def test__datastore_type():
prop = model.Property("foo")
value = mock.sentinel.value
assert prop._datastore_type(value) is value
@staticmethod
def test__comparison_indexed():
prop = model.Property("color", indexed=False)
with pytest.raises(exceptions.BadFilterError):
prop._comparison("!=", "red")
@staticmethod
def test__comparison():
prop = model.Property("sentiment", indexed=True)
filter_node = prop._comparison(">=", 0.0)
assert filter_node == query_module.FilterNode("sentiment", ">=", 0.0)
@staticmethod
def test__comparison_empty_value():
prop = model.Property("height", indexed=True)
filter_node = prop._comparison("=", None)
assert filter_node == query_module.FilterNode("height", "=", None)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test___eq__():
prop = model.Property("name", indexed=True)
value = 1337
expected = query_module.FilterNode("name", "=", value)
filter_node_left = prop == value
assert filter_node_left == expected
filter_node_right = value == prop
assert filter_node_right == expected
@staticmethod
def test___ne__():
prop = model.Property("name", indexed=True)
value = 7.0
expected = query_module.DisjunctionNode(
query_module.FilterNode("name", "<", value),
query_module.FilterNode("name", ">", value),
)
or_node_left = prop != value
assert or_node_left == expected
or_node_right = value != prop
assert or_node_right == expected
@staticmethod
def test___lt__():
prop = model.Property("name", indexed=True)
value = 2.0
expected = query_module.FilterNode("name", "<", value)
filter_node_left = prop < value
assert filter_node_left == expected
filter_node_right = value > prop
assert filter_node_right == expected
@staticmethod
def test___le__():
prop = model.Property("name", indexed=True)
value = 20.0
expected = query_module.FilterNode("name", "<=", value)
filter_node_left = prop <= value
assert filter_node_left == expected
filter_node_right = value >= prop
assert filter_node_right == expected
@staticmethod
def test___gt__():
prop = model.Property("name", indexed=True)
value = "new"
expected = query_module.FilterNode("name", ">", value)
filter_node_left = prop > value
assert filter_node_left == expected
filter_node_right = value < prop
assert filter_node_right == expected
@staticmethod
def test___ge__():
prop = model.Property("name", indexed=True)
value = "old"
expected = query_module.FilterNode("name", ">=", value)
filter_node_left = prop >= value
assert filter_node_left == expected
filter_node_right = value <= prop
assert filter_node_right == expected
@staticmethod
def test__IN_not_indexed():
prop = model.Property("name", indexed=False)
with pytest.raises(exceptions.BadFilterError):
prop._IN([10, 20, 81])
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__IN_wrong_container():
prop = model.Property("name", indexed=True)
with pytest.raises(exceptions.BadArgumentError):
prop._IN({1: "a", 11: "b"})
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__IN():
prop = model.Property("name", indexed=True)
or_node = prop._IN(["a", None, "xy"])
expected = query_module.DisjunctionNode(
query_module.FilterNode("name", "=", "a"),
query_module.FilterNode("name", "=", None),
query_module.FilterNode("name", "=", "xy"),
)
assert or_node == expected
# Also verify the alias
assert or_node == prop.IN(["a", None, "xy"])
@staticmethod
def test___neg__():
prop = model.Property("name")
order = -prop
assert isinstance(order, query_module.PropertyOrder)
assert order.name == "name"
assert order.reverse is True
order = -order
assert order.reverse is False
@staticmethod
def test___pos__():
prop = model.Property("name")
order = +prop
assert isinstance(order, query_module.PropertyOrder)
assert order.name == "name"
assert order.reverse is False
@staticmethod
def test__do_validate():
validator = mock.Mock(spec=())
value = 18
choices = (1, 2, validator.return_value)
prop = model.Property(name="foo", validator=validator, choices=choices)
result = prop._do_validate(value)
assert result is validator.return_value
# Check validator call.
validator.assert_called_once_with(prop, value)
@staticmethod
def test__do_validate_base_value():
value = model._BaseValue(b"\x00\x01")
prop = model.Property(name="foo")
result = prop._do_validate(value)
assert result is value
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__do_validate_validator_none():
validator = mock.Mock(spec=(), return_value=None)
value = 18
prop = model.Property(name="foo", validator=validator)
result = prop._do_validate(value)
assert result == value
# Check validator call.
validator.assert_called_once_with(prop, value)
@staticmethod
def test__do_validate_not_in_choices():
value = 18
prop = model.Property(name="foo", choices=(1, 2))
with pytest.raises(exceptions.BadValueError):
prop._do_validate(value)
@staticmethod
def test__do_validate_call_validation():
class SimpleProperty(model.Property):
def _validate(self, value):
value.append("SimpleProperty._validate")
return value
value = []
prop = SimpleProperty(name="foo")
result = prop._do_validate(value)
assert result is value
assert value == ["SimpleProperty._validate"]
@staticmethod
def test__fix_up():
prop = model.Property(name="foo")
assert prop._code_name is None
prop._fix_up(None, "bar")
assert prop._code_name == "bar"
@staticmethod
def test__fix_up_no_name():
prop = model.Property()
assert prop._name is None
assert prop._code_name is None
prop._fix_up(None, "both")
assert prop._code_name == "both"
assert prop._name == "both"
@staticmethod
def test__store_value():
entity = mock.Mock(_values={}, spec=("_values",))
prop = model.Property(name="foo")
prop._store_value(entity, mock.sentinel.value)
assert entity._values == {prop._name: mock.sentinel.value}
@staticmethod
def test__set_value():
entity = mock.Mock(
_projection=None, _values={}, spec=("_projection", "_values")
)
prop = model.Property(name="foo", repeated=False)
prop._set_value(entity, 19)
assert entity._values == {prop._name: 19}
@staticmethod
def test__set_value_none():
entity = mock.Mock(
_projection=None, _values={}, spec=("_projection", "_values")
)
prop = model.Property(name="foo", repeated=False)
prop._set_value(entity, None)
assert entity._values == {prop._name: None}
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__set_value_repeated():
entity = mock.Mock(
_projection=None, _values={}, spec=("_projection", "_values")
)
prop = model.Property(name="foo", repeated=True)
prop._set_value(entity, (11, 12, 13))
assert entity._values == {prop._name: [11, 12, 13]}
@staticmethod
def test__set_value_repeated_bad_container():
entity = mock.Mock(
_projection=None, _values={}, spec=("_projection", "_values")
)
prop = model.Property(name="foo", repeated=True)
with pytest.raises(exceptions.BadValueError):
prop._set_value(entity, None)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__set_value_projection():
entity = mock.Mock(_projection=("a", "b"), spec=("_projection",))
prop = model.Property(name="foo", repeated=True)
with pytest.raises(model.ReadonlyPropertyError):
prop._set_value(entity, None)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__has_value():
prop = model.Property(name="foo")
values = {prop._name: 88}
entity1 = mock.Mock(_values=values, spec=("_values",))
entity2 = mock.Mock(_values={}, spec=("_values",))
assert prop._has_value(entity1)
assert not prop._has_value(entity2)
@staticmethod
def test__retrieve_value():
prop = model.Property(name="foo")
values = {prop._name: b"\x00\x01"}
entity1 = mock.Mock(_values=values, spec=("_values",))
entity2 = mock.Mock(_values={}, spec=("_values",))
assert prop._retrieve_value(entity1) == b"\x00\x01"
assert prop._retrieve_value(entity2) is None
assert prop._retrieve_value(entity2, default=b"zip") == b"zip"
@staticmethod
def test__get_user_value():
prop = model.Property(name="prop")
value = b"\x00\x01"
values = {prop._name: value}
entity = mock.Mock(_values=values, spec=("_values",))
assert value is prop._get_user_value(entity)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__get_user_value_wrapped():
class SimpleProperty(model.Property):
def _from_base_type(self, value):
return value * 2.0
prop = SimpleProperty(name="prop")
values = {prop._name: model._BaseValue(9.5)}
entity = mock.Mock(_values=values, spec=("_values",))
assert prop._get_user_value(entity) == 19.0
@staticmethod
def test__get_base_value():
class SimpleProperty(model.Property):
def _validate(self, value):
return value + 1
prop = SimpleProperty(name="prop")
values = {prop._name: 20}
entity = mock.Mock(_values=values, spec=("_values",))
assert prop._get_base_value(entity) == model._BaseValue(21)
@staticmethod
def test__get_base_value_wrapped():
prop = model.Property(name="prop")
value = model._BaseValue(b"\x00\x01")
values = {prop._name: value}
entity = mock.Mock(_values=values, spec=("_values",))
assert value is prop._get_base_value(entity)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__get_base_value_unwrapped_as_list():
class SimpleProperty(model.Property):
def _validate(self, value):
return value + 11
prop = SimpleProperty(name="prop", repeated=False)
values = {prop._name: 20}
entity = mock.Mock(_values=values, spec=("_values",))
assert prop._get_base_value_unwrapped_as_list(entity) == [31]
@staticmethod
def test__get_base_value_unwrapped_as_list_empty():
prop = model.Property(name="prop", repeated=False)
entity = mock.Mock(_values={}, spec=("_values",))
assert prop._get_base_value_unwrapped_as_list(entity) == [None]
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__get_base_value_unwrapped_as_list_repeated():
class SimpleProperty(model.Property):
def _validate(self, value):
return value / 10.0
prop = SimpleProperty(name="prop", repeated=True)
values = {prop._name: [20, 30, 40]}
entity = mock.Mock(_values=values, spec=("_values",))
expected = [2.0, 3.0, 4.0]
assert prop._get_base_value_unwrapped_as_list(entity) == expected
@staticmethod
def test__opt_call_from_base_type():
prop = model.Property(name="prop")
value = b"\x00\x01"
assert value is prop._opt_call_from_base_type(value)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__opt_call_from_base_type_wrapped():
class SimpleProperty(model.Property):
def _from_base_type(self, value):
return value * 2.0
prop = SimpleProperty(name="prop")
value = model._BaseValue(8.5)
assert prop._opt_call_from_base_type(value) == 17.0
@staticmethod
def test__value_to_repr():
class SimpleProperty(model.Property):
def _from_base_type(self, value):
return value * 3.0
prop = SimpleProperty(name="prop")
value = model._BaseValue(9.25)
assert prop._value_to_repr(value) == "27.75"
@staticmethod
def test__opt_call_to_base_type():
class SimpleProperty(model.Property):
def _validate(self, value):
return value + 1
prop = SimpleProperty(name="prop")
value = 17
result = prop._opt_call_to_base_type(value)
assert result == model._BaseValue(value + 1)
@staticmethod
def test__opt_call_to_base_type_wrapped():
prop = model.Property(name="prop")
value = model._BaseValue(b"\x00\x01")
assert value is prop._opt_call_to_base_type(value)
# Cache is untouched.
assert model.Property._FIND_METHODS_CACHE == {}
@staticmethod
def test__call_from_base_type():
class SimpleProperty(model.Property):
def _from_base_type(self, value):
value.append("SimpleProperty._from_base_type")
return value
prop = SimpleProperty(name="prop")
value = []
assert value is prop._call_from_base_type(value)
assert value == ["SimpleProperty._from_base_type"]
@staticmethod
def _property_subtype_chain():
class A(model.Property):
def _validate(self, value):
value.append("A._validate")
return value
def _to_base_type(self, value):
value.append("A._to_base_type")
return value
class B(A):
def _validate(self, value):
value.append("B._validate")
return value
def _to_base_type(self, value):
value.append("B._to_base_type")
return value
class C(B):
def _validate(self, value):
value.append("C._validate")
return value
value = []
prop_a = A(name="name-a")
assert value is prop_a._validate(value)
assert value == ["A._validate"]
assert value is prop_a._to_base_type(value)
assert value == ["A._validate", "A._to_base_type"]
prop_b = B(name="name-b")
assert value is prop_b._validate(value)
assert value == ["A._validate", "A._to_base_type", "B._validate"]
assert value is prop_b._to_base_type(value)
assert value == [
"A._validate",
"A._to_base_type",
"B._validate",
"B._to_base_type",
]
prop_c = C(name="name-c")
assert value is prop_c._validate(value)
assert value == [
"A._validate",
"A._to_base_type",
"B._validate",
"B._to_base_type",
"C._validate",
]
return A, B, C
def test__call_to_base_type(self):
_, _, PropertySubclass = self._property_subtype_chain()
prop = PropertySubclass(name="prop")
value = []
assert value is prop._call_to_base_type(value)
assert value == [
"C._validate",
"B._validate",
"B._to_base_type",
"A._validate",
"A._to_base_type",
]
def test__call_shallow_validation(self):
_, _, PropertySubclass = self._property_subtype_chain()
prop = PropertySubclass(name="prop")
value = []
assert value is prop._call_shallow_validation(value)
assert value == ["C._validate", "B._validate"]
@staticmethod
def test__call_shallow_validation_no_break():
class SimpleProperty(model.Property):
def _validate(self, value):
value.append("SimpleProperty._validate")
return value
prop = SimpleProperty(name="simple")
value = []
assert value is prop._call_shallow_validation(value)
assert value == ["SimpleProperty._validate"]
@staticmethod
def _property_subtype():
class SomeProperty(model.Property):
def find_me(self):
return self._name
def IN(self):
return len(self._name) < 20
prop = SomeProperty(name="hi")
assert prop.find_me() == "hi"
assert prop.IN()
return SomeProperty
def test__find_methods(self):
SomeProperty = self._property_subtype()
# Make sure cache is empty.
assert model.Property._FIND_METHODS_CACHE == {}
methods = SomeProperty._find_methods("IN", "find_me")
expected = [SomeProperty.IN, SomeProperty.find_me, model.Property.IN]
assert methods == expected
# Check cache
key = "{}.{}".format(SomeProperty.__module__, SomeProperty.__name__)
assert model.Property._FIND_METHODS_CACHE == {key: {("IN", "find_me"): methods}}
def test__find_methods_reverse(self):
SomeProperty = self._property_subtype()
# Make sure cache is empty.
assert model.Property._FIND_METHODS_CACHE == {}
methods = SomeProperty._find_methods("IN", "find_me", reverse=True)
expected = [model.Property.IN, SomeProperty.find_me, SomeProperty.IN]
assert methods == expected
# Check cache
key = "{}.{}".format(SomeProperty.__module__, SomeProperty.__name__)
assert model.Property._FIND_METHODS_CACHE == {
key: {("IN", "find_me"): list(reversed(methods))}
}
def test__find_methods_cached(self):
SomeProperty = self._property_subtype()
# Set cache
methods = mock.sentinel.methods
key = "{}.{}".format(SomeProperty.__module__, SomeProperty.__name__)
model.Property._FIND_METHODS_CACHE = {key: {("IN", "find_me"): methods}}
assert SomeProperty._find_methods("IN", "find_me") is methods
def test__find_methods_cached_reverse(self):