defaults_and_context/
defaults_and_context.rs1use kube_cel::{RootContext, Validator, apply_defaults};
6use serde_json::json;
7
8fn main() {
9 let schema = json!({
10 "type": "object",
11 "properties": {
12 "replicas": {
13 "type": "integer",
14 "default": 1,
15 "x-kubernetes-validations": [
16 {"rule": "self >= 0", "message": "replicas must be non-negative"}
17 ]
18 },
19 "strategy": {
20 "type": "string",
21 "default": "RollingUpdate"
22 }
23 },
24 "x-kubernetes-validations": [
25 {"rule": "apiGroup == 'apps'", "message": "only apps group allowed"},
26 {"rule": "kind == 'Deployment'", "message": "must be a Deployment"}
27 ]
28 });
29
30 let object = json!({"replicas": 3});
32
33 let defaulted = apply_defaults(&schema, &object);
35 println!("=== Default Injection ===");
36 println!("Before: {object}");
37 println!("After: {defaulted}\n");
38
39 let root_ctx = RootContext {
41 api_version: "apps/v1".into(),
42 api_group: "apps".into(),
43 kind: "Deployment".into(),
44 };
45
46 let validator = Validator::new();
47 let errors = validator.validate_with_context(&schema, &defaulted, None, Some(&root_ctx));
48
49 println!("=== Validation Results ===");
50 if errors.is_empty() {
51 println!("All rules passed!");
52 } else {
53 for e in &errors {
54 println!("[FAIL] {}: {}", e.field_path, e.message);
55 }
56 }
57
58 println!("\n=== validate_with_defaults ===");
62 let simple_schema = json!({
63 "type": "object",
64 "properties": {
65 "replicas": {
66 "type": "integer",
67 "default": 1,
68 "x-kubernetes-validations": [
69 {"rule": "self >= 0", "message": "replicas must be non-negative"}
70 ]
71 },
72 "strategy": {
73 "type": "string",
74 "default": "RollingUpdate"
75 }
76 }
77 });
78 let sparse_object = json!({}); let errors = validator.validate_with_defaults(&simple_schema, &sparse_object, None);
80 println!("Validating empty object with defaults applied:");
81 if errors.is_empty() {
82 println!("All rules passed (replicas defaulted to 1, strategy to RollingUpdate)");
83 } else {
84 for e in &errors {
85 println!("[FAIL] {}", e.message);
86 }
87 }
88}