Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

check items() exists before calling it a mapping #117

Merged
merged 2 commits into from
Jun 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions src/input/input_python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::str::from_utf8;

use pyo3::prelude::*;
use pyo3::types::{
PyBool, PyBytes, PyDate, PyDateTime, PyDict, PyFrozenSet, PyInt, PyList, PyMapping, PySet, PyString, PyTime,
PyTuple, PyType,
PyBool, PyBytes, PyDate, PyDateTime, PyDict, PyFrozenSet, PyInt, PyList, PyMapping, PySequence, PySet, PyString,
PyTime, PyTuple, PyType,
};

use crate::errors::location::LocItem;
Expand Down Expand Up @@ -155,10 +155,8 @@ impl<'a> Input<'a> for PyAny {
fn lax_dict<'data>(&'data self, try_instance: bool) -> ValResult<GenericMapping<'data>> {
if let Ok(dict) = self.cast_as::<PyDict>() {
Ok(dict.into())
} else if let Ok(mapping) = self.cast_as::<PyMapping>() {
// this is ugly, but we'd have to do it in somewhere anyway
// we could perhaps use an indexmap instead of a python dict?
let dict = match mapping_as_dict(mapping) {
} else if let Some(mapping_seq) = extract_mapping_seq(self) {
let dict = match mapping_seq_as_dict(mapping_seq) {
Ok(dict) => dict,
Err(err) => {
return err_val_error!(
Expand Down Expand Up @@ -375,9 +373,23 @@ impl<'a> Input<'a> for PyAny {
}
}

fn mapping_as_dict(mapping: &PyMapping) -> PyResult<&PyDict> {
let seq = mapping.items()?;
let dict = PyDict::new(mapping.py());
fn extract_mapping_seq(obj: &PyAny) -> Option<&PySequence> {
let mapping: &PyMapping = match obj.cast_as() {
Ok(mapping) => mapping,
Err(_) => return None,
};
// see https://github.com/PyO3/pyo3/issues/2072 - the cast_as::<PyMapping> is not entirely accurate
// and returns some things which are definitely not mappings (e.g. str) as mapping,
// hence we also require that the object as `items` to consider it a mapping
match mapping.items() {
Ok(seq) => Some(seq),
Err(_) => None,
}
}

// creating a temporary dict is slow, we could perhaps use an indexmap instead
fn mapping_seq_as_dict(seq: &PySequence) -> PyResult<&PyDict> {
let dict = PyDict::new(seq.py());
for r in seq.iter()? {
let t: &PyTuple = r?.extract()?;
let k = t.get_item(0)?;
Expand Down
4 changes: 2 additions & 2 deletions src/validators/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ impl Validator for ModelValidator {
return self.validate_assignment(py, field, input, extra, slots);
}

// TODO we shouldn't always use try_instance=true here
let dict = input.lax_dict(true)?;
// TODO allow _try_instance to be configurable
let dict = input.lax_dict(false)?;
let output_dict = PyDict::new(py);
let mut errors: Vec<ValLineError> = Vec::new();
let fields_set = PySet::empty(py).map_err(as_internal)?;
Expand Down
26 changes: 26 additions & 0 deletions tests/validators/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,32 @@ def test_dict(py_or_json):
assert v.validate_test({'1': 2, '3': 4}) == {1: 2, 3: 4}
v = py_or_json({'type': 'dict', 'strict': True, 'keys': {'type': 'int'}, 'values': {'type': 'int'}})
assert v.validate_test({'1': 2, '3': 4}) == {1: 2, 3: 4}
assert v.validate_test({}) == {}
with pytest.raises(ValidationError, match='Value must be a valid dictionary'):
v.validate_test([])


@pytest.mark.parametrize(
'input_value,expected',
[
({'1': 1, '2': 2}, {'1': '1', '2': '2'}),
({}, {}),
('foobar', Err("Value must be a valid dictionary [kind=dict_type, input_value='foobar', input_type=str]")),
([], Err('Value must be a valid dictionary [kind=dict_type,')),
([('x', 'y')], Err('Value must be a valid dictionary [kind=dict_type,')),
([('x', 'y'), ('z', 'z')], Err('Value must be a valid dictionary [kind=dict_type,')),
((), Err('Value must be a valid dictionary [kind=dict_type,')),
((('x', 'y'),), Err('Value must be a valid dictionary [kind=dict_type,')),
],
ids=repr,
)
def test_dict_cases(input_value, expected):
v = SchemaValidator({'type': 'dict', 'keys': 'str', 'values': 'str'})
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=re.escape(expected.message)):
v.validate_python(input_value)
else:
assert v.validate_python(input_value) == expected


def test_dict_value_error(py_or_json):
Expand Down
4 changes: 3 additions & 1 deletion tests/validators/test_model.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re

import pytest

from pydantic_core import SchemaError, SchemaValidator, ValidationError
Expand Down Expand Up @@ -479,7 +481,7 @@ def test_alias_build_error(alias_schema, error):
def test_empty_model():
v = SchemaValidator({'type': 'model', 'fields': {}})
assert v.validate_python({}) == ({}, set())
with pytest.raises(ValidationError):
with pytest.raises(ValidationError, match=re.escape('Value must be a valid dictionary [kind=dict_type,')):
v.validate_python('x')


Expand Down
1 change: 1 addition & 0 deletions tests/validators/test_model_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ def __init__(self):
assert m3.field_a == 'init'


@pytest.mark.xfail(reason="need to fix 'try_instance' in model.rs")
def test_model_class_instance_subclass():
class MyModel:
__slots__ = '__dict__', '__fields_set__'
Expand Down