Skip to content
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

Use input type json when validating a json schema #1117

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
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