-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathtest_json_model.py
962 lines (766 loc) · 27.1 KB
/
test_json_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
# type: ignore
import abc
import dataclasses
import datetime
import decimal
import uuid
from collections import namedtuple
from typing import Dict, List, Optional, Set, Union
from unittest import mock
import pytest
import pytest_asyncio
from aredis_om import (
EmbeddedJsonModel,
Field,
JsonModel,
Migrator,
NotFoundError,
QueryNotSupportedError,
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.
from redis_om import has_redis_json
from tests._compat import EmailStr, PositiveInt, ValidationError
from .conftest import py_test_mark_asyncio
if not has_redis_json():
pytestmark = pytest.mark.skip
today = datetime.date.today()
@pytest_asyncio.fixture
async def m(key_prefix, redis):
class BaseJsonModel(JsonModel, abc.ABC):
class Meta:
global_key_prefix = key_prefix
class Note(EmbeddedJsonModel):
# TODO: This was going to be a full-text search example, but
# we can't index embedded documents for full-text search in
# the preview release.
description: str = Field(index=True)
created_on: datetime.datetime
class Address(EmbeddedJsonModel):
address_line_1: str
address_line_2: Optional[str] = None
city: str = Field(index=True)
state: str
country: str
postal_code: str = Field(index=True)
note: Optional[Note] = None
class Item(EmbeddedJsonModel):
price: decimal.Decimal
name: str = Field(index=True)
class Order(EmbeddedJsonModel):
items: List[Item]
created_on: datetime.datetime
class Member(BaseJsonModel):
first_name: str = Field(index=True)
last_name: str = Field(index=True)
email: Optional[EmailStr] = Field(index=True, default=None)
join_date: datetime.date
age: Optional[PositiveInt] = Field(index=True, default=None)
bio: Optional[str] = Field(index=True, full_text_search=True, default="")
# Creates an embedded model.
address: Address
# Creates an embedded list of models.
orders: Optional[List[Order]] = None
await Migrator().run()
return namedtuple(
"Models", ["BaseJsonModel", "Note", "Address", "Item", "Order", "Member"]
)(BaseJsonModel, Note, Address, Item, Order, Member)
@pytest.fixture()
def address(m):
try:
yield m.Address(
address_line_1="1 Main St.",
city="Portland",
state="OR",
country="USA",
postal_code="11111",
)
except Exception as e:
raise e
@pytest_asyncio.fixture()
async def members(address, m):
member1 = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
age=38,
join_date=today,
address=address,
)
member2 = m.Member(
first_name="Kim",
last_name="Brookins",
email="[email protected]",
age=34,
join_date=today,
address=address,
)
member3 = m.Member(
first_name="Andrew",
last_name="Smith",
email="[email protected]",
age=100,
join_date=today,
address=address,
)
await member1.save()
await member2.save()
await member3.save()
yield member1, member2, member3
@py_test_mark_asyncio
async def test_validate_bad_email(address, m):
# Raises ValidationError as email is malformed
with pytest.raises(ValidationError):
m.Member(
first_name="Andrew",
last_name="Brookins",
zipcode="97086",
join_date=today,
email="foobarbaz",
)
@py_test_mark_asyncio
async def test_validate_bad_age(address, m):
# Raises ValidationError as email is malformed
with pytest.raises(ValidationError):
m.Member(
first_name="Andrew",
last_name="Brookins",
zipcode="97086",
join_date=today,
email="[email protected]",
address=address,
age=-5,
)
@py_test_mark_asyncio
async def test_validates_required_fields(address, m):
# Raises ValidationError address is required
with pytest.raises(ValidationError):
m.Member(
first_name="Andrew",
last_name="Brookins",
zipcode="97086",
join_date=today,
)
@py_test_mark_asyncio
async def test_validates_field(address, m):
# Raises ValidationError: join_date is not a date
with pytest.raises(ValidationError):
m.Member(
first_name="Andrew",
last_name="Brookins",
join_date="yesterday",
address=address,
)
@py_test_mark_asyncio
async def test_validation_passes(address, m):
member = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
address=address,
)
assert member.first_name == "Andrew"
@py_test_mark_asyncio
async def test_saves_model_and_creates_pk(address, m, redis):
await Migrator().run()
member = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
address=address,
)
# Save a model instance to Redis
await member.save()
member2 = await m.Member.get(member.pk)
assert member2 == member
assert member2.address == address
@py_test_mark_asyncio
async def test_all_pks(address, m, redis):
member = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
address=address,
)
await member.save()
member1 = m.Member(
first_name="Simon",
last_name="Prickett",
email="[email protected]",
join_date=today,
age=99,
address=address,
)
await member1.save()
pk_list = []
async for pk in await m.Member.all_pks():
pk_list.append(pk)
assert sorted(pk_list) == sorted([member.pk, member1.pk])
@py_test_mark_asyncio
async def test_all_pks_with_complex_pks(key_prefix):
class City(JsonModel):
name: str
class Meta:
global_key_prefix = key_prefix
model_key_prefix = "city"
city1 = City(
pk="ca:on:toronto",
name="Toronto",
)
await city1.save()
city2 = City(
pk="ca:qc:montreal",
name="Montreal",
)
await city2.save()
pk_list = []
async for pk in await City.all_pks():
pk_list.append(pk)
assert sorted(pk_list) == ["ca:on:toronto", "ca:qc:montreal"]
@py_test_mark_asyncio
async def test_delete(address, m, redis):
member = m.Member(
first_name="Simon",
last_name="Prickett",
email="[email protected]",
join_date=today,
age=38,
address=address,
)
await member.save()
response = await m.Member.delete(member.pk)
assert response == 1
@py_test_mark_asyncio
async def test_saves_many_implicit_pipeline(address, m):
member1 = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
address=address,
age=38,
)
member2 = m.Member(
first_name="Kim",
last_name="Brookins",
email="[email protected]",
join_date=today,
address=address,
age=34,
)
members = [member1, member2]
result = await m.Member.add(members)
assert result == [member1, member2]
assert await m.Member.get(pk=member1.pk) == member1
assert await m.Member.get(pk=member2.pk) == member2
@py_test_mark_asyncio
async def test_saves_many_explicit_transaction(address, m):
member1 = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
address=address,
age=38,
)
member2 = m.Member(
first_name="Kim",
last_name="Brookins",
email="[email protected]",
join_date=today,
address=address,
age=34,
)
members = [member1, member2]
result = await m.Member.add(members)
assert result == [member1, member2]
assert await m.Member.get(pk=member1.pk) == member1
assert await m.Member.get(pk=member2.pk) == member2
# Test the explicit pipeline path -- here, we add multiple Members
# using a single Redis transaction, with MULTI/EXEC.
async with m.Member.db().pipeline(transaction=True) as pipeline:
await m.Member.add(members, pipeline=pipeline)
assert result == [member1, member2]
assert await pipeline.execute() == [True, True]
assert await m.Member.get(pk=member1.pk) == member1
assert await m.Member.get(pk=member2.pk) == member2
@py_test_mark_asyncio
async def test_delete_many_implicit_pipeline(address, m):
member1 = m.Member(
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
address=address,
age=38,
)
member2 = m.Member(
first_name="Kim",
last_name="Brookins",
email="[email protected]",
join_date=today,
address=address,
age=34,
)
members = [member1, member2]
result = await m.Member.add(members)
assert result == [member1, member2]
result = await m.Member.delete_many(members)
assert result == 2
with pytest.raises(NotFoundError):
await m.Member.get(pk=member2.pk)
async def save(members):
for m in members:
await m.save()
return members
@py_test_mark_asyncio
async def test_updates_a_model(members, m):
member1, member2, member3 = await save(members)
# Update a field directly on the model
await member1.update(last_name="Apples to oranges")
member = await m.Member.get(member1.pk)
assert member.last_name == "Apples to oranges"
# Update a field in an embedded model
await member2.update(address__city="Happy Valley")
member = await m.Member.get(member2.pk)
assert member.address.city == "Happy Valley"
@py_test_mark_asyncio
async def test_paginate_query(members, m):
member1, member2, member3 = members
actual = await m.Member.find().sort_by("age").all(batch_size=1)
assert actual == [member2, member1, member3]
@py_test_mark_asyncio
async def test_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.
assert query._model_cache == []
await query.execute()
assert query._model_cache == [member2, member1, member3]
# Access an item that should be in the cache.
with mock.patch.object(query.model, "db") as mock_db:
assert await query.get_item(0) == member2
assert not mock_db.called
@py_test_mark_asyncio
async def test_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.
assert query._model_cache == []
assert await query.get_item(0) == member2
assert await query.get_item(1) == member1
assert await query.get_item(2) == member3
@py_test_mark_asyncio
async def test_in_query(members, m):
member1, member2, member3 = members
actual = await (
m.Member.find(m.Member.pk << [member1.pk, member2.pk, member3.pk])
.sort_by("age")
.all()
)
assert actual == [member2, member1, member3]
@py_test_mark_asyncio
async def test_not_in_query(members, m):
member1, member2, member3 = members
actual = await (
m.Member.find(m.Member.pk >> [member2.pk, member3.pk]).sort_by("age").all()
)
assert actual == [member1]
@py_test_mark_asyncio
async def test_update_query(members, m):
member1, member2, member3 = members
await m.Member.find(m.Member.pk << [member1.pk, member2.pk, member3.pk]).update(
first_name="Bobby"
)
actual = await (
m.Member.find(m.Member.pk << [member1.pk, member2.pk, member3.pk])
.sort_by("age")
.all()
)
assert len(actual) == 3
assert all([m.first_name == "Bobby" for m in actual])
@py_test_mark_asyncio
async def test_exact_match_queries(members, m):
member1, member2, member3 = members
actual = await m.Member.find(m.Member.last_name == "Brookins").sort_by("age").all()
assert actual == [member2, member1]
actual = await m.Member.find(
(m.Member.last_name == "Brookins") & ~(m.Member.first_name == "Andrew")
).all()
assert actual == [member2]
actual = await m.Member.find(~(m.Member.last_name == "Brookins")).all()
assert actual == [member3]
actual = await m.Member.find(m.Member.last_name != "Brookins").all()
assert actual == [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()
)
assert actual == [member2, member1]
actual = await m.Member.find(
m.Member.first_name == "Kim", m.Member.last_name == "Brookins"
).all()
assert actual == [member2]
actual = (
await m.Member.find(m.Member.address.city == "Portland").sort_by("age").all()
)
assert actual == [member2, member1, member3]
@py_test_mark_asyncio
async def test_recursive_query_expression_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()
)
assert actual == [member2, member1, member3]
@py_test_mark_asyncio
async def test_recursive_query_field_resolution(members, m):
member1, _, _ = members
member1.address.note = m.Note(
description="Weird house", created_on=datetime.datetime.now()
)
await member1.save()
actual = await m.Member.find(
m.Member.address.note.description == "Weird house"
).all()
assert actual == [member1]
member1.orders = [
m.Order(
items=[m.Item(price=10.99, name="Ball")],
total=10.99,
created_on=datetime.datetime.now(),
)
]
await member1.save()
actual = await m.Member.find(m.Member.orders.items.name == "Ball").all()
assert actual == [member1]
assert actual[0].orders[0].items[0].name == "Ball"
@py_test_mark_asyncio
async def test_full_text_search(members, m):
member1, member2, _ = members
await member1.update(bio="Hates sunsets, likes beaches")
await member2.update(bio="Hates beaches, likes forests")
actual = await m.Member.find(m.Member.bio % "beaches").sort_by("age").all()
assert actual == [member2, member1]
actual = await m.Member.find(m.Member.bio % "forests").all()
assert actual == [member2]
@py_test_mark_asyncio
async def test_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()
)
assert actual == [member1, member3]
@py_test_mark_asyncio
async def test_tag_queries_punctuation(address, m):
member1 = m.Member(
first_name="Andrew, the Michael",
last_name="St. Brookins-on-Pier",
email="a|[email protected]", # NOTE: This string uses the TAG field separator.
age=38,
join_date=today,
address=address,
)
await member1.save()
member2 = m.Member(
first_name="Bob",
last_name="the Villain",
email="a|[email protected]", # NOTE: This string uses the TAG field separator.
age=38,
join_date=today,
address=address,
)
await member2.save()
assert (
await m.Member.find(m.Member.first_name == "Andrew, the Michael").first()
== member1
)
assert (
await m.Member.find(m.Member.last_name == "St. Brookins-on-Pier").first()
== 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.
assert await m.Member.find(m.Member.email == "a|[email protected]").all() == [member1]
assert await m.Member.find(m.Member.email == "a|[email protected]").all() == [
member2
]
@py_test_mark_asyncio
async def test_tag_queries_negation(members, m):
member1, member2, member3 = members
"""
┌first_name
NOT EQ┤
└Andrew
"""
query = m.Member.find(~(m.Member.first_name == "Andrew"))
assert await query.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")
)
assert await query.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"))
)
assert await query.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")
)
assert await query.sort_by("age").all() == [member2, member3]
actual = await m.Member.find(
(m.Member.first_name == "Andrew") & ~(m.Member.last_name == "Brookins")
).all()
assert actual == [member3]
@py_test_mark_asyncio
async def test_numeric_queries(members, m):
member1, member2, member3 = members
actual = await m.Member.find(m.Member.age == 34).all()
assert actual == [member2]
actual = await m.Member.find(m.Member.age > 34).sort_by("age").all()
assert actual == [member1, member3]
actual = await m.Member.find(m.Member.age < 35).all()
assert actual == [member2]
actual = await m.Member.find(m.Member.age <= 34).all()
assert actual == [member2]
actual = await m.Member.find(m.Member.age >= 100).all()
assert actual == [member3]
actual = await m.Member.find(~(m.Member.age == 100)).sort_by("age").all()
assert actual == [member2, member1]
actual = (
await m.Member.find(m.Member.age > 30, m.Member.age < 40).sort_by("age").all()
)
assert actual == [member2, member1]
actual = await m.Member.find(m.Member.age != 34).sort_by("age").all()
assert actual == [member1, member3]
@py_test_mark_asyncio
async def test_sorting(members, m):
member1, member2, member3 = members
actual = await m.Member.find(m.Member.age > 34).sort_by("age").all()
assert actual == [member1, member3]
actual = await m.Member.find(m.Member.age > 34).sort_by("-age").all()
assert actual == [member3, member1]
with pytest.raises(QueryNotSupportedError):
# This field does not exist.
await m.Member.find().sort_by("not-a-real-field").all()
with pytest.raises(QueryNotSupportedError):
# This field is not sortable.
await m.Member.find().sort_by("join_date").all()
@py_test_mark_asyncio
async def test_not_found(m):
with pytest.raises(NotFoundError):
# This ID does not exist.
await m.Member.get(1000)
@py_test_mark_asyncio
async def test_list_field_limitations(m, redis):
with pytest.raises(RedisModelError):
class SortableTarotWitch(m.BaseJsonModel):
# We support indexing lists of strings for quality and membership
# queries. Sorting is not supported, but is planned.
tarot_cards: List[str] = Field(index=True, sortable=True)
with pytest.raises(RedisModelError):
class SortableFullTextSearchAlchemicalWitch(m.BaseJsonModel):
# We don't support indexing a list of strings for full-text search
# queries. Support for this feature is not planned.
potions: List[str] = Field(index=True, full_text_search=True)
with pytest.raises(RedisModelError):
class NumerologyWitch(m.BaseJsonModel):
# We don't support indexing a list of numbers. Support for this
# feature is To Be Determined.
lucky_numbers: List[int] = Field(index=True)
with pytest.raises(RedisModelError):
class ReadingWithPrice(EmbeddedJsonModel):
gold_coins_charged: int = Field(index=True)
class TarotWitchWhoCharges(m.BaseJsonModel):
tarot_cards: List[str] = Field(index=True)
# The preview release does not support indexing numeric fields on models
# found within a list or tuple. This is the same limitation that stops
# us from indexing plain lists (or tuples) containing numeric values.
# The fate of this feature is To Be Determined.
readings: List[ReadingWithPrice]
class TarotWitch(m.BaseJsonModel):
# We support indexing lists of strings for quality and membership
# queries. Sorting is not supported, but is planned.
tarot_cards: List[str] = Field(index=True)
# We need to import and run this manually because we defined
# our model classes within a function that runs after the test
# suite's migrator has already looked for migrations to run.
await Migrator().run()
witch = TarotWitch(tarot_cards=["death"])
await witch.save()
actual = await TarotWitch.find(TarotWitch.tarot_cards << "death").all()
assert actual == [witch]
@py_test_mark_asyncio
async def test_allows_dataclasses(m):
@dataclasses.dataclass
class Address:
address_line_1: str
class ValidMember(m.BaseJsonModel):
address: Address
address = Address(address_line_1="hey")
member = ValidMember(address=address)
await member.save()
member2 = await ValidMember.get(member.pk)
assert member2 == member
assert member2.address.address_line_1 == "hey"
@py_test_mark_asyncio
async def test_allows_and_serializes_dicts(m):
class ValidMember(m.BaseJsonModel):
address: Dict[str, str]
member = ValidMember(address={"address_line_1": "hey"})
await member.save()
member2 = await ValidMember.get(member.pk)
assert member2 == member
assert member2.address["address_line_1"] == "hey"
@py_test_mark_asyncio
async def test_allows_and_serializes_sets(m):
class ValidMember(m.BaseJsonModel):
friend_ids: Set[int]
member = ValidMember(friend_ids={1, 2})
await member.save()
member2 = await ValidMember.get(member.pk)
assert member2 == member
assert member2.friend_ids == {1, 2}
@py_test_mark_asyncio
async def test_allows_and_serializes_lists(m):
class ValidMember(m.BaseJsonModel):
friend_ids: List[int]
member = ValidMember(friend_ids=[1, 2])
await member.save()
member2 = await ValidMember.get(member.pk)
assert member2 == member
assert member2.friend_ids == [1, 2]
@py_test_mark_asyncio
async def test_schema(m, key_prefix):
# 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 = m.Member.make_key(m.Member._meta.primary_key_pattern.format(pk=""))
assert (
m.Member.redisearch_schema()
== f"ON JSON PREFIX 1 {key_prefix} SCHEMA $.pk AS pk TAG SEPARATOR | $.first_name AS first_name TAG SEPARATOR | $.last_name AS last_name TAG SEPARATOR | $.email AS email TAG SEPARATOR | $.age AS age NUMERIC $.bio AS bio TAG SEPARATOR | $.bio AS bio_fts TEXT $.address.pk AS address_pk TAG SEPARATOR | $.address.city AS address_city TAG SEPARATOR | $.address.postal_code AS address_postal_code TAG SEPARATOR | $.address.note.pk AS address_note_pk TAG SEPARATOR | $.address.note.description AS address_note_description TAG SEPARATOR | $.orders[*].pk AS orders_pk TAG SEPARATOR | $.orders[*].items[*].pk AS orders_items_pk TAG SEPARATOR | $.orders[*].items[*].name AS orders_items_name TAG SEPARATOR |"
)
@py_test_mark_asyncio
async def test_count(members, m):
# member1, member2, member3 = members
actual_count = await m.Member.find(
(m.Member.first_name == "Andrew") & (m.Member.last_name == "Brookins")
| (m.Member.last_name == "Smith")
).count()
assert actual_count == 2
actual_count = await m.Member.find(
m.Member.first_name == "Kim", m.Member.last_name == "Brookins"
).count()
assert actual_count == 1
@py_test_mark_asyncio
async def test_type_with_union(members, m):
class TypeWithUnion(m.BaseJsonModel):
field: Union[str, int]
twu_str = TypeWithUnion(field="hello world")
res = await twu_str.save()
assert res.pk == twu_str.pk
twu_str_rematerialized = await TypeWithUnion.get(twu_str.pk)
assert (
isinstance(twu_str_rematerialized.field, str)
and twu_str_rematerialized.pk == twu_str.pk
)
twu_int = TypeWithUnion(field=42)
await twu_int.save()
twu_int_rematerialized = await TypeWithUnion.get(twu_int.pk)
assert (
isinstance(twu_int_rematerialized.field, int)
and twu_int_rematerialized.pk == twu_int.pk
)
@py_test_mark_asyncio
async def test_type_with_uuid():
class TypeWithUuid(JsonModel):
uuid: uuid.UUID
item = TypeWithUuid(uuid=uuid.uuid4())
await item.save()
@py_test_mark_asyncio
async def test_xfix_queries(m):
await m.Member(
first_name="Steve",
last_name="Lorello",
email="[email protected]",
join_date=today,
bio="Steve is a two-bit hacker who loves Redis.",
address=m.Address(
address_line_1="42 foo bar lane",
city="Satellite Beach",
state="FL",
country="USA",
postal_code="32999",
),
age=34,
).save()
result = await m.Member.find(m.Member.first_name.startswith("Ste")).first()
assert result.first_name == "Steve"
result = await m.Member.find(m.Member.last_name.endswith("llo")).first()
assert result.first_name == "Steve"
result = await m.Member.find(m.Member.address.city.contains("llite")).first()
assert result.first_name == "Steve"
result = await m.Member.find(m.Member.bio % "tw*").first()
assert result.first_name == "Steve"
result = await m.Member.find(m.Member.bio % "*cker").first()
assert result.first_name == "Steve"
result = await m.Member.find(m.Member.bio % "*ack*").first()
assert result.first_name == "Steve"