Skip to content

Commit 376a38d

Browse files
committed
add test
1 parent 84faba3 commit 376a38d

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

tests/validators/test_dict.py

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
2-
from collections import OrderedDict
2+
import sys
3+
from collections import OrderedDict, defaultdict
34
from collections.abc import Mapping
45
from typing import Any
56

@@ -11,6 +12,12 @@
1112

1213
from ..conftest import Err, PyAndJson
1314

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+
1421

1522
def test_dict(py_and_json: PyAndJson):
1623
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):
315322
assert exc_info.value.errors(include_url=False) == expected
316323

317324

325+
@skip_on_graalpy
318326
@pytest.mark.parametrize('strict', [True, False])
319327
def test_ordered_dict_key_order_preservation(strict):
320328
# GH 12273
@@ -335,3 +343,46 @@ def test_ordered_dict_key_order_preservation(strict):
335343
result2 = v.validate_python(foo2, strict=strict)
336344
assert list(result2.keys()) == list(foo2.keys()) == ['y', 'z', 'x']
337345
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

Comments
 (0)