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 result = validator.validate_with_context(&schema, &defaulted, None, Some(&root_ctx));
48
49 println!("=== Validation Results ===");
50 match result {
51 Ok(()) => println!("All rules passed!"),
52 Err(errors) => {
53 for e in &errors {
54 println!("[FAIL] {}: {}", e.field_path, e.message);
55 }
56 }
57 }
58
59 println!("\n=== validate_with_defaults ===");
63 let simple_schema = json!({
64 "type": "object",
65 "properties": {
66 "replicas": {
67 "type": "integer",
68 "default": 1,
69 "x-kubernetes-validations": [
70 {"rule": "self >= 0", "message": "replicas must be non-negative"}
71 ]
72 },
73 "strategy": {
74 "type": "string",
75 "default": "RollingUpdate"
76 }
77 }
78 });
79 let sparse_object = json!({}); let result = validator.validate_with_defaults(&simple_schema, &sparse_object, None);
81 println!("Validating empty object with defaults applied:");
82 match result {
83 Ok(()) => println!("All rules passed (replicas defaulted to 1, strategy to RollingUpdate)"),
84 Err(errors) => {
85 for e in &errors {
86 println!("[FAIL] {}", e.message);
87 }
88 }
89 }
90}