File: test_model_logic.py

package info (click to toggle)
python-odmantic 1.0.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 1,640 kB
  • sloc: python: 8,547; sh: 37; makefile: 34; xml: 13; javascript: 3
file content (734 lines) | stat: -rw-r--r-- 19,750 bytes parent folder | download | duplicates (2)
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
from typing import Dict, List, Optional, Tuple

import pytest
from bson.objectid import ObjectId
from inline_snapshot import snapshot
from pydantic import ValidationError, model_validator, root_validator
from pydantic.main import BaseModel

from odmantic.exceptions import DocumentParsingError
from odmantic.field import Field
from odmantic.model import EmbeddedModel, Model
from odmantic.reference import Reference
from tests.integration.utils import redact_objectid
from tests.zoo.person import PersonModel


def test_repr_model():
    class M(Model):
        a: int

    instance = M(a=5)
    assert repr(instance) == f"M(id={repr(instance.id)}, a=5)"


def test_repr_embedded_model():
    class M(EmbeddedModel):
        a: int

    instance = M(a=5)
    assert repr(instance) == "M(a=5)"


def test_fields_modified_no_modification():
    class M(Model):
        f: int

    instance = M(f=0)
    assert instance.__fields_modified__ == set(["f", "id"])


def test_fields_embedded_modified_no_modification():
    class M(EmbeddedModel):
        f: int

    instance = M(f=0)
    assert instance.__fields_modified__ == set(["f"])


def test_fields_modified_with_default():
    class M(Model):
        f: int = 5

    instance = M(f=0)
    assert instance.__fields_modified__ == set(["f", "id"])


@pytest.mark.parametrize("model_cls", [Model, EmbeddedModel])
def test_fields_modified_one_update(model_cls):
    class M(model_cls):  # type: ignore
        f: int

    instance = M(f=0)
    instance.__fields_modified__.clear()
    instance.f = 1
    assert instance.__fields_modified__ == set(["f"])


def test_field_update_with_invalid_data_type():
    class M(Model):
        f: int

    instance = M(f=0)
    with pytest.raises(ValidationError):
        instance.f = "aa"  # type: ignore


def test_field_update_with_invalid_data():
    class M(Model):
        f: int = Field(gt=0)

    instance = M(f=1)
    with pytest.raises(ValidationError):
        instance.f = -1


def test_validate_does_not_copy():
    instance = PersonModel(first_name="Jean", last_name="Pierre")
    assert PersonModel.validate(instance) is instance


def test_validate_from_dict():
    instance = PersonModel.validate({"first_name": "Jean", "last_name": "Pierre"})
    assert isinstance(instance, PersonModel)
    assert instance.first_name == "Jean" and instance.last_name == "Pierre"


def test_fields_modified_on_construction():
    instance = PersonModel(first_name="Jean", last_name="Pierre")
    assert instance.__fields_modified__ == set(["first_name", "last_name", "id"])


def test_fields_modified_on_document_parsing():
    instance = PersonModel.model_validate_doc(
        {"_id": ObjectId(), "first_name": "Jackie", "last_name": "Chan"}
    )
    assert instance.__fields_modified__ == set(["first_name", "last_name", "id"])


def test_document_parsing_error_keyname():
    class M(Model):
        field: str = Field(key_name="custom")

    id = ObjectId()
    with pytest.raises(DocumentParsingError) as exc_info:
        M.model_validate_doc({"_id": id})
    assert redact_objectid(str(exc_info.value), id) == snapshot(
        """\
1 validation error for M
field
  Key 'custom' not found in document [type=odmantic::key_not_found_in_document, input_value={'_id': ObjectId('<ObjectId>')}, input_type=dict]\
"""  # noqa: E501
    )


def test_document_parsing_error_embedded_keyname():
    class F(EmbeddedModel):
        a: int

    class E(EmbeddedModel):
        f: F

    class M(Model):
        e: E

    with pytest.raises(DocumentParsingError) as exc_info:
        M.model_validate_doc({"_id": ObjectId(), "e": {"f": {}}})
    assert str(exc_info.value) == snapshot(
        """\
1 validation error for M
e.f.a
  Key 'a' not found in document [type=odmantic::key_not_found_in_document, input_value={}, input_type=dict]\
"""  # noqa: E501
    )


def test_embedded_document_parsing_error():
    class E(EmbeddedModel):
        f: int

    with pytest.raises(DocumentParsingError) as exc_info:
        E.model_validate_doc({})
    assert str(exc_info.value) == snapshot(
        """\
1 validation error for E
f
  Key 'f' not found in document [type=odmantic::key_not_found_in_document, input_value={}, input_type=dict]\
"""  # noqa: E501
    )


def test_embedded_document_parsing_validation_error():
    class E(EmbeddedModel):
        f: int

    with pytest.raises(DocumentParsingError) as exc_info:
        E.model_validate_doc({"f": "aa"})
    assert str(exc_info.value).splitlines()[:-1] == snapshot(
        [
            "1 validation error for E",
            "f",
            "  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='aa', input_type=str]",  # noqa: E501
        ]
    )


def test_embedded_model_alternate_key_name_with_default():
    class Em(EmbeddedModel):
        name: str = Field(key_name="username")

    class M(Model):
        f: Em = Em(name="Jack")

    _id = ObjectId()
    doc = {"_id": _id}
    parsed = M.model_validate_doc(doc)
    assert parsed.f.name == "Jack"


def test_embedded_model_alternate_key_name_parsing_exception():
    class Em(EmbeddedModel):
        name: str = Field(key_name="username")

    class M(Model):
        f: Em

    _id = ObjectId()
    doc = {"_id": _id}
    with pytest.raises(DocumentParsingError):
        M.model_validate_doc(doc)


def test_embedded_model_alternate_key_name():
    class Em(EmbeddedModel):
        name: str = Field(key_name="username")

    class M(Model):
        f: Em

    instance = M(f=Em(name="Jack"))
    doc = instance.model_dump_doc()
    assert doc["f"] == {"username": "Jack"}
    parsed = M.model_validate_doc(doc)
    assert parsed == instance


def test_embedded_model_list_alternate_key_name():
    class Em(EmbeddedModel):
        name: str = Field(key_name="username")

    class M(Model):
        f: List[Em]

    instance = M(f=[Em(name="Jack")])
    doc = instance.model_dump_doc()
    assert doc["f"] == [{"username": "Jack"}]
    parsed = M.model_validate_doc(doc)
    assert parsed == instance


def test_embedded_model_tuple_alternate_key_name():
    class Em(EmbeddedModel):
        name: str = Field(key_name="username")

    class M(Model):
        f: Tuple[Em, ...]

    instance = M(f=(Em(name="Jack"),))
    doc = instance.model_dump_doc()
    assert doc["f"] == [{"username": "Jack"}]
    parsed = M.model_validate_doc(doc)
    assert parsed == instance


def test_embedded_model_list_parsing_invalid_type():
    class Em(EmbeddedModel):
        name: str

    class M(Model):
        f: List[Em]

    with pytest.raises(DocumentParsingError) as exc_info:
        M.model_validate_doc({"_id": 1, "f": {1: {"name": "Jack"}}})

    assert str(exc_info.value) == snapshot(
        """\
1 validation error for M
f
  Incorrect generic embedded model value '{1: {'name': 'Jack'}}' [type=odmantic::incorrect_generic_embedded_model_value, input_value={'_id': 1, 'f': {1: {'name': 'Jack'}}}, input_type=dict]\
"""  # noqa: E501
    )


def test_embedded_model_list_parsing_missing_value():
    class Em(EmbeddedModel):
        name: str

    class M(Model):
        f: List[Em]

    with pytest.raises(
        DocumentParsingError,
    ) as exc_info:
        M.model_validate_doc({"_id": 1})
    assert str(exc_info.value) == snapshot(
        """\
1 validation error for M
f
  Key 'f' not found in document [type=odmantic::key_not_found_in_document, input_value={'_id': 1}, input_type=dict]\
"""  # noqa: E501
    )


def test_embedded_model_list_parsing_missing_value_with_default():
    class Em(EmbeddedModel):
        name: str

    class M(Model):
        f: List[Em] = [Em(name="John")]

    parsed = M.model_validate_doc({"_id": ObjectId()})
    assert parsed.f == [Em(name="John")]


def test_embedded_model_dict_parsing_invalid_value():
    class Em(EmbeddedModel):
        name: str

    class M(Model):
        f: Dict[str, Em]

    with pytest.raises(DocumentParsingError) as exc_info:
        M.model_validate_doc({"_id": 1, "f": []})
    assert str(exc_info.value) == snapshot(
        """\
1 validation error for M
f
  Incorrect generic embedded model value '[]' [type=odmantic::incorrect_generic_embedded_model_value, input_value={'_id': 1, 'f': []}, input_type=dict]\
"""  # noqa: E501
    )


def test_embedded_model_dict_parsing_invalid_sub_value():
    class Em(EmbeddedModel):
        e: int

    class M(Model):
        f: Dict[str, Em]

    with pytest.raises(DocumentParsingError) as exc_info:
        M.model_validate_doc({"_id": ObjectId(), "f": {"key": {"not_there": "a"}}})
    assert str(exc_info.value) == snapshot(
        """\
1 validation error for M
f.["key"].e
  Key 'e' not found in document [type=odmantic::key_not_found_in_document, input_value={'not_there': 'a'}, input_type=dict]\
"""  # noqa: E501
    )


def test_embedded_model_list_parsing_invalid_sub_value():
    class Em(EmbeddedModel):
        e: int

    class M(Model):
        f: List[Em]

    with pytest.raises(DocumentParsingError) as exc_info:
        M.model_validate_doc({"_id": ObjectId(), "f": [{"not_there": "a"}]})
    assert str(exc_info.value) == snapshot(
        """\
1 validation error for M
f.[0].e
  Key 'e' not found in document [type=odmantic::key_not_found_in_document, input_value={'not_there': 'a'}, input_type=dict]\
"""  # noqa: E501
    )


def test_fields_modified_on_object_parsing():
    instance = PersonModel.model_validate(
        {"_id": ObjectId(), "first_name": "Jackie", "last_name": "Chan"}
    )
    assert instance.__fields_modified__ == set(["first_name", "last_name", "id"])


def test_change_primary_key_value():
    class M(Model): ...

    instance = M()
    with pytest.raises(NotImplementedError, match="assigning a new primary key"):
        instance.id = 12


def test_model_copy_without_update():
    instance = PersonModel(first_name="Jean", last_name="Valjean")
    copied = instance.model_copy()
    assert instance == copied


def test_model_copy_with_update():
    instance = PersonModel(first_name="Jean", last_name="Valjean")
    copied = instance.model_copy(update={"last_name": "Pierre"})
    assert instance.id == copied.id
    assert instance.first_name == copied.first_name
    assert copied.last_name == "Pierre"


def test_model_copy_with_update_primary_key():
    instance = PersonModel(first_name="Jean", last_name="Valjean")
    copied = instance.model_copy(update={"id": ObjectId()})
    assert instance.first_name == copied.first_name
    assert copied.last_name == copied.last_name
    assert instance.id != copied.id


@pytest.mark.filterwarnings("ignore:copy is deprecated")
def test_deprecated_model_copy_call():
    class M(Model): ...

    with pytest.raises(NotImplementedError):
        M().copy(include={"id"})

    with pytest.raises(NotImplementedError):
        M().copy(exclude={"id"})


def test_model_copy_deep_embedded():
    class E(EmbeddedModel):
        f: int

    class M(Model):
        e: E

    instance = M(e=E(f=1))
    copied = instance.model_copy(deep=True)
    assert instance.e is not copied.e


def test_model_copy_deep_embedded_mutability():
    class F(EmbeddedModel):
        g: int

    class E(EmbeddedModel):
        f: F

    class M(Model):
        e: E

    instance = M(e=E(f=F(g=1)))
    copied = instance.model_copy(deep=True)
    copied.e.f.g = 42
    assert instance.e.f.g != copied.e.f.g


def test_model_copy_not_deep_embedded():
    class E(EmbeddedModel):
        f: int

    class M(Model):
        e: E

    instance = M(e=E(f=1))
    copied = instance.model_copy(deep=False)
    assert instance.e is copied.e


@pytest.mark.parametrize("deep", [True, False])
def test_model_copy_with_reference(deep: bool):
    class R(Model):
        f: int

    class M(Model):
        r: R = Reference()

    ref_instance = R(f=12)
    instance = M(r=ref_instance)
    copied = instance.model_copy(deep=deep)
    assert instance.model_dump_doc() == copied.model_dump_doc()
    assert instance.r == copied.r


@pytest.mark.parametrize("deep", [True, False])
def test_model_copy_field_modified(deep: bool):
    class M(Model):
        f: int

    instance = M(f=5)
    object.__setattr__(instance, "__fields_modified__", set())
    copied = instance.model_copy(update={"f": 12}, deep=deep)
    assert "f" in copied.__fields_modified__


@pytest.mark.parametrize("deep", [True, False])
def test_model_copy_field_modified_on_primary_field_change(deep: bool):
    class M(Model):
        f0: int
        f1: int
        f2: int

    instance = M(f0=12, f1=5, f2=6)
    object.__setattr__(instance, "__fields_modified__", set())
    copied = instance.model_copy(deep=deep)
    assert {"id", "f0", "f1", "f2"} == copied.__fields_modified__


INITIAL_FIRST_NAME, INITIAL_LAST_NAME = "INITIAL_FIRST_NAME", "INITIAL_LAST_NAME"
UPDATED_NAME = "UPDATED_NAME"


@pytest.fixture
def instance_to_update():
    return PersonModel(first_name=INITIAL_FIRST_NAME, last_name=INITIAL_LAST_NAME)


def test_update_pydantic_model(instance_to_update):
    class Update(BaseModel):
        first_name: str

    update_obj = Update(first_name=UPDATED_NAME)
    instance_to_update.model_update(update_obj)
    assert instance_to_update.first_name == UPDATED_NAME
    assert instance_to_update.last_name == INITIAL_LAST_NAME


def test_update_dictionary(instance_to_update):
    update_obj = {"first_name": UPDATED_NAME}
    instance_to_update.model_update(update_obj)
    assert instance_to_update.first_name == UPDATED_NAME
    assert instance_to_update.last_name == INITIAL_LAST_NAME


def test_update_include(instance_to_update):
    update_obj = {"first_name": UPDATED_NAME}
    instance_to_update.model_update(update_obj, include=set())
    assert instance_to_update.first_name == INITIAL_FIRST_NAME
    assert instance_to_update.last_name == INITIAL_LAST_NAME


def test_update_exclude(instance_to_update):
    update_obj = {"first_name": UPDATED_NAME}
    instance_to_update.model_update(update_obj, exclude={"first_name"})
    assert instance_to_update.first_name == INITIAL_FIRST_NAME
    assert instance_to_update.last_name == INITIAL_LAST_NAME


def test_update_exclude_none(instance_to_update):
    class Update(BaseModel):
        first_name: Optional[str]
        last_name: Optional[str]

    update_obj = Update(first_name=UPDATED_NAME, last_name=None)
    instance_to_update.model_update(update_obj, exclude_unset=False, exclude_none=True)
    assert instance_to_update.first_name == UPDATED_NAME
    assert instance_to_update.last_name == INITIAL_LAST_NAME


def test_update_exclude_defaults(instance_to_update):
    initial_instance = instance_to_update.model_copy()

    class Update(BaseModel):
        first_name: Optional[str] = None
        last_name: str = UPDATED_NAME

    update_obj = Update()
    instance_to_update.model_update(
        update_obj, exclude_unset=False, exclude_defaults=True
    )
    assert instance_to_update == initial_instance


def test_update_exclude_over_include(instance_to_update):
    update_obj = {"first_name": UPDATED_NAME}
    instance_to_update.model_update(
        update_obj, include={"first_name"}, exclude={"first_name"}
    )
    assert instance_to_update.first_name == INITIAL_FIRST_NAME
    assert instance_to_update.last_name == INITIAL_LAST_NAME


def test_update_invalid():
    class M(Model):
        f: int

    instance = M(f=12)
    update_obj = {"f": "aaa"}
    with pytest.raises(ValidationError):
        instance.model_update(update_obj)


def test_update_model_undue_update_fields():
    class M(Model):
        f: int

    instance = M(f=12)
    update_obj = {"not_in_model": "aaa"}
    instance.model_update(update_obj)


def test_update_pydantic_unset_update_fields():
    UPDATEED_VALUE = 100

    class P(BaseModel):
        f: int = UPDATEED_VALUE

    class M(Model):
        f: int

    instance = M(f=0)
    update_obj = P()
    instance.model_update(update_obj)
    assert instance.f != UPDATEED_VALUE


def test_update_pydantic_unset_update_fields_include_unset():
    UPDATEED_VALUE = 100

    class P(BaseModel):
        f: int = UPDATEED_VALUE

    class M(Model):
        f: int

    instance = M(f=0)
    update_obj = P()
    instance.model_update(update_obj, exclude_unset=False)
    assert instance.f == UPDATEED_VALUE


def test_update_embedded_model():
    class E(EmbeddedModel):
        f: int

    instance = E(f=12)
    instance.model_update({"f": 15})
    assert instance.f == 15


def test_update_reference():
    class R(Model):
        f: int

    class M(Model):
        r: R = Reference()

    r0 = R(f=0)
    r1 = R(f=1)

    instance = M(r=r0)
    instance.model_update({"r": r1})
    assert instance.r.f == r1.f
    assert instance.r == r1


def test_update_type_coercion():
    class M(Model):
        f: int

    instance = M(f=12)
    update_obj = {"f": "12"}
    instance.model_update(update_obj)
    assert isinstance(instance.f, int)


def test_update_side_effect_field_modified():
    class Rectangle(Model):
        width: float
        height: float
        area: float = 0

        @model_validator(mode="before")
        def set_area(cls, v):
            v["area"] = v["width"] * v["height"]
            return v

    r = Rectangle(width=1, height=1)
    assert r.area == 1
    r.__fields_modified__.clear()
    r.model_update({"width": 5})
    assert r.area == 5
    assert "area" in r.__fields_modified__


@pytest.mark.filterwarnings(
    "ignore: Pydantic V1 style `@root_validator` validators are deprecated"
)
def test_update_side_effect_field_modified_with_root_validator():
    class Rectangle(Model):
        width: float
        height: float
        area: float = 0

        @root_validator(skip_on_failure=True)
        def set_area(cls, v):
            v["area"] = v["width"] * v["height"]
            return v

    r = Rectangle(width=1, height=1)
    assert r.area == 1
    r.__fields_modified__.clear()
    r.model_update({"width": 5})
    assert r.area == 5
    assert "area" in r.__fields_modified__


def test_update_dict_id_exception():
    class M(Model):
        alternate_id: int = Field(primary_field=True)
        f: int

    m = M(alternate_id=0, f=0)
    with pytest.raises(ValueError, match="Updating the primary key is not supported"):
        m.model_update({"alternate_id": 1})


@pytest.mark.parametrize(
    "update_kwargs",
    (
        {"include": set()},
        {"exclude": {"alternate_id"}},
        {"include": {"alternate_id"}, "exclude": {"alternate_id"}},
    ),
)
def test_update_dict_alternate_id_filtered(update_kwargs):
    class M(Model):
        alternate_id: int = Field(primary_field=True)
        f: int

    m = M(alternate_id=0, f=0)
    m.model_update({"alternate_id": 1}, **update_kwargs)
    assert m.f == 0 and m.alternate_id == 0, "instance should be unchanged"


def test_update_pydantic_id_exception():
    class M(Model):
        alternate_id: int = Field(primary_field=True)
        f: int

    m = M(alternate_id=0, f=0)

    class UpdateObject(BaseModel):
        alternate_id: int

    with pytest.raises(ValueError, match="Updating the primary key is not supported"):
        m.model_update(UpdateObject(alternate_id=1))


@pytest.mark.parametrize(
    "update_kwargs",
    (
        {"include": set()},
        {"exclude": {"alternate_id"}},
        {"include": {"alternate_id"}, "exclude": {"alternate_id"}},
    ),
)
def test_update_pydantic_alternate_id_filtered(update_kwargs):
    class M(Model):
        alternate_id: int = Field(primary_field=True)
        f: int

    class UpdateObject(BaseModel):
        alternate_id: int

    m = M(alternate_id=0, f=0)
    m.model_update(UpdateObject(alternate_id=1), **update_kwargs)
    assert m.f == 0 and m.alternate_id == 0, "instance should be unchanged"