forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation_exception.rs
238 lines (210 loc) · 6.89 KB
/
validation_exception.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::error::Error;
use std::fmt;
use std::fmt::Write;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use strum::EnumMessage;
use crate::input::repr_string;
use super::kinds::ErrorKind;
use super::line_error::{Context, ValLineError};
use super::location::Location;
use super::ValError;
#[pyclass(extends=PyValueError, module="pydantic_core._pydantic_core")]
#[derive(Debug, Clone)]
pub struct ValidationError {
line_errors: Vec<PyLineError>,
title: PyObject,
}
impl fmt::Display for ValidationError {
#[cfg_attr(has_no_coverage, no_coverage)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.display(None))
}
}
impl ValidationError {
pub fn from_val_error(py: Python, title: PyObject, error: ValError) -> PyErr {
match error {
ValError::LineErrors(raw_errors) => {
let line_errors: Vec<PyLineError> = raw_errors.into_iter().map(|e| e.into_py(py)).collect();
PyErr::new::<ValidationError, _>((line_errors, title))
}
ValError::InternalErr(err) => err,
}
}
fn display(&self, py: Option<Python>) -> String {
let count = self.line_errors.len();
let plural = if count == 1 { "" } else { "s" };
let title: &str = match py {
Some(py) => self.title.extract(py).unwrap(),
None => "Schema",
};
let line_errors = pretty_py_line_errors(py, self.line_errors.iter());
format!("{} validation error{} for {}\n{}", count, plural, title, line_errors)
}
}
impl Error for ValidationError {
#[cfg_attr(has_no_coverage, no_coverage)]
fn source(&self) -> Option<&(dyn Error + 'static)> {
// we could in theory set self.source as `ValError::LineErrors(line_errors.clone())`, then return that here
// source is not used, and I can't imagine why it would be
None
}
}
// used to convert a validation error back to ValError for wrap functions
impl<'a> From<ValidationError> for ValError<'a> {
fn from(val_error: ValidationError) -> Self {
val_error
.line_errors
.into_iter()
.map(|e| e.into())
.collect::<Vec<_>>()
.into()
}
}
#[pymethods]
impl ValidationError {
#[new]
fn py_new(line_errors: Vec<PyLineError>, title: PyObject) -> Self {
Self { line_errors, title }
}
#[getter]
fn title(&self, py: Python) -> PyObject {
self.title.clone_ref(py)
}
fn error_count(&self) -> usize {
self.line_errors.len()
}
fn errors(&self, py: Python) -> PyResult<PyObject> {
Ok(self
.line_errors
.iter()
.map(|e| e.as_dict(py))
.collect::<PyResult<Vec<PyObject>>>()?
.into_py(py))
}
fn __repr__(&self, py: Python) -> String {
self.display(Some(py))
}
fn __str__(&self, py: Python) -> String {
self.__repr__(py)
}
}
macro_rules! truncate_input_value {
($out:expr, $value:expr) => {
if $value.len() > 50 {
write!(
$out,
", input_value={}...{}",
&$value[0..25],
&$value[$value.len() - 24..]
)?;
} else {
write!($out, ", input_value={}", $value)?;
}
};
}
pub fn pretty_py_line_errors<'a>(
py: Option<Python>,
line_errors_iter: impl Iterator<Item = &'a PyLineError>,
) -> String {
line_errors_iter
.map(|i| i.pretty(py))
.collect::<Result<Vec<_>, _>>()
.unwrap_or_else(|err| vec![format!("[error formatting line errors: {}]", err)])
.join("\n")
}
/// `PyLineError` are the public version of `ValLineError`, as help and used in `ValidationError`s
#[pyclass]
#[derive(Debug, Clone)]
pub struct PyLineError {
kind: ErrorKind,
location: Location,
input_value: PyObject,
context: Context,
}
impl<'a> IntoPy<PyLineError> for ValLineError<'a> {
fn into_py(self, py: Python<'_>) -> PyLineError {
PyLineError {
kind: self.kind,
location: match self.reverse_location.len() {
0..=1 => self.reverse_location,
_ => self.reverse_location.into_iter().rev().collect(),
},
input_value: self.input_value.to_object(py),
context: self.context,
}
}
}
/// opposite of above, used to extract line errors from a validation error for wrap functions
impl<'a> From<PyLineError> for ValLineError<'a> {
fn from(py_line_error: PyLineError) -> Self {
Self {
kind: py_line_error.kind,
reverse_location: match py_line_error.location.len() {
0..=1 => py_line_error.location,
_ => py_line_error.location.into_iter().rev().collect(),
},
input_value: py_line_error.input_value.into(),
context: py_line_error.context,
}
}
}
impl PyLineError {
pub fn as_dict(&self, py: Python) -> PyResult<PyObject> {
let dict = PyDict::new(py);
dict.set_item("kind", self.kind())?;
dict.set_item("loc", self.location.to_object(py))?;
dict.set_item("message", self.get_message())?;
dict.set_item("input_value", &self.input_value)?;
if !self.context.is_empty() {
dict.set_item("context", &self.context)?;
}
Ok(dict.into_py(py))
}
fn kind(&self) -> String {
self.kind.to_string()
}
fn get_message(&self) -> String {
let raw = match self.kind.get_message() {
Some(message) => message.to_string(),
None => self.kind(),
};
if self.context.is_empty() {
raw
} else {
self.context.render(raw)
}
}
fn pretty(&self, py: Option<Python>) -> Result<String, fmt::Error> {
let mut output = String::with_capacity(200);
if !self.location.is_empty() {
let loc = self
.location
.iter()
.map(|i| i.to_string())
.collect::<Vec<String>>()
.join(" -> ");
writeln!(output, "{}", &loc)?;
}
write!(output, " {} [kind={}", self.get_message(), self.kind())?;
if !self.context.is_empty() {
write!(output, ", context={}", self.context)?;
}
if let Some(py) = py {
let input_value = self.input_value.as_ref(py);
let input_str = match repr_string(input_value) {
Ok(s) => s,
Err(_) => input_value.to_string(),
};
truncate_input_value!(output, input_str);
if let Ok(type_) = input_value.get_type().name() {
write!(output, ", input_type={}", type_)?;
}
} else {
truncate_input_value!(output, self.input_value.to_string());
}
output.push(']');
Ok(output)
}
}