8000 Error changes by samuelcolvin · Pull Request #307 · pydantic/pydantic-core · GitHub
[go: up one dir, main page]

Skip to content

Error changes #307

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

Merged
merged 6 commits into from
Oct 26, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
make "loc" a tuple, not a list
  • Loading branch information
samuelcolvin committed Oct 25, 2022
commit eda1058d45f8eb05ee8a6ae4530b48042bc725cc
11 changes: 8 additions & 3 deletions src/errors/location.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use pyo3::once_cell::GILOnceCell;
use std::fmt;

use pyo3::prelude::*;
use pyo3::types::PyList;
use pyo3::types::PyTuple;

/// Used to store individual items of the error location, e.g. a string for key/field names
/// or a number for array indices.
Expand Down Expand Up @@ -85,11 +86,15 @@ impl Default for Location {
}
}

static EMPTY_TUPLE: GILOnceCell<PyObject> = GILOnceCell::new();

impl ToPyObject for Location {
fn to_object(&self, py: Python<'_>) -> PyObject {
match self {
Self::List(loc) => loc.iter().rev().collect::<Vec<_>>().to_object(py),
Self::Empty => PyList::empty(py).to_object(py),
Self::List(loc) => PyTuple::new(py, loc.iter().rev()).to_object(py),
Self::Empty => EMPTY_TUPLE
.get_or_init(py, || PyTuple::empty(py).to_object(py))
.clone_ref(py),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/input/input_python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ impl<'a> Input<'a> for PyAny {
} else if args.is_none() {
Ok(None)
} else if let Ok(list) = args.cast_as::<PyList>() {
// remove `collect` when we have https://github.com/PyO3/pyo3/pull/2676
Ok(Some(PyTuple::new(self.py(), list.iter().collect::<Vec<_>>())))
} else {
Err(ValLineError::new_with_loc(
Expand Down Expand Up @@ -160,6 +161,7 @@ impl<'a> Input<'a> for PyAny {
} else if let Ok(tuple) = self.cast_as::<PyTuple>() {
Ok(PyArgs::new(Some(tuple), None).into())
} else if let Ok(list) = self.cast_as::<PyList>() {
// remove `collect` when we have https://github.com/PyO3/pyo3/pull/2676
let tuple = PyTuple::new(self.py(), list.iter().collect::<Vec<_>>());
Ok(PyArgs::new(Some(tuple), None).into())
} else {
Expand Down
26 changes: 26 additions & 0 deletions tests/benchmarks/test_micro_benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,3 +1030,29 @@ def test_isinstance_json(benchmark):
def t():
validator.isinstance_json('"foo"')
validator.isinstance_json('123')


@pytest.mark.benchmark(group='error')
def test_int_error(benchmark):
validator = SchemaValidator(core_schema.int_schema())
try:
validator.validate_python('bar')
except ValidationError as e:
# insert_assert(e.errors())
assert e.errors() == [
{
'type': 'int_parsing',
'loc': (),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'bar',
}
]
else:
raise AssertionError('ValidationError not raised')

@benchmark
def t():
try:
validator.validate_python('foobar', strict=True)
except ValidationError as e:
e.errors()
4 changes: 2 additions & 2 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,14 @@ def test_sub_model_merge():
assert exc_info.value.errors() == [
{
'type': 'string_too_long',
'loc': ['f'],
'loc': ('f',),
'msg': 'String should have at most 4 characters',
'input': 'tests',
'ctx': {'max_length': 4},
},
{
'type': 'string_too_short',
'loc': ['sub_model', ' 9E88 f'],
'loc': ('sub_model', 'f'),
'msg': 'String should have at least 1 characters',
'input': '',
'ctx': {'min_length': 1},
Expand Down
6 changes: 3 additions & 3 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def f(input_value, **kwargs):
assert exc_info.value.errors() == [
{
'type': 'my_error',
'loc': [],
'loc': (),
'msg': 'this is a custom error FOOBAR 42',
'input': 42,
'ctx': {'foo': 'FOOBAR', 'bar': 42},
Expand Down Expand Up @@ -142,7 +142,7 @@ def f(input_value, **kwargs):
v.validate_python(4)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{'type': 'finite_number', 'loc': [], 'msg': 'Input should be a finite number', 'input': 4}
{'type': 'finite_number', 'loc': (), 'msg': 'Input should be a finite number', 'input': 4}
]


Expand All @@ -156,7 +156,7 @@ def f(input_value, **kwargs):
v.validate_python(4)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{'type': 'greater_than', 'loc': [], 'msg': 'Input should be greater than 42', 'input': 4, 'ctx': {'gt': 42.0}}
{'type': 'greater_than', 'loc': (), 'msg': 'Input should be greater than 42', 'input': 4, 'ctx': {'gt': 42.0}}
]


Expand Down
6 changes: 3 additions & 3 deletions tests/test_hypothesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Optional

import pytest
from dirty_equals import AnyThing, IsBytes, IsList, IsStr
from dirty_equals import AnyThing, IsBytes, IsStr, IsTuple
from hypothesis import given, strategies
from typing_extensions import TypedDict

Expand Down Expand Up @@ -44,7 +44,7 @@ def test_datetime_binary(datetime_schema, data):
assert exc.errors() == [
{
'type': 'datetime_parsing',
'loc': [],
'loc': (),
'msg': IsStr(regex='Input should be a valid datetime, .+'),
'input': IsBytes(),
'ctx': {'error': IsStr()},
Expand Down Expand Up @@ -108,7 +108,7 @@ def test_recursive_cycles(recursive_schema, data):
assert exc.errors() == [
{
'type': 'recursion_loop',
'loc': IsList(length=(1, None)),
'loc': IsTuple(length=(1, None)),
'msg': 'Recursion error - cyclic reference detected',
'input': AnyThing(),
}
Expand Down
6 changes: 3 additions & 3 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_error_loc():
assert exc_info.value.errors() == [
{
'type': 'int_parsing',
'loc': ['field_a', 2],
'loc': ('field_a', 2),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'wrong',
}
Expand All @@ -152,7 +152,7 @@ def test_json_invalid():
assert exc_info.value.errors() == [
{
'type': 'json_invalid',
'loc': [],
'loc': (),
'msg': 'Invalid JSON: EOF while parsing a string at line 1 column 7',
'input': '"foobar',
'ctx': {'error': 'EOF while parsing a string at line 1 column 7'},
Expand All @@ -163,7 +163,7 @@ def test_json_invalid():
assert exc_info.value.errors() == [
{
'type': 'json_invalid',
'loc': [],
'loc': (),
'msg': 'Invalid JSON: trailing comma at line 3 column 3',
'input': '[1,\n2,\n3,]',
'ctx': {'error': 'trailing comma at line 3 column 3'},
Expand Down
10 changes: 5 additions & 5 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def test_validation_error():
== [
{
'type': 'int_from_float',
'loc': [],
'loc': (),
'msg': 'Input should be a valid integer, got a number with a fractional part',
'input': 1.5,
}
Expand All @@ -68,7 +68,7 @@ def test_validation_error_include_context():
assert exc_info.value.errors() == [
{
'type': 'too_long',
'loc': [],
'loc': (),
'msg': 'List should have at most 2 items after validation, not 3',
'input': [1, 2, 3],
'ctx': {'field_type': 'List', 'max_length': 2, 'actual_length': 3},
Expand All @@ -78,7 +78,7 @@ def test_validation_error_include_context():
assert exc_info.value.errors(include_context=False) == [
{
'type': 'too_long',
'loc': [],
'loc': (),
'msg': 'List should have at most 2 items after validation, not 3',
'input': [1, 2, 3],
}
Expand Down Expand Up @@ -119,13 +119,13 @@ class MyModel:
assert exc_info.value.errors() == [
{
'type': 'float_parsing',
'loc': ['x'],
'loc': ('x',),
'msg': 'Input should be a valid number, unable to parse string as an number',
'input': 'x' * 60,
},
{
'type': 'int_parsing',
'loc': ['y'],
'loc': ('y',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'y',
},
Expand Down
Loading
0