
ContextTest.pudu
Pudu53 lines2.4 KB
1/** @Test.Validation.Context.Suite — checks immutable root data */2module PuduLangValidator.ContextTest34import Std.Json as Json5import Std.Map as Map6import Std.Test as Test7import PuduLangValidator.Advanced as Advanced8import PuduLangValidator.Result as Validation9import PuduLangValidator.Rule as Rule10import PuduLangValidator.Rules.Child as Child11import PuduLangValidator.Validator as Validator1213type ChildValue = { token: Str }14type Model = { child: ChildValue }1516fn childRules() -> Validator.Validator[ChildValue] {17 let token = Rule.build(Rule.withCode(Rule.mustWithContext(18 Rule.ruleFor("token", |value: ChildValue| value.token),19 fn(_root: ChildValue, token: Str, data: Rule.ContextData) -> Bool {20 match Map.get(&data, "expected") {21 case Some(Json.Text(expected)) => token == expected22 case _ => false23 }24 }25 ), "TokenMismatch"))26 Validator.add(Validator.create(), token)27}2829fn main() -> Int {30 let child = Child.setValidator("child", |model: Model| model.child, childRules())31 let validator = Validator.add(Validator.create(), child)32 let allowed: Rule.ContextData = mapOf([("expected", Json.Text("open"))])33 let good = Validator.validateWithData(&validator, Model{child: ChildValue{token: "open"}},34 Validator.defaults(), allowed)35 let bad = Validator.validateWithData(&validator, Model{child: ChildValue{token: "closed"}},36 Validator.defaults(), allowed)37 let missing = Validator.validate(&validator, Model{child: ChildValue{token: "open"}})38 let custom = Advanced.customWithContext("context", fn(_model: Model, data: Rule.ContextData) -> Array[Validation.Failure] {39 if Map.get(&data, "expected") == None { [Validation.Failure {40 propertyName: "context", errorMessage: "Expected token was not supplied.", errorCode: "MissingContext",41 severity: Validation.Error, customState: ""42 }] } else { [] }43 })44 let customResult = Validator.validate(&Validator.add(Validator.create(), custom), Model{child: ChildValue{token: "open"}})45 let checks = Test.suite("Context", &[46 Test.equals("child receives root context data", &good.isValid, &true),47 Test.equals("wrong token fails child at prefixed path", &bad.errors[0].propertyName, &"child.token"),48 Test.equals("missing context fails typed check", &missing.errors[0].errorCode, &"TokenMismatch"),49 Test.equals("custom context rule emits its own failure", &customResult.errors[0].errorCode, &"MissingContext")50 ])51 Test.report(&Test.run(&checks))52}53