-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathtest_hash_model.py
918 lines (714 loc) · 24.1 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
# 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 (
Field,
HashModel,
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_redisearch
from tests._compat import ValidationError
from .conftest import py_test_mark_asyncio
if not has_redisearch():
pytestmark = pytest.mark.skip
today = datetime.date.today()
@pytest_asyncio.fixture
async def m(key_prefix, redis):
class BaseHashModel(HashModel, abc.ABC):
class Meta:
global_key_prefix = key_prefix
class Order(BaseHashModel):
total: decimal.Decimal
currency: str
created_on: datetime.datetime
class Member(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)
class Meta:
model_key_prefix = "member"
primary_key_pattern = ""
await Migrator().run()
return namedtuple("Models", ["BaseHashModel", "Order", "Member"])(
BaseHashModel, Order, Member
)
@pytest_asyncio.fixture
async def members(m):
member1 = m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
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="[email protected]",
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="[email protected]",
age=100,
join_date=today,
bio="This is member 3 who is a funny and lively sort of person.",
)
await member1.save()
await member2.save()
await member3.save()
yield member1, member2, member3
@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.id == 0).all()
assert actual == [member1]
@py_test_mark_asyncio
async def test_delete_non_exist(members, m):
member1, member2, member3 = members
actual = await m.Member.find(
(m.Member.last_name == "Brookins") & ~(m.Member.first_name == "Andrew")
).all()
assert actual == [member2]
assert (
1
== await m.Member.find(
(m.Member.last_name == "Brookins") & ~(m.Member.first_name == "Andrew")
).delete()
)
assert (
0
== await m.Member.find(
(m.Member.last_name == "Brookins") & ~(m.Member.first_name == "Andrew")
).delete()
)
@py_test_mark_asyncio
async def test_full_text_search_queries(members, m):
member1, member2, member3 = members
actual = await m.Member.find(m.Member.bio % "great").all()
assert actual == [member1]
actual = await m.Member.find(~(m.Member.bio % "anxious")).sort_by("age").all()
assert actual == [member1, member3]
@py_test_mark_asyncio
@pytest.mark.xfail(strict=False)
async def test_pagination_queries(members, m):
member1, member2, member3 = members
actual = await m.Member.find(m.Member.last_name == "Brookins").page()
assert actual == [member1, member2]
actual = await m.Member.find().page(1, 1)
assert actual == [member2]
actual = await m.Member.find().page(0, 1)
assert actual == [member1]
@py_test_mark_asyncio
async def test_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()
)
assert actual == [member2, member1, member3]
@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(m):
member1 = m.Member(
id=0,
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,
bio="This is a test user on our system.",
)
await member1.save()
member2 = m.Member(
id=1,
first_name="Bob",
last_name="the Villain",
email="a|[email protected]", # NOTE: This string uses the TAG field separator.
age=38,
join_date=today,
bio="This is a villain, they are a really bad person!",
)
await member2.save()
result = await m.Member.find(m.Member.first_name == "Andrew, the Michael").first()
assert result == member1
result = await m.Member.find(m.Member.last_name == "St. Brookins-on-Pier").first()
assert result == 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 = await m.Member.find(m.Member.email == "a|[email protected]").all()
assert results == [member1]
results = await m.Member.find(m.Member.email == "a|[email protected]").all()
assert results == [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 != 34).sort_by("age").all()
assert actual == [member1, 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]
@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_case_sensitive(members, m):
member1, member2, member3 = members
actual = await m.Member.find(
m.Member.first_name == "Andrew" and m.Member.pk == member1.pk
).all()
assert actual == [member1]
actual = await m.Member.find(m.Member.first_name == "andrew").all()
assert actual == []
def test_validates_required_fields(m):
# Raises ValidationError: last_name is required
# TODO: Test the error value
with pytest.raises(ValidationError):
try:
m.Member(id=0, first_name="Andrew", zipcode="97086", join_date=today)
except Exception as e:
raise e
def test_validates_field(m):
# Raises ValidationError: join_date is not a date
# TODO: Test the error value
with pytest.raises(ValidationError):
m.Member(id=0, first_name="Andrew", last_name="Brookins", join_date="yesterday")
def test_validation_passes(m):
member = m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
bio="This is the bio field.",
)
assert member.first_name == "Andrew"
@py_test_mark_asyncio
async def test_retrieve_first(m):
member = m.Member(
id=0,
first_name="Simon",
last_name="Prickett",
email="[email protected]",
join_date=today,
age=99,
bio="This is the bio field for this user.",
)
await member.save()
member2 = m.Member(
id=1,
first_name="Another",
last_name="Member",
email="[email protected]",
join_date=today,
age=98,
bio="This is the bio field for this user.",
)
await member2.save()
member3 = m.Member(
id=2,
first_name="Third",
last_name="Member",
email="[email protected]",
join_date=today,
age=97,
bio="This is the bio field for this user.",
)
await member3.save()
first_one = await m.Member.find().sort_by("age").first()
assert first_one == member3
@py_test_mark_asyncio
async def test_saves_model_and_creates_pk(m):
member = m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
bio="This is the bio field for this user.",
)
# Save a model instance to Redis
await member.save()
member2 = await m.Member.get(pk=member.id)
assert member2 == member
@py_test_mark_asyncio
async def test_all_pks(m):
member = m.Member(
id=0,
first_name="Simon",
last_name="Prickett",
email="[email protected]",
join_date=today,
age=97,
bio="This is a test user to be deleted.",
)
await member.save()
member1 = m.Member(
id=1,
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
bio="This is a test user to be deleted.",
)
await member1.save()
pk_list = []
async for pk in await m.Member.all_pks():
pk_list.append(pk)
assert sorted(pk_list) == ["0", "1"]
@py_test_mark_asyncio
async def test_all_pks_with_complex_pks(key_prefix):
class City(HashModel):
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(m):
member = m.Member(
id=0,
first_name="Simon",
last_name="Prickett",
email="[email protected]",
join_date=today,
age=97,
bio="This is a test user to be deleted.",
)
await member.save()
response = await m.Member.delete(pk=member.id)
assert response == 1
@py_test_mark_asyncio
async def test_expire(m):
member = m.Member(
id=0,
first_name="Expire",
last_name="Test",
email="[email protected]",
join_date=today,
age=93,
bio="This is a test user for expiry",
)
await member.save()
await member.expire(60)
ttl = await m.Member.db().ttl(member.key())
assert ttl > 0
def test_raises_error_with_embedded_models(m):
class Address(m.BaseHashModel):
address_line_1: str
address_line_2: Optional[str]
city: str
country: str
postal_code: str
with pytest.raises(RedisModelError):
class InvalidMember(m.BaseHashModel):
name: str = Field(index=True)
address: Address
def test_raises_error_with_dataclasses(m):
@dataclasses.dataclass
class Address:
address_line_1: str
with pytest.raises(RedisModelError):
class InvalidMember(m.BaseHashModel):
address: Address
def test_raises_error_with_dicts(m):
with pytest.raises(RedisModelError):
class InvalidMember(m.BaseHashModel):
address: Dict[str, str]
def test_raises_error_with_sets(m):
with pytest.raises(RedisModelError):
class InvalidMember(m.BaseHashModel):
friend_ids: Set[str]
def test_raises_error_with_lists(m):
with pytest.raises(RedisModelError):
class InvalidMember(m.BaseHashModel):
friend_ids: List[str]
@py_test_mark_asyncio
async def test_saves_many(m):
member1 = m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
bio="This is the user bio.",
)
member2 = m.Member(
id=1,
first_name="Kim",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=34,
bio="This is the bio for Kim.",
)
members = [member1, member2]
result = await m.Member.add(members)
assert result == [member1, member2]
assert await m.Member.get(pk=member1.id) == member1
assert await m.Member.get(pk=member2.id) == member2
@py_test_mark_asyncio
async def test_delete_many(m):
member1 = m.Member(
id=0,
first_name="Andrew",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=38,
bio="This is the user bio.",
)
member2 = m.Member(
id=1,
first_name="Kim",
last_name="Brookins",
email="[email protected]",
join_date=today,
age=34,
bio="This is the bio for Kim.",
)
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=member1.key())
@py_test_mark_asyncio
async def test_updates_a_model(members, m):
member1, member2, member3 = members
await member1.update(last_name="Smith")
member = await m.Member.get(member1.id)
assert member.last_name == "Smith"
@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
def test_schema(m):
class Address(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
async def test_primary_key_model_error(m):
class Customer(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]
await Migrator().run()
with pytest.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
async def test_primary_pk_exists(m):
class Customer1(m.BaseHashModel):
id: int
first_name: str
last_name: str
bio: Optional[str]
class Customer2(m.BaseHashModel):
id: int = Field(primary_key=True, index=True)
first_name: str
last_name: str
bio: Optional[str]
await Migrator().run()
customer = Customer1(
id=0,
first_name="Mahmoud",
last_name="Harmouch",
bio="Python developer, wanna work at Redis, Inc.",
)
assert "pk" in customer.__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" not in customer.__fields__
@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.BaseHashModel):
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)
# 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
assert twu_int_rematerialized.pk == twu_int.pk
@py_test_mark_asyncio
async def test_type_with_uuid():
class TypeWithUuid(HashModel):
uuid: uuid.UUID
item = TypeWithUuid(uuid=uuid.uuid4())
await item.save()
@py_test_mark_asyncio
async def test_xfix_queries(members, m):
member1, member2, member3 = members
result = await m.Member.find(m.Member.first_name.startswith("And")).first()
assert result.last_name == "Brookins"
result = await m.Member.find(m.Member.last_name.endswith("ins")).first()
assert result.last_name == "Brookins"
result = await m.Member.find(m.Member.last_name.contains("ook")).first()
assert result.last_name == "Brookins"
result = await m.Member.find(m.Member.bio % "great*").first()
assert result.first_name == "Andrew"
result = await m.Member.find(m.Member.bio % "*rty").first()
assert result.first_name == "Andrew"
result = await m.Member.find(m.Member.bio % "*eat*").first()
assert result.first_name == "Andrew"
@py_test_mark_asyncio
async def test_none():
class ModelWithNoneDefault(HashModel):
test: Optional[str] = Field(index=True, default=None)
class ModelWithStringDefault(HashModel):
test: Optional[str] = Field(index=True, default="None")
await Migrator().run()
a = ModelWithNoneDefault()
await a.save()
res = await ModelWithNoneDefault.find(ModelWithNoneDefault.pk == a.pk).first()
assert res.test is None
b = ModelWithStringDefault()
await b.save()
res = await ModelWithStringDefault.find(ModelWithStringDefault.pk == b.pk).first()
assert res.test == "None"
async def test_update_validation():
class TestUpdate(HashModel):
name: str
age: int
await Migrator().run()
t = TestUpdate(name="steve", age=34)
await t.save()
update_dict = dict()
update_dict["age"] = "cat"
with pytest.raises(ValidationError):
await t.update(**update_dict)
rematerialized = await TestUpdate.find(TestUpdate.pk == t.pk).first()
assert rematerialized.age == 34