1- import json
2-
31from asynctest import TestCase as AsyncTestCase , mock as async_mock
42
5- from marshmallow import EXCLUDE , fields , validates_schema , ValidationError
6-
7- from ....cache .base import BaseCache
8- from ....config .injection_context import InjectionContext
9- from ....storage .base import BaseStorage , StorageRecord
10-
11- from ...responder import BaseResponder , MockResponder
12- from ...util import time_now
3+ from marshmallow import EXCLUDE , INCLUDE , fields , validates_schema , ValidationError
134
145from ..base import BaseModel , BaseModelError , BaseModelSchema
156
@@ -35,6 +26,48 @@ def validate_fields(self, data, **kwargs):
3526 raise ValidationError ("" )
3627
3728
29+ class ModelImplWithUnknown (BaseModel ):
30+ class Meta :
31+ schema_class = "SchemaImplWithUnknown"
32+
33+ def __init__ (self , * , attr = None , ** kwargs ):
34+ self .attr = attr
35+ self .extra = kwargs
36+
37+
38+ class SchemaImplWithUnknown (BaseModelSchema ):
39+ class Meta :
40+ model_class = ModelImplWithUnknown
41+ unknown = INCLUDE
42+
43+ attr = fields .String (required = True )
44+
45+ @validates_schema
46+ def validate_fields (self , data , ** kwargs ):
47+ if data ["attr" ] != "succeeds" :
48+ raise ValidationError ("" )
49+
50+
51+ class ModelImplWithoutUnknown (BaseModel ):
52+ class Meta :
53+ schema_class = "SchemaImplWithoutUnknown"
54+
55+ def __init__ (self , * , attr = None ):
56+ self .attr = attr
57+
58+
59+ class SchemaImplWithoutUnknown (BaseModelSchema ):
60+ class Meta :
61+ model_class = ModelImplWithoutUnknown
62+
63+ attr = fields .String (required = True )
64+
65+ @validates_schema
66+ def validate_fields (self , data , ** kwargs ):
67+ if data ["attr" ] != "succeeds" :
68+ raise ValidationError ("" )
69+
70+
3871class TestBase (AsyncTestCase ):
3972 def test_model_validate_fails (self ):
4073 model = ModelImpl (attr = "string" )
@@ -63,3 +96,24 @@ def test_from_json_x(self):
6396 data = "{}{}"
6497 with self .assertRaises (BaseModelError ):
6598 ModelImpl .from_json (data )
99+
100+ def test_model_with_unknown (self ):
101+ model = ModelImplWithUnknown (attr = "succeeds" )
102+ model = model .validate ()
103+ assert model .attr == "succeeds"
104+
105+ model = ModelImplWithUnknown .deserialize (
106+ {"attr" : "succeeds" , "another" : "value" }
107+ )
108+ assert model .extra
109+ assert model .extra ["another" ] == "value"
110+ assert model .attr == "succeeds"
111+
112+ def test_model_without_unknown_default_exclude (self ):
113+ model = ModelImplWithoutUnknown (attr = "succeeds" )
114+ model = model .validate ()
115+ assert model .attr == "succeeds"
116+
117+ assert ModelImplWithoutUnknown .deserialize (
118+ {"attr" : "succeeds" , "another" : "value" }
119+ )
0 commit comments