File: test_model_definition.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 (530 lines) | stat: -rw-r--r-- 12,660 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
import sys
from types import FunctionType
from typing import (
    Any,
    Callable,
    ClassVar,
    Dict,
    FrozenSet,
    List,
    Literal,
    Mapping,
    Optional,
    Set,
    Tuple,
    Type,
    TypeVar,
    Union,
)

import pytest
from bson import ObjectId
from bson.decimal128 import Decimal128
from bson.regex import Regex
from pydantic import Field as PDField
from pydantic import ValidationError

from odmantic import ObjectId as ODMObjectId
from odmantic.field import Field
from odmantic.model import EmbeddedModel, Model
from odmantic.reference import Reference


class TheClassName(Model): ...


class TheClassNameModel(Model): ...


class TheClassNameOverriden(Model):
    model_config = {"collection": "collection_name"}


def test_auto_collection_name():
    assert TheClassName.__collection__ == "the_class_name"

    assert TheClassNameModel.__collection__ == "the_class_name"

    assert TheClassNameOverriden.__collection__ == "collection_name"


def test_auto_collection_name_nested():
    class theNestedClassName(Model): ...

    assert theNestedClassName.__collection__ == "the_nested_class_name"

    class TheNestedClassNameOverriden(Model):
        model_config = {"collection": "collection_name"}

    assert TheNestedClassNameOverriden.__collection__ == "collection_name"


def test_get_collection_name_pos():
    class Thing(Model): ...

    assert +Thing == "thing"


def test_duplicated_key_name():
    with pytest.raises(TypeError):

        class M(Model):
            a: int
            b: int = Field(key_name="a")


def test_duplicated_key_name_in_reference():
    class Referenced(Model):
        a: int

    with pytest.raises(TypeError):

        class Base(Model):
            a: int = Field(key_name="referenced")
            referenced: Referenced = Reference()


def test_duplicate_key_name_definition():
    with pytest.raises(TypeError):

        class Base(Model):
            a: int = Field(key_name="referenced")
            b: int = Field(key_name="referenced")


def test_key_name_containing_dollar_sign():
    class Base(Model):
        a: int = Field(key_name="a$b")


def test_key_starting_with_dollar_sign():
    with pytest.raises(TypeError):

        class Base(Model):
            a: int = Field(key_name="$a")


def test_key_containing_dot():
    with pytest.raises(TypeError):

        class Base(Model):
            b: int = Field(key_name="a.b")


def test_wrong_model_field():
    with pytest.raises(TypeError, match="use odmantic.Field instead of pydantic.Field"):

        class M(Model):
            a: int = PDField()


def test_unknown_model_field():
    class UnknownType:
        pass

    def U() -> Any:
        return UnknownType()

    with pytest.raises(TypeError):

        class M(Model):
            a: int = U()


def test_model_default_simple():
    class M(Model):
        f: int = 3

    instance = M()
    assert instance.f == 3


def test_model_default_with_field():
    class M(Model):
        f: int = Field(default=3)

    instance = M()
    assert instance.f == 3


def test_optional_field_with_default():
    class M(Model):
        f: Optional[str] = None

    assert M().f is None
    assert M(f="hello world").f == "hello world"


def test_field_with_invalid_default_type():
    with pytest.raises(TypeError, match="Unhandled field definition"):

        class M(Model):
            f: Optional[int] = "a"  # type: ignore


@pytest.mark.skip("Wait for feedback on an pydantic issue #1936")
def test_field_with_invalid_default_type_in_field():
    with pytest.raises(TypeError, match="Unhandled field definition"):

        class M(Model):
            f: Optional[int] = Field("a")


@pytest.mark.skip("Wait for feedback on an pydantic issue #1936")
def test_field_with_invalid_default_value_in_field_at_definition():
    with pytest.raises(TypeError, match="Unhandled field definition"):

        class M(Model):
            f: Optional[int] = Field(3, gt=5)


def test_field_with_invalid_default_value_in_field_at_instantiation():
    class M(Model):
        f: Optional[int] = Field(3, gt=5)

    with pytest.raises(ValidationError):
        M()


def test_optional_field_with_field_settings():
    class M(Model):
        f: Optional[str] = Field("hello world", key_name="my_field")

    assert M().f == "hello world"
    assert M(f=None).f is None


def test_unable_to_generate_primary_field():
    with pytest.raises(TypeError, match="can't automatically generate a primary field"):

        class A(Model):
            id: str


def test_define_alternate_primary_key():
    class M(Model):
        name: str = Field(primary_field=True)

    instance = M(name="Jack")
    assert instance.model_dump_doc() == {"_id": "Jack"}


def test_weird_overload_id_field():
    class M(Model):
        id: int
        name: str = Field(primary_field=True)

    instance = M(id=15, name="Johnny")
    assert instance.model_dump_doc() == {"_id": "Johnny", "id": 15}


@pytest.mark.skip("Not implemented, see if it should be supported...")
def test_overload_id_with_another_primary_key():
    with pytest.raises(TypeError, match="cannot define multiple primary keys"):

        class M(Model):
            id: int
            number: int = Field(primary_key=True)


def test_untyped_field_definition():
    with pytest.raises(TypeError, match="defined without type annotation"):

        class M(Model):
            a = 3


def test_multiple_primary_key():
    with pytest.raises(TypeError, match="Duplicated key_name"):

        class M(Model):
            a: int = Field(primary_field=True)
            b: int = Field(primary_field=True)


def test_model_with_implicit_reference_error():
    class A(Model):
        pass

    with pytest.raises(TypeError, match="without a Reference assigned"):

        class B(Model):
            a: A


def test_embedded_model_with_primary_key():
    with pytest.raises(TypeError, match="cannot define a primary field"):

        class A(EmbeddedModel):
            f: int = Field(primary_field=True)


T = TypeVar("T")


@pytest.mark.parametrize("generic", [List, Set, Tuple])
def test_embedded_model_generics_as_primary_key(generic: Type):
    class E(EmbeddedModel):
        f: int

    with pytest.raises(
        TypeError,
        match="Declaring a generic type of embedded models as a primary field"
        " is not allowed",
    ):

        class M(Model):
            e: generic[E] = Field(primary_field=True)  # type: ignore


@pytest.mark.parametrize(
    "generic",
    [
        lambda e: List[e],  # type: ignore
        lambda e: Set[e],  # type: ignore
        lambda e: Dict[str, e],  # type: ignore
        lambda e: Tuple[e],
        lambda e: Tuple[e, ...],
    ],
)
def test_embedded_model_generics_with_references(generic: Callable[[Type], Type]):
    class AnotherModel(Model):
        a: float

    class E(EmbeddedModel):
        f: AnotherModel = Reference()

    with pytest.raises(
        TypeError,
        match="Declaring a generic type of embedded models containing references"
        " is not allowed",
    ):

        class M(Model):
            e: generic(E)  # type: ignore


def test_invalid_collection_name_dollar():
    with pytest.raises(TypeError, match=r"cannot contain '\$'"):

        class A(Model):
            model_config = {"collection": "hello$world"}


def test_invalid_collection_name_empty():
    with pytest.raises(TypeError, match="cannot be empty"):

        class A(Model):
            model_config = {"collection": ""}


def test_invalid_collection_name_contain_system_dot():
    with pytest.raises(TypeError, match="cannot start with 'system.'"):

        class A(Model):
            model_config = {"collection": "system.hi"}


def test_custom_collection_name():
    class M(Model):
        model_config = {"collection": "collection_name"}

    assert M.__collection__ == "collection_name"


def test_embedded_model_key_name():
    class E(EmbeddedModel):
        f: int = 3

    class M(Model):
        field: E = Field(E(), key_name="hello")

    doc = M().model_dump_doc()
    assert "hello" in doc
    assert doc["hello"] == {"f": 3}


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

    class M(Model):
        field: E = Field(primary_field=True)

    assert M(field=E(f=1)).model_dump_doc() == {"_id": {"f": 1}}


def test_untouched_types_function():
    def id_str(self) -> str:  # pragma: no cover
        return str(self.id)

    class M(Model):
        model_config = {"arbitrary_types_allowed": True}

        id_: FunctionType = id_str  # type: ignore

    assert "id_" not in M.__odm_fields__.keys()


@pytest.mark.parametrize(
    "t",
    [
        Optional[ObjectId],
        List[ObjectId],
        List[Decimal128],
        List[Regex],
        FrozenSet[Regex],
        Union[Regex, ObjectId],
        Dict[ObjectId, str],
        Dict[Tuple[ObjectId, ...], str],
        Dict[Union[ObjectId, str], str],
        Mapping[Union[ObjectId, str], str],
    ],
)
def test_compound_bson_field(t: Type):
    class M(Model):
        children: t  # type: ignore


def test_forbidden_field():
    with pytest.raises(TypeError, match="fields are not supported"):

        class M(Model):
            children: Callable


def test_model_with_class_var():
    class M(Model):
        cls_var: ClassVar[str] = "theclassvar"
        field: int

    assert M.cls_var == "theclassvar"
    m = M(field=5)
    assert m.cls_var == "theclassvar"
    assert m.field == 5
    assert "cls_var" not in m.model_dump_doc().keys()


def test_model_definition_extra_allow():
    class M(Model):
        model_config = {"extra": "allow"}

        f: int

    instance = M(f=1, g=2)
    assert instance.model_dump_doc(include={"f", "g"}) == {"f": 1, "g": 2}


def test_model_definition_extra_ignore():
    class M(Model):
        model_config = {"extra": "ignore"}

        f: int

    instance = M(f=1, g=2)
    assert instance.model_dump_doc(include={"f", "g"}) == {"f": 1}


def test_model_definition_extra_forbid():
    class M(Model):
        model_config = {"extra": "forbid"}

        f: int

    with pytest.raises(ValidationError, match="Extra inputs are not permitted"):
        M(f=1, g=2)


def test_extra_field_type_subst():
    class M(Model):
        model_config = {"extra": "allow"}

        f: int

    instance = M(f=1, oid=ODMObjectId())

    assert isinstance(instance.model_dump_doc()["oid"], ObjectId)


def test_extra_field_document_parsing():
    class M(Model):
        model_config = {"extra": "allow"}

        f: int

    instance = M.model_validate_doc({"_id": ObjectId(), "f": 1, "extra": "hello"})

    assert "extra" in instance.model_dump_doc()


class EmForGenericDefinitionTest(EmbeddedModel):
    f: int


@pytest.mark.skipif(
    sys.version_info[:3] < (3, 9, 0),
    reason="Standard collection generics not supported by python < 3.9",
)
@pytest.mark.parametrize(
    "get_type, value",
    [
        (lambda: list[int], [1, 2, 3]),
        (lambda: dict[str, int], {"a": 1, "b": 2}),
        (lambda: set[int], {1, 2, 3}),
        (lambda: tuple[int, ...], (1, 2, 3)),
        (
            lambda: list[EmForGenericDefinitionTest],
            [EmForGenericDefinitionTest(f=1), EmForGenericDefinitionTest(f=2)],
        ),
        (
            lambda: dict[str, EmForGenericDefinitionTest],
            {
                "a": EmForGenericDefinitionTest(f=1),
                "b": EmForGenericDefinitionTest(f=2),
            },
        ),
        (
            lambda: tuple[EmForGenericDefinitionTest, ...],
            (EmForGenericDefinitionTest(f=1), EmForGenericDefinitionTest(f=2)),
        ),
    ],
)
def test_model_definition_with_new_generics(get_type: Callable, value: Any):
    class M(Model):
        f: get_type()  # type: ignore # 3.9 + syntax

    assert M(f=value).f == value


def test_model_definition_with_literal():
    class M(Model):
        f: Literal["a", "b", "c"]  # noqa: F821

    assert M(f="a").f == "a"


def test_model_definition_with_literal_fail():
    class M(Model):
        f: Literal["a", "b", "c"]  # noqa: F821

    with pytest.raises(ValidationError):
        M(f="w")


def test_model_definition_with_generic_literals():
    class M(Model):
        f: List[Literal["a", "b", "c"]]  # noqa: F821

    assert M(f=["a", "c"]).f == ["a", "c"]


def test_model_with_multiple_optional_fields():
    class Person(Model):
        hashed_password: Optional[str]
        totp_secret: Optional[str] = Field(default=None)
        totp_counter: Optional[int] = Field(default=None)

    user = {
        "hashed_password": "hashed_password",
    }
    Person(**user)