- Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathtest_hash_model.py
1004 lines (783 loc) · 26.7 KB
/
test_hash_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
# type: ignore
importabc
importdataclasses
importdatetime
importdecimal
importuuid
fromcollectionsimportnamedtuple
fromtypingimportDict, List, Optional, Set, Union
fromunittestimportmock
importpytest
importpytest_asyncio
fromaredis_omimport (
Field,
HashModel,
Migrator,
NotFoundError,
QueryNotSupportedError,
RedisModel,
RedisModelError,
)
# We need to run this check as sync code (during tests) even in async mode
# because we call it in the top-level module scope.
fromredis_omimporthas_redisearch
fromtests._compatimportValidationError
from .conftestimportpy_test_mark_asyncio
ifnothas_redisearch():
pytestmark=pytest.mark.skip
today=datetime.date.today()
@pytest_asyncio.fixture
asyncdefm(key_prefix, redis):
classBaseHashModel(HashModel, abc.ABC):
classMeta:
global_key_prefix=key_prefix
classOrder(BaseHashModel):
total: decimal.Decimal
currency: str
created_on: datetime.datetime
classMember(BaseHashModel):
id: int=Field(index=True, primary_key=True)
first_name: str=Field(index=True, case_sensitive=True)
last_name: str=Field(index=True)
email: str=Field(index=True)
join_date: datetime.date
age: int=Field(index=True, sortable=True)
bio: str=Field(index=True, full_text_search=True)
classMeta:
model_key_prefix="member"
primary_key_pattern=""
awaitMigrator().run()
returnnamedtuple("Models", ["BaseHashModel", "Order", "Member"])(
BaseHashModel, Order, Member
)
@pytest_asyncio.fixture
asyncdefmembers(m):
member1=m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="a@example.com",
age=38,
join_date=today,
bio="This is member 1 whose greatness makes him the life and soul of any party he goes to.",
)
member2=m.Member(
id=1,
first_name="Kim",
last_name="Brookins",
email="k@example.com",
age=34,
join_date=today,
bio="This is member 2 who can be quite anxious until you get to know them.",
)
member3=m.Member(
id=2,
first_name="Andrew",
last_name="Smith",
email="as@example.com",
age=100,
join_date=today,
bio="This is member 3 who is a funny and lively sort of person.",
)
awaitmember1.save()
awaitmember2.save()
awaitmember3.save()
yieldmember1, member2, member3
@py_test_mark_asyncio
asyncdeftest_exact_match_queries(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(m.Member.last_name=="Brookins").sort_by("age").all()
assertactual== [member2, member1]
actual=awaitm.Member.find(
(m.Member.last_name=="Brookins") &~(m.Member.first_name=="Andrew")
).all()
assertactual== [member2]
actual=awaitm.Member.find(~(m.Member.last_name=="Brookins")).all()
assertactual== [member3]
actual=awaitm.Member.find(m.Member.last_name!="Brookins").all()
assertactual== [member3]
actual=await (
m.Member.find(
(m.Member.last_name=="Brookins") & (m.Member.first_name=="Andrew")
| (m.Member.first_name=="Kim")
)
.sort_by("age")
.all()
)
assertactual== [member2, member1]
actual=awaitm.Member.find(
m.Member.first_name=="Kim", m.Member.last_name=="Brookins"
).all()
assertactual== [member2]
actual=awaitm.Member.find(m.Member.id==0).all()
assertactual== [member1]
@py_test_mark_asyncio
asyncdeftest_delete_non_exist(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(
(m.Member.last_name=="Brookins") &~(m.Member.first_name=="Andrew")
).all()
assertactual== [member2]
assert (
1
==awaitm.Member.find(
(m.Member.last_name=="Brookins") &~(m.Member.first_name=="Andrew")
).delete()
)
assert (
0
==awaitm.Member.find(
(m.Member.last_name=="Brookins") &~(m.Member.first_name=="Andrew")
).delete()
)
@py_test_mark_asyncio
asyncdeftest_full_text_search_queries(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(m.Member.bio%"great").all()
assertactual== [member1]
actual=awaitm.Member.find(~(m.Member.bio%"anxious")).sort_by("age").all()
assertactual== [member1, member3]
@py_test_mark_asyncio
@pytest.mark.xfail(strict=False)
asyncdeftest_pagination_queries(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(m.Member.last_name=="Brookins").page()
assertactual== [member1, member2]
actual=awaitm.Member.find().page(1, 1)
assertactual== [member2]
actual=awaitm.Member.find().page(0, 1)
assertactual== [member1]
@py_test_mark_asyncio
asyncdeftest_recursive_query_resolution(members, m):
member1, member2, member3=members
actual=await (
m.Member.find(
(m.Member.last_name=="Brookins")
| (m.Member.age==100) & (m.Member.last_name=="Smith")
)
.sort_by("age")
.all()
)
assertactual== [member2, member1, member3]
@py_test_mark_asyncio
asyncdeftest_tag_queries_boolean_logic(members, m):
member1, member2, member3=members
actual=await (
m.Member.find(
(m.Member.first_name=="Andrew") & (m.Member.last_name=="Brookins")
| (m.Member.last_name=="Smith")
)
.sort_by("age")
.all()
)
assertactual== [member1, member3]
@py_test_mark_asyncio
asyncdeftest_tag_queries_punctuation(m):
member1=m.Member(
id=0,
first_name="Andrew, the Michael",
last_name="St. Brookins-on-Pier",
email="a|b@example.com", # NOTE: This string uses the TAG field separator.
age=38,
join_date=today,
bio="This is a test user on our system.",
)
awaitmember1.save()
member2=m.Member(
id=1,
first_name="Bob",
last_name="the Villain",
email="a|villain@example.com", # NOTE: This string uses the TAG field separator.
age=38,
join_date=today,
bio="This is a villain, they are a really bad person!",
)
awaitmember2.save()
result=awaitm.Member.find(m.Member.first_name=="Andrew, the Michael").first()
assertresult==member1
result=awaitm.Member.find(m.Member.last_name=="St. Brookins-on-Pier").first()
assertresult==member1
# Notice that when we index and query multiple values that use the internal
# TAG separator for single-value exact-match fields, like an indexed string,
# the queries will succeed. We apply a workaround that queries for the union
# of the two values separated by the tag separator.
results=awaitm.Member.find(m.Member.email=="a|b@example.com").all()
assertresults== [member1]
results=awaitm.Member.find(m.Member.email=="a|villain@example.com").all()
assertresults== [member2]
@py_test_mark_asyncio
asyncdeftest_tag_queries_negation(members, m):
member1, member2, member3=members
"""
┌first_name
NOT EQ┤
└Andrew
"""
query=m.Member.find(~(m.Member.first_name=="Andrew"))
assertawaitquery.all() == [member2]
"""
┌first_name
┌NOT EQ┤
| └Andrew
AND┤
| ┌last_name
└EQ┤
└Brookins
"""
query=m.Member.find(
~(m.Member.first_name=="Andrew") & (m.Member.last_name=="Brookins")
)
assertawaitquery.all() == [member2]
"""
┌first_name
┌NOT EQ┤
| └Andrew
AND┤
| ┌last_name
| ┌EQ┤
| | └Brookins
└OR┤
| ┌last_name
└EQ┤
└Smith
"""
query=m.Member.find(
~(m.Member.first_name=="Andrew")
& ((m.Member.last_name=="Brookins") | (m.Member.last_name=="Smith"))
)
assertawaitquery.all() == [member2]
"""
┌first_name
┌NOT EQ┤
| └Andrew
┌AND┤
| | ┌last_name
| └EQ┤
| └Brookins
OR┤
| ┌last_name
└EQ┤
└Smith
"""
query=m.Member.find(
~(m.Member.first_name=="Andrew") & (m.Member.last_name=="Brookins")
| (m.Member.last_name=="Smith")
)
assertawaitquery.sort_by("age").all() == [member2, member3]
actual=awaitm.Member.find(
(m.Member.first_name=="Andrew") &~(m.Member.last_name=="Brookins")
).all()
assertactual== [member3]
@py_test_mark_asyncio
asyncdeftest_numeric_queries(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(m.Member.age==34).all()
assertactual== [member2]
actual=awaitm.Member.find(m.Member.age>34).sort_by("age").all()
assertactual== [member1, member3]
actual=awaitm.Member.find(m.Member.age<35).all()
assertactual== [member2]
actual=awaitm.Member.find(m.Member.age<=34).all()
assertactual== [member2]
actual=awaitm.Member.find(m.Member.age>=100).all()
assertactual== [member3]
actual=awaitm.Member.find(m.Member.age!=34).sort_by("age").all()
assertactual== [member1, member3]
actual=awaitm.Member.find(~(m.Member.age==100)).sort_by("age").all()
assertactual== [member2, member1]
actual= (
awaitm.Member.find(m.Member.age>30, m.Member.age<40).sort_by("age").all()
)
assertactual== [member2, member1]
@py_test_mark_asyncio
asyncdeftest_sorting(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(m.Member.age>34).sort_by("age").all()
assertactual== [member1, member3]
actual=awaitm.Member.find(m.Member.age>34).sort_by("-age").all()
assertactual== [member3, member1]
withpytest.raises(QueryNotSupportedError):
# This field does not exist.
awaitm.Member.find().sort_by("not-a-real-field").all()
withpytest.raises(QueryNotSupportedError):
# This field is not sortable.
awaitm.Member.find().sort_by("join_date").all()
@py_test_mark_asyncio
asyncdeftest_case_sensitive(members, m):
member1, member2, member3=members
actual=awaitm.Member.find(
m.Member.first_name=="Andrew"andm.Member.pk==member1.pk
).all()
assertactual== [member1]
actual=awaitm.Member.find(m.Member.first_name=="andrew").all()
assertactual== []
deftest_validates_required_fields(m):
# Raises ValidationError: last_name is required
# TODO: Test the error value
withpytest.raises(ValidationError):
try:
m.Member(id=0, first_name="Andrew", zipcode="97086", join_date=today)
exceptExceptionase:
raisee
deftest_validates_field(m):
# Raises ValidationError: join_date is not a date
# TODO: Test the error value
withpytest.raises(ValidationError):
m.Member(id=0, first_name="Andrew", last_name="Brookins", join_date="yesterday")
deftest_validation_passes(m):
member=m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="a@example.com",
join_date=today,
age=38,
bio="This is the bio field.",
)
assertmember.first_name=="Andrew"
@py_test_mark_asyncio
asyncdeftest_retrieve_first(m):
member=m.Member(
id=0,
first_name="Simon",
last_name="Prickett",
email="s@example.com",
join_date=today,
age=99,
bio="This is the bio field for this user.",
)
awaitmember.save()
member2=m.Member(
id=1,
first_name="Another",
last_name="Member",
email="m@example.com",
join_date=today,
age=98,
bio="This is the bio field for this user.",
)
awaitmember2.save()
member3=m.Member(
id=2,
first_name="Third",
last_name="Member",
email="t@example.com",
join_date=today,
age=97,
bio="This is the bio field for this user.",
)
awaitmember3.save()
first_one=awaitm.Member.find().sort_by("age").first()
assertfirst_one==member3
@py_test_mark_asyncio
asyncdeftest_saves_model_and_creates_pk(m):
member=m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="a@example.com",
join_date=today,
age=38,
bio="This is the bio field for this user.",
)
# Save a model instance to Redis
awaitmember.save()
member2=awaitm.Member.get(pk=member.id)
assertmember2==member
@py_test_mark_asyncio
asyncdeftest_all_pks(m):
member=m.Member(
id=0,
first_name="Simon",
last_name="Prickett",
email="s@example.com",
join_date=today,
age=97,
bio="This is a test user to be deleted.",
)
awaitmember.save()
member1=m.Member(
id=1,
first_name="Andrew",
last_name="Brookins",
email="a@example.com",
join_date=today,
age=38,
bio="This is a test user to be deleted.",
)
awaitmember1.save()
pk_list= []
asyncforpkinawaitm.Member.all_pks():
pk_list.append(pk)
assertsorted(pk_list) == ["0", "1"]
@py_test_mark_asyncio
asyncdeftest_all_pks_with_complex_pks(key_prefix):
classCity(HashModel):
name: str
classMeta:
global_key_prefix=key_prefix
model_key_prefix="city"
city1=City(
pk="ca:on:toronto",
name="Toronto",
)
awaitcity1.save()
city2=City(
pk="ca:qc:montreal",
name="Montreal",
)
awaitcity2.save()
pk_list= []
asyncforpkinawaitCity.all_pks():
pk_list.append(pk)
assertsorted(pk_list) == ["ca:on:toronto", "ca:qc:montreal"]
@py_test_mark_asyncio
asyncdeftest_delete(m):
member=m.Member(
id=0,
first_name="Simon",
last_name="Prickett",
email="s@example.com",
join_date=today,
age=97,
bio="This is a test user to be deleted.",
)
awaitmember.save()
response=awaitm.Member.delete(pk=member.id)
assertresponse==1
@py_test_mark_asyncio
asyncdeftest_expire(m):
member=m.Member(
id=0,
first_name="Expire",
last_name="Test",
email="e@example.com",
join_date=today,
age=93,
bio="This is a test user for expiry",
)
awaitmember.save()
awaitmember.expire(60)
ttl=awaitm.Member.db().ttl(member.key())
assertttl>0
deftest_raises_error_with_embedded_models(m):
classAddress(m.BaseHashModel):
address_line_1: str
address_line_2: Optional[str]
city: str
country: str
postal_code: str
withpytest.raises(RedisModelError):
classInvalidMember(m.BaseHashModel):
name: str=Field(index=True)
address: Address
deftest_raises_error_with_dataclasses(m):
@dataclasses.dataclass
classAddress:
address_line_1: str
withpytest.raises(RedisModelError):
classInvalidMember(m.BaseHashModel):
address: Address
deftest_raises_error_with_dicts(m):
withpytest.raises(RedisModelError):
classInvalidMember(m.BaseHashModel):
address: Dict[str, str]
deftest_raises_error_with_sets(m):
withpytest.raises(RedisModelError):
classInvalidMember(m.BaseHashModel):
friend_ids: Set[str]
deftest_raises_error_with_lists(m):
withpytest.raises(RedisModelError):
classInvalidMember(m.BaseHashModel):
friend_ids: List[str]
@py_test_mark_asyncio
asyncdeftest_saves_many(m):
member1=m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="a@example.com",
join_date=today,
age=38,
bio="This is the user bio.",
)
member2=m.Member(
id=1,
first_name="Kim",
last_name="Brookins",
email="k@example.com",
join_date=today,
age=34,
bio="This is the bio for Kim.",
)
members= [member1, member2]
result=awaitm.Member.add(members)
assertresult== [member1, member2]
assertawaitm.Member.get(pk=member1.id) ==member1
assertawaitm.Member.get(pk=member2.id) ==member2
@py_test_mark_asyncio
asyncdeftest_delete_many(m):
member1=m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="a@example.com",
join_date=today,
age=38,
bio="This is the user bio.",
)
member2=m.Member(
id=1,
first_name="Kim",
last_name="Brookins",
email="k@example.com",
join_date=today,
age=34,
bio="This is the bio for Kim.",
)
members= [member1, member2]
result=awaitm.Member.add(members)
assertresult== [member1, member2]
result=awaitm.Member.delete_many(members)
assertresult==2
withpytest.raises(NotFoundError):
awaitm.Member.get(pk=member1.key())
@py_test_mark_asyncio
asyncdeftest_updates_a_model(members, m):
member1, member2, member3=members
awaitmember1.update(last_name="Smith")
member=awaitm.Member.get(member1.id)
assertmember.last_name=="Smith"
@py_test_mark_asyncio
asyncdeftest_paginate_query(members, m):
member1, member2, member3=members
actual=awaitm.Member.find().sort_by("age").all(batch_size=1)
assertactual== [member2, member1, member3]
@py_test_mark_asyncio
asyncdeftest_access_result_by_index_cached(members, m):
member1, member2, member3=members
query=m.Member.find().sort_by("age")
# Load the cache, throw away the result.
assertquery._model_cache== []
awaitquery.execute()
assertquery._model_cache== [member2, member1, member3]
# Access an item that should be in the cache.
withmock.patch.object(query.model, "db") asmock_db:
assertawaitquery.get_item(0) ==member2
assertnotmock_db.called
@py_test_mark_asyncio
asyncdeftest_access_result_by_index_not_cached(members, m):
member1, member2, member3=members
query=m.Member.find().sort_by("age")
# Assert that we don't have any models in the cache yet -- we
# haven't made any requests of Redis.
assertquery._model_cache== []
assertawaitquery.get_item(0) ==member2
assertawaitquery.get_item(1) ==member1
assertawaitquery.get_item(2) ==member3
deftest_schema(m):
classAddress(m.BaseHashModel):
a_string: str=Field(index=True)
a_full_text_string: str=Field(index=True, full_text_search=True)
an_integer: int=Field(index=True, sortable=True)
a_float: float=Field(index=True)
another_integer: int
another_float: float
# We need to build the key prefix because it will differ based on whether
# these tests were copied into the tests_sync folder and unasynce'd.
key_prefix=Address.make_key(Address._meta.primary_key_pattern.format(pk=""))
assert (
Address.redisearch_schema()
==f"ON HASH PREFIX 1 {key_prefix} SCHEMA pk TAG SEPARATOR | a_string TAG SEPARATOR | a_full_text_string TAG SEPARATOR | a_full_text_string AS a_full_text_string_fts TEXT an_integer NUMERIC SORTABLE a_float NUMERIC"
)
@py_test_mark_asyncio
asyncdeftest_primary_key_model_error(m):
classCustomer(m.BaseHashModel):
id: int=Field(primary_key=True, index=True)
first_name: str=Field(primary_key=True, index=True)
last_name: str
bio: Optional[str]
awaitMigrator().run()
withpytest.raises(
RedisModelError, match="You must define only one primary key for a model"
):
_=Customer(
id=0,
first_name="Mahmoud",
last_name="Harmouch",
bio="Python developer, wanna work at Redis, Inc.",
)
@py_test_mark_asyncio
asyncdeftest_primary_pk_exists(m):
classCustomer1(m.BaseHashModel):
id: int
first_name: str
last_name: str
bio: Optional[str]
classCustomer2(m.BaseHashModel):
id: int=Field(primary_key=True, index=True)
first_name: str
last_name: str
bio: Optional[str]
awaitMigrator().run()
customer=Customer1(
id=0,
first_name="Mahmoud",
last_name="Harmouch",
bio="Python developer, wanna work at Redis, Inc.",
)
assert"pk"incustomer.__fields__
customer=Customer2(
id=1,
first_name="Kim",
last_name="Brookins",
bio="This is member 2 who can be quite anxious until you get to know them.",
)
assert"pk"notincustomer.__fields__
@py_test_mark_asyncio
asyncdeftest_count(members, m):
# member1, member2, member3 = members
actual_count=awaitm.Member.find(
(m.Member.first_name=="Andrew") & (m.Member.last_name=="Brookins")
| (m.Member.last_name=="Smith")
).count()
assertactual_count==2
actual_count=awaitm.Member.find(
m.Member.first_name=="Kim", m.Member.last_name=="Brookins"
).count()
assertactual_count==1
@py_test_mark_asyncio
asyncdeftest_type_with_union(members, m):
classTypeWithUnion(m.BaseHashModel):
field: Union[str, int]
twu_str=TypeWithUnion(field="hello world")
res=awaittwu_str.save()
assertres.pk==twu_str.pk
twu_str_rematerialized=awaitTypeWithUnion.get(twu_str.pk)
assert (
isinstance(twu_str_rematerialized.field, str)
andtwu_str_rematerialized.pk==twu_str.pk
)
twu_int=TypeWithUnion(field=42)
awaittwu_int.save()
twu_int_rematerialized=awaitTypeWithUnion.get(twu_int.pk)
# Note - we will not be able to automatically serialize an int back to this union type,
# since as far as we know from Redis this item is a string
asserttwu_int_rematerialized.pk==twu_int.pk
@py_test_mark_asyncio
asyncdeftest_type_with_uuid():
classTypeWithUuid(HashModel):
uuid: uuid.UUID
item=TypeWithUuid(uuid=uuid.uuid4())
awaititem.save()
@py_test_mark_asyncio
asyncdeftest_xfix_queries(members, m):
member1, member2, member3=members
result=awaitm.Member.find(
m.Member.first_name.startswith("And") andm.Member.last_name=="Brookins"
).first()
assertresult.last_name=="Brookins"
result=awaitm.Member.find(
m.Member.last_name.endswith("ins") andm.Member.last_name=="Brookins"
).first()
assertresult.last_name=="Brookins"
result=awaitm.Member.find(
m.Member.last_name.contains("ook") andm.Member.last_name=="Brookins"
).first()
assertresult.last_name=="Brookins"
result=awaitm.Member.find(
m.Member.bio%"great*"andm.Member.first_name=="Andrew"
).first()
assertresult.first_name=="Andrew"
result=awaitm.Member.find(
m.Member.bio%"*rty"andm.Member.first_name=="Andrew"
).first()
assertresult.first_name=="Andrew"
result=awaitm.Member.find(
m.Member.bio%"*eat*"andm.Member.first_name=="Andrew"
).first()
assertresult.first_name=="Andrew"
@py_test_mark_asyncio
asyncdeftest_none():
classModelWithNoneDefault(HashModel):
test: Optional[str] =Field(index=True, default=None)
classModelWithStringDefault(HashModel):
test: Optional[str] =Field(index=True, default="None")
awaitMigrator().run()
a=ModelWithNoneDefault()
awaita.save()
res=awaitModelWithNoneDefault.find(ModelWithNoneDefault.pk==a.pk).first()
assertres.testisNone
b=ModelWithStringDefault()
awaitb.save()
res=awaitModelWithStringDefault.find(ModelWithStringDefault.pk==b.pk).first()
assertres.test=="None"
@py_test_mark_asyncio
asyncdeftest_update_validation():
classTestUpdate(HashModel):
name: str
age: int
awaitMigrator().run()
t=TestUpdate(name="steve", age=34)
awaitt.save()
update_dict=dict()
update_dict["age"] ="cat"
withpytest.raises(ValidationError):
awaitt.update(**update_dict)
rematerialized=awaitTestUpdate.find(TestUpdate.pk==t.pk).first()
assertrematerialized.age==34
@py_test_mark_asyncio
asyncdeftest_literals():
fromtypingimportLiteral
classTestLiterals(HashModel):
flavor: Literal["apple", "pumpkin"] =Field(index=True, default="apple")
schema=TestLiterals.redisearch_schema()
key_prefix=TestLiterals.make_key(
TestLiterals._meta.primary_key_pattern.format(pk="")
)
assertschema== (
f"ON HASH PREFIX 1 {key_prefix} SCHEMA pk TAG SEPARATOR | flavor TAG SEPARATOR |"
)
awaitMigrator().run()
item=TestLiterals(flavor="pumpkin")
awaititem.save()
rematerialized=awaitTestLiterals.find(TestLiterals.flavor=="pumpkin").first()
assertrematerialized.pk==item.pk
@py_test_mark_asyncio
asyncdeftest_child_class_expression_proxy():
# https://github.com/redis/redis-om-python/issues/669 seeing weird issue with child classes initalizing all their undefined members as ExpressionProxies
classModel(HashModel):
first_name: str
last_name: str
age: int=Field(default=18)
bio: Optional[str] =Field(default=None)
classChild(Model):
other_name: str
# is_new: bool = Field(default=True)
awaitMigrator().run()
m=Child(first_name="Steve", last_name="Lorello", other_name="foo")
awaitm.save()
print(m.age)
assertm.age==18
rematerialized=awaitChild.find(Child.pk==m.pk).first()
assertrematerialized.age==18
assertrematerialized.bioisNone
@py_test_mark_asyncio
asyncdeftest_child_class_expression_proxy_with_mixin():
# https://github.com/redis/redis-om-python/issues/669 seeing weird issue with child classes initalizing all their undefined members as ExpressionProxies
classModel(RedisModel, abc.ABC):
first_name: str
last_name: str
age: int=Field(default=18)
bio: Optional[str] =Field(default=None)
classChild(Model, HashModel):
other_name: str
# is_new: bool = Field(default=True)
awaitMigrator().run()
m=Child(first_name="Steve", last_name="Lorello", other_name="foo")
awaitm.save()
print(m.age)
assertm.age==18