Skip to content

Commit 2a48cef

Browse files
committed
match error message to python
1 parent bade337 commit 2a48cef

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

pydantic_core/_pydantic_core.pyi

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ class SchemaValidator:
88
def __init__(self, schema: Schema) -> None: ...
99
def validate_python(self, input: Any) -> Any: ...
1010
def isinstance_python(self, input: Any) -> bool: ...
11-
def validate_json(self, input: Union[str, bytes]) -> Any: ...
12-
def isinstance_json(self, input: Union[str, bytes]) -> bool: ...
11+
def validate_json(self, input: Union[str, bytes, bytearray]) -> Any: ...
12+
def isinstance_json(self, input: Union[str, bytes, bytearray]) -> bool: ...
1313
def validate_assignment(self, field: str, input: Any, data: Dict[str, Any]) -> Dict[str, Any]: ...
1414

1515
class SchemaError(ValueError):

src/validators/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,13 @@ fn parse_json(input: &PyAny) -> PyResult<serde_json::Result<JsonInput>> {
167167
if let Ok(py_bytes) = input.cast_as::<PyBytes>() {
168168
Ok(serde_json::from_slice(py_bytes.as_bytes()))
169169
} else if let Ok(py_str) = input.cast_as::<PyString>() {
170-
Ok(serde_json::from_str(&py_str.to_string_lossy()))
170+
let str = py_str.to_str()?;
171+
Ok(serde_json::from_str(str))
171172
} else if let Ok(py_byte_array) = input.cast_as::<PyByteArray>() {
172173
Ok(serde_json::from_slice(unsafe { py_byte_array.as_bytes() }))
173174
} else {
174-
Err(PyTypeError::new_err("JSON input must be str, bytes or bytearray"))
175+
let input_type = input.get_type().name().unwrap_or("unknown");
176+
py_error!(PyTypeError; "JSON input must be str, bytes or bytearray, not {}", input_type)
175177
}
176178
}
177179

tests/test_json.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def test_input_types(input_value):
2020

2121
def test_input_type_invalid():
2222
v = SchemaValidator({'type': 'list', 'items_schema': {'type': 'int'}})
23-
with pytest.raises(TypeError, match='^JSON input must be str, bytes or bytearray$'):
23+
with pytest.raises(TypeError, match='^JSON input must be str, bytes or bytearray, not list$'):
2424
v.validate_json([])
2525

2626

0 commit comments

Comments
 (0)