A faithful MoonBit port of python-jsonschema: JSON Schema validation.
Dependencies
///|
test "validate" {
let schema : Json = {
"type": "object",
"properties": { "price": { "type": "number", "minimum": 0 } },
"required": ["name"],
}
@jsonschema.validate({ "name": "Eggs", "price": 34.99 }, schema)
try @jsonschema.validate({ "name": "Eggs", "price": -1 }, schema) catch {
@jsonschema.ValidationError(error) => {
inspect(error.message, content="-1 is less than the minimum of 0")
inspect(
error,
content=(
#|-1 is less than the minimum of 0
#|
#|Failed validating 'minimum' in schema['properties']['price']:
#| {'type': 'number', 'minimum': 0}
#|
#|On instance['price']:
#| -1
),
)
}
_ => fail("expected a ValidationError")
} noraise {
_ => fail("expected a ValidationError")
}
}///|
test "iter_errors" {
let validator = @jsonschema.draft202012_validator.new({
"items": { "type": "integer" },
"maxItems": 2,
})
let errors = validator.iter_errors([1, "two", 3.5]).to_array()
inspect(
errors.map(e => "\{e.json_path()}: \{e.message}").join("\n"),
content=(
#|$[1]: 'two' is not of type 'integer'
#|$[2]: 3.5 is not of type 'integer'
#|$: [1, 'two', 3.5] is too long
),
)
inspect(validator.is_valid([1, 2]), content="true")
let best = @jsonschema.best_match(errors.iter()).unwrap()
inspect(best.message, content="[1, 'two', 3.5] is too long")
}///|
test "formats" {
let cls = @jsonschema.draft202012_validator
let validator = cls.new(
{ "format": "ipv4" },
format_checker=cls.format_checker,
)
inspect(validator.is_valid("127.0.0.1"), content="true")
inspect(validator.is_valid("127.0.0.01"), content="false")
inspect(cls.new({ "format": "ipv4" }).is_valid("nope"), content="true")
}///|
test "loads" {
let one_point_zero = @jsonschema.loads("1.0")
inspect(
@jsonschema.draft4_validator
.new({ "type": "integer" })
.is_valid(one_point_zero),
content="false",
)
inspect(
@jsonschema.draft7_validator
.new({ "type": "integer" })
.is_valid(one_point_zero),
content="true",
)
inspect(
@jsonschema.py_repr(@jsonschema.loads("[1.0, 1e400, 7]")),
content="[1.0, inf, 7]",
)
}///|
test "extend" {
let even : @jsonschema.KeywordFn = (_, value, instance, _) => {
@jsonschema.Errors::new(yield_ => {
if value is True && instance is Number(n, ..) && n % 2.0 != 0.0 {
return yield_(
@jsonschema.ValidationError::new(
"\{@jsonschema.py_repr(instance)} is odd",
),
)
}
true
})
}
let cls = @jsonschema.draft202012_validator.extend_with(validators=[
("even", even),
])
let errors = cls.new({ "even": true }).iter_errors(3).to_array()
inspect(errors[0].message, content="3 is odd")
debug_inspect(errors[0].schema_path, content="[Key(\"even\")]")
}| package | upstream |
|---|---|
| bobzhang/jsonschema | jsonschema (validators, _keywords, _legacy_keywords, _types, _format, _utils, exceptions) |
| bobzhang/jsonschema/specifications | jsonschema-specifications (meta-schemas, parsed lazily) |
| bobzhang/jsonschema/internal/pycompat | json.loads, repr, pprint.pformat, reprlib, textwrap, Python numerics |
| bobzhang/jsonschema/internal/regex | re: a port of CPython's parser, run on MoonBit core's @string.Regex or, for constructs it lacks, a backtracking matcher following sre |
| bobzhang/jsonschema/internal/formats | ipaddress, fqdn, idna, rfc3986-validator, rfc3987-syntax, rfc3339-validator, isoduration, jsonpointer, uri-template, webcolors |
| bobzhang/jsonschema/internal/unicodedata | the unicodedata / idna tables these need |
pub(all) suberror FormatCause {
AddressValueError(String)
IDNAError(String)
JsonPointerException(String)
DurationParsingException(String)
PatternError(String)
ValueError(String)
}impl Show for FormatCausepub suberror FormatError {
FormatError(message~ : String, cause~ : Error?)
}impl Show for FormatErrorpub suberror JSONDecodeError {
JSONDecodeError(msg~ : String, pos~ : Int, lineno~ : Int, colno~ : Int)
}impl Show for JSONDecodeErrorimpl Show for PythonErrorpub suberror UndefinedTypeCheck {
UndefinedTypeCheck(String)
}impl Show for UndefinedTypeCheckimpl Show for UnknownTypepub struct Errors {
// private fields
}impl Show for FormatCheckerfn FormatChecker::checks(self : FormatChecker, format : String, func : (Json) -> Bool raise, raises? : (Error) -> Bool) -> Unitfn FormatChecker::cls_checks(format : String, func : (Json) -> Bool raise, raises? : (Error) -> Bool) -> Unitpub struct TypeChecker {
// private fields
}impl Eq for TypeCheckerimpl Show for TypeCheckerfn TypeChecker::new(type_checkers? : ArrayView[(String, (TypeChecker, Json) -> Bool raise)]) -> TypeCheckerfn TypeChecker::redefine(self : TypeChecker, type_ : String, f : (TypeChecker, Json) -> Bool raise) -> TypeCheckerfn TypeChecker::redefine_many(self : TypeChecker, definitions : ArrayView[(String, (TypeChecker, Json) -> Bool raise)]) -> TypeCheckerfn TypeChecker::remove(self : TypeChecker, types : ArrayView[String]) -> TypeChecker raise UndefinedTypeCheckimpl Show for ValidationErrorfn ValidationError::new(message : String, validator? : Json, path? : ArrayView[PathItem], cause? : Error, context? : ArrayView[ValidationError], validator_value? : Json, instance? : Json, schema? : Json, schema_path? : ArrayView[PathItem], parent? : ValidationError, type_checker? : TypeChecker, kind? : ErrorKind) -> ValidationErrorpub struct Validator {
cls : ValidatorClass
schema : Json
format_checker : FormatChecker?
// private fields
}impl Show for ValidatorClassfn ValidatorClass::check_schema(self : ValidatorClass, schema : Json, format_checker? : FormatChecker?) -> Unit raisefn ValidatorClass::extend_with(cls : ValidatorClass, validators? : ArrayView[(String, (Validator, Json, Json, Json) -> Errors)], version? : String, type_checker? : TypeChecker, format_checker? : FormatChecker) -> ValidatorClassfn ValidatorClass::new(self : ValidatorClass, schema : Json, format_checker? : FormatChecker, registry? : Registry) -> Validator raisefn best_match(errors : Iter[ValidationError], key? : (ValidationError) -> Relevance) -> ValidationError?fn by_relevance(weak? : ArrayView[String], strong? : ArrayView[String]) -> ((ValidationError) -> Relevance)fn create(meta_schema~ : Json, validators? : ArrayView[(String, (Validator, Json, Json, Json) -> Errors)], version? : String, type_checker? : TypeChecker, format_checker? : FormatChecker, id_of? : (Json) -> String?, applicable_validators? : (Json) -> Array[(String, Json)]) -> ValidatorClassfn validate(instance : Json, schema : Json, cls? : ValidatorClass, format_checker? : FormatChecker, registry? : Registry) -> Unit raiseInstall
Download zipA faithful MoonBit port of python-jsonschema: JSON Schema validation.
Dependencies