1
1
import re
2
- from collections import OrderedDict
2
+ import sys
3
+ from collections import OrderedDict , defaultdict
3
4
from collections .abc import Mapping
4
5
from typing import Any
5
6
11
12
12
13
from ..conftest import Err , PyAndJson
13
14
15
+ # Skip OrderedDict tests on GraalPy due to a bug in PyMapping.items()
16
+ skip_on_graalpy = pytest .mark .skipif (
17
+ sys .implementation .name == 'graalpy' ,
18
+ reason = 'GraalPy has a bug where PyMapping.items() does not preserve OrderedDict order' ,
19
+ )
20
+
14
21
15
22
def test_dict (py_and_json : PyAndJson ):
16
23
v = py_and_json ({'type' : 'dict' , 'keys_schema' : {'type' : 'int' }, 'values_schema' : {'type' : 'int' }})
@@ -315,6 +322,7 @@ def test_dict_fail_fast(fail_fast, expected):
315
322
assert exc_info .value .errors (include_url = False ) == expected
316
323
317
324
325
+ @skip_on_graalpy
318
326
@pytest .mark .parametrize ('strict' , [True , False ])
319
327
def test_ordered_dict_key_order_preservation (strict ):
320
328
# GH 12273
@@ -335,3 +343,46 @@ def test_ordered_dict_key_order_preservation(strict):
335
343
result2 = v .validate_python (foo2 , strict = strict )
336
344
assert list (result2 .keys ()) == list (foo2 .keys ()) == ['y' , 'z' , 'x' ]
337
345
assert result2 == {'y' : 2 , 'z' : 3 , 'x' : 1 }
346
+
347
+
348
+ @skip_on_graalpy
349
+ def test_userdefined_ordereddict ():
350
+ class MyOD (Mapping ):
351
+ def __init__ (self , ** kwargs ):
352
+ self .dict = {}
353
+ for kv in kwargs .items ():
354
+ self .dict [kv [0 ]] = kv [1 ]
355
+
356
+ def __iter__ (self ):
357
+ return iter (self .dict .keys ())
358
+
359
+ def move_to_end (self , key ):
360
+ self .dict [key ] = self .dict .pop (key )
361
+
362
+ def __getitem__ (self , key ):
363
+ return self .dict [key ]
364
+
365
+ def __len__ (self ):
366
+ return len (self .dict )
367
+
368
+ v = SchemaValidator (cs .dict_schema (keys_schema = cs .str_schema (), values_schema = cs .int_schema ()))
369
+
370
+ foo = MyOD (** {'a' : 1 , 'b' : 2 })
371
+ foo .move_to_end ('a' )
372
+
373
+ result = v .validate_python (foo )
374
+ assert list (result .keys ()) == list (foo .keys ()) == ['b' , 'a' ]
375
+ assert result == {'b' : 2 , 'a' : 1 }
376
+
377
+
378
+ @pytest .mark .parametrize ('strict' , [True , False ])
379
+ def test_defaultdict (strict ):
380
+ """Test that defaultdict is accepted and converted to regular dict"""
381
+ v = SchemaValidator (cs .dict_schema (keys_schema = cs .str_schema (), values_schema = cs .int_schema ()))
382
+
383
+ dd = defaultdict (int , {'a' : 1 , 'b' : 2 })
384
+
385
+ result = v .validate_python (dd , strict = strict )
386
+ assert result == {'a' : 1 , 'b' : 2 }
387
+ assert isinstance (result , dict )
388
+ assert not isinstance (result , defaultdict )
0 commit comments