Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-validator

Typed fluent validation rules for Pudu

0.1.1Apache-2.01

InstallClose

CompositionTest.pudu

Pudu38 lines1.6 KB

GitHub ↗
1/** @Test.Validation.Composition.Suite — checks conditions and nested paths */2module PuduLangValidator.CompositionTest34import Std.Test as Test5import PuduLangValidator.Result as Validation6import PuduLangValidator.Rule as Rule7import PuduLangValidator.Rules.Child as ChildRule8import PuduLangValidator.Rules.Text as TextRule9import PuduLangValidator.Validator as Validator1011type Address = { city: Str }12type Customer = { name: Str, active: Bool, address: Option[Address] }1314fn addressValidator() -> Validator.Validator[Address] {15  let city = Rule.build(TextRule.notEmpty(Rule.ruleFor("city", |address: Address| address.city)))16  Validator.add(Validator.create(), city)17}1819fn customerValidator() -> Validator.Validator[Customer] {20  let name = Rule.build(Rule.when(TextRule.notEmpty(Rule.ruleFor("name", |person: Customer| person.name)),21      |person: Customer| person.active))22  let nested = ChildRule.setOptionalValidator("address", |person: Customer| person.address, addressValidator())23  Validator.add(Validator.add(Validator.create(), name), nested)24}2526fn main() -> Int {27  let validator = customerValidator()28  let skipped = Validator.validate(&validator, Customer{name: "", active: false, address: None})29  let failed = Validator.validate(&validator, Customer{name: "", active: true, address: Some(Address{city: ""})})30  let checks = Test.suite("Composition", &[31      Test.equals("false condition skips a rule", &skipped.isValid, &true),32      Test.equals("nested failure keeps parent path", &failed.errors.map(|failure: Validation.Failure| failure.propertyName),33          &["name", "address.city"]),34      Test.equals("nested rule preserves order", &failed.errors.length(), &2)35    ])36  Test.report(&Test.run(&checks))37}38