From a7067d335dbce745db72582323b1996e2e680e20 Mon Sep 17 00:00:00 2001 From: David Montague <35119617+dmontagu@users.noreply.github.com> Date: Mon, 11 Dec 2023 08:47:39 -0700 Subject: [PATCH 1/2] Use input type json when validating a json schema --- src/validators/json.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/validators/json.rs b/src/validators/json.rs index 44250ef9d..641892364 100644 --- a/src/validators/json.rs +++ b/src/validators/json.rs @@ -5,7 +5,7 @@ use pyo3::types::PyDict; use jiter::JsonValue; use crate::errors::{ErrorType, ErrorTypeDefaults, ValError, ValLineError, ValResult}; -use crate::input::{EitherBytes, Input, ValidationMatch}; +use crate::input::{EitherBytes, Input, InputType, ValidationMatch}; use crate::tools::SchemaDict; use super::{build_validator, BuildValidator, CombinedValidator, DefinitionsBuilder, ValidationState, Validator}; @@ -58,7 +58,10 @@ impl Validator for JsonValidator { match self.validator { Some(ref validator) => { let json_value = JsonValue::parse(json_bytes, true).map_err(|e| map_json_err(input, e, json_bytes))?; - validator.validate(py, &json_value, state) + let mut json_state = state.rebind_extra(|e| { + e.input_type = InputType::Json; + }); + validator.validate(py, &json_value, &mut json_state) } None => { let obj = From 77f776c4e22b75cc3ee87b4d85dee5887ed3f4b4 Mon Sep 17 00:00:00 2001 From: sydney-runkle Date: Mon, 11 Dec 2023 11:23:40 -0600 Subject: [PATCH 2/2] add test --- tests/validators/test_json.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/validators/test_json.py b/tests/validators/test_json.py index 228d18e55..9bd553d46 100644 --- a/tests/validators/test_json.py +++ b/tests/validators/test_json.py @@ -1,4 +1,5 @@ import re +from enum import Enum import pytest @@ -152,6 +153,23 @@ def test_dict_key(py_and_json: PyAndJson): ] +def test_enum() -> None: + class MyEnum(Enum): + a = 'a' + b = 'b' + + enum_schema = core_schema.lax_or_strict_schema( + core_schema.no_info_after_validator_function(MyEnum, core_schema.str_schema()), + core_schema.is_instance_schema(MyEnum), + ) + v = core_schema.json_schema(enum_schema) + v = SchemaValidator(v) + assert v.validate_python('"a"') == MyEnum.a + assert v.validate_python('"b"') == MyEnum.b + with pytest.raises(ValidationError): + v.validate_python('"c"') + + def test_any_schema_no_schema(): v = SchemaValidator(core_schema.json_schema()) assert 'validator:None' in plain_repr(v)