Skip to content

Commit

Permalink
Use input type json when validating a json schema (#1117)
Browse files Browse the repository at this point in the history
Co-authored-by: sydney-runkle <sydneymarierunkle@gmail.com>
  • Loading branch information
dmontagu and sydney-runkle authored Dec 12, 2023
1 parent 7fa450d commit a5b3906
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/validators/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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 =
Expand Down
18 changes: 18 additions & 0 deletions tests/validators/test_json.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
from enum import Enum

import pytest

Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit a5b3906

Please sign in to comment.