-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelpers_tests.rs
More file actions
4049 lines (3684 loc) · 153 KB
/
Copy pathhelpers_tests.rs
File metadata and controls
4049 lines (3684 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 Erick Bourgeois, RBC Capital Markets
// SPDX-License-Identifier: Apache-2.0
#[cfg(test)]
#[allow(clippy::module_inception)]
mod tests {
use super::super::*;
use crate::constants::{
ALLOWED_BOOTSTRAP_API_GROUPS, ALLOWED_INFRASTRUCTURE_API_GROUPS, MAX_CLUSTER_NAME_LEN,
MAX_DURATION_SECS, MAX_KILL_IF_COMMANDS_COUNT, MAX_KILL_IF_COMMAND_LEN,
};
use std::collections::BTreeMap;
// ========================================================================
// parse_duration — overflow & bounds protection
// ========================================================================
#[test]
fn test_parse_duration_seconds() {
let d = parse_duration("30s").unwrap();
assert_eq!(d.as_secs(), 30);
}
#[test]
fn test_parse_duration_minutes() {
let d = parse_duration("5m").unwrap();
assert_eq!(d.as_secs(), 300);
}
#[test]
fn test_parse_duration_hours() {
let d = parse_duration("1h").unwrap();
assert_eq!(d.as_secs(), 3600);
}
#[test]
fn test_parse_duration_max_allowed() {
// 24h == MAX_DURATION_SECS exactly — should be accepted
let d = parse_duration("24h").unwrap();
assert_eq!(d.as_secs(), MAX_DURATION_SECS);
}
#[test]
fn test_parse_duration_exceeds_max_hours() {
let err = parse_duration("25h").unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("exceeds maximum"),
"expected 'exceeds maximum' in error, got: {msg}"
);
}
#[test]
fn test_parse_duration_exceeds_max_seconds() {
// 86401s is one second over the 24h limit
let err = parse_duration("86401s").unwrap_err();
assert!(err.to_string().contains("exceeds maximum"));
}
#[test]
fn test_parse_duration_overflow_u64() {
// This would overflow u64 on multiplication: 9999999999999999h * 3600
let err = parse_duration("9999999999999999h").unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("overflow") || msg.contains("exceeds maximum"),
"expected overflow or bounds error, got: {msg}"
);
}
#[test]
fn test_parse_duration_overflow_minutes() {
// u64::MAX / 60 + 1 should overflow
let value = u64::MAX / 60 + 1;
let input = format!("{value}m");
let err = parse_duration(&input).unwrap_err();
assert!(
err.to_string().contains("overflow") || err.to_string().contains("exceeds maximum")
);
}
#[test]
fn test_parse_duration_empty() {
assert!(parse_duration("").is_err());
assert!(parse_duration(" ").is_err());
}
#[test]
fn test_parse_duration_invalid_unit() {
let err = parse_duration("5d").unwrap_err();
assert!(err.to_string().contains("Invalid duration unit"));
}
#[test]
fn test_parse_duration_invalid_value() {
assert!(parse_duration("abch").is_err());
assert!(parse_duration("s").is_err());
}
#[test]
fn test_parse_duration_rejects_non_ascii() {
// Regression: fuzz discovered that split_at(len - 1) panics when the
// trailing byte is mid-UTF-8-code-point (e.g. "٠" = U+0660, bytes
// D9 A0). Non-ASCII input must return Err, not panic.
let err = parse_duration("٠").unwrap_err();
assert!(err.to_string().contains("non-ASCII"));
assert!(parse_duration("5٠").is_err());
assert!(parse_duration("🕐").is_err());
}
// ========================================================================
// validate_labels — reserved prefix rejection
// ========================================================================
#[test]
fn test_validate_labels_clean() {
let mut labels = BTreeMap::new();
labels.insert("app".to_string(), "my-app".to_string());
labels.insert("team".to_string(), "platform".to_string());
assert!(validate_labels(&labels, "labels").is_ok());
}
#[test]
fn test_validate_labels_rejects_kubernetes_io() {
let mut labels = BTreeMap::new();
labels.insert("kubernetes.io/hostname".to_string(), "node1".to_string());
let err = validate_labels(&labels, "labels").unwrap_err();
assert!(err.to_string().contains("reserved prefix"));
assert!(err.to_string().contains("kubernetes.io/"));
}
#[test]
fn test_validate_labels_rejects_k8s_io() {
let mut labels = BTreeMap::new();
labels.insert("k8s.io/something".to_string(), "val".to_string());
assert!(validate_labels(&labels, "labels").is_err());
}
#[test]
fn test_validate_labels_rejects_cluster_x_k8s_io() {
let mut labels = BTreeMap::new();
labels.insert(
"cluster.x-k8s.io/cluster-name".to_string(),
"injected-cluster".to_string(),
);
let err = validate_labels(&labels, "labels").unwrap_err();
assert!(err.to_string().contains("reserved prefix"));
}
#[test]
fn test_validate_labels_rejects_5spot_io() {
let mut labels = BTreeMap::new();
labels.insert(
"5spot.finos.org/scheduled-machine".to_string(),
"injected".to_string(),
);
assert!(validate_labels(&labels, "labels").is_err());
}
#[test]
fn test_validate_labels_empty_map() {
let labels = BTreeMap::new();
assert!(validate_labels(&labels, "labels").is_ok());
}
#[test]
fn test_validate_annotations_rejects_reserved() {
let mut annotations = BTreeMap::new();
annotations.insert(
"kubernetes.io/created-by".to_string(),
"attacker".to_string(),
);
let err = validate_labels(&annotations, "annotations").unwrap_err();
assert!(err.to_string().contains("annotations"));
assert!(err.to_string().contains("reserved prefix"));
}
// ========================================================================
// validate_api_group — allowlist enforcement
// ========================================================================
#[test]
fn test_validate_api_group_valid_bootstrap() {
assert!(validate_api_group(
"bootstrap.cluster.x-k8s.io/v1beta1",
ALLOWED_BOOTSTRAP_API_GROUPS,
"bootstrap"
)
.is_ok());
}
#[test]
fn test_validate_api_group_valid_k0smotron_bootstrap() {
assert!(validate_api_group(
"k0smotron.io/v1beta1",
ALLOWED_BOOTSTRAP_API_GROUPS,
"bootstrap"
)
.is_ok());
}
#[test]
fn test_validate_api_group_valid_infrastructure() {
assert!(validate_api_group(
"infrastructure.cluster.x-k8s.io/v1beta1",
ALLOWED_INFRASTRUCTURE_API_GROUPS,
"infrastructure"
)
.is_ok());
}
#[test]
fn test_validate_api_group_rejects_core_api() {
// Core API (no slash) must be rejected
let err = validate_api_group("v1", ALLOWED_BOOTSTRAP_API_GROUPS, "bootstrap").unwrap_err();
assert!(err.to_string().contains("namespaced API group"));
}
#[test]
fn test_validate_api_group_rejects_rbac() {
let err = validate_api_group(
"rbac.authorization.k8s.io/v1",
ALLOWED_BOOTSTRAP_API_GROUPS,
"bootstrap",
)
.unwrap_err();
assert!(err.to_string().contains("not allowed"));
assert!(err.to_string().contains("rbac.authorization.k8s.io"));
}
#[test]
fn test_validate_api_group_rejects_apps() {
let err = validate_api_group(
"apps/v1",
ALLOWED_INFRASTRUCTURE_API_GROUPS,
"infrastructure",
)
.unwrap_err();
assert!(err.to_string().contains("not allowed"));
}
#[test]
fn test_validate_api_group_rejects_wrong_side() {
// Infrastructure group used as bootstrap should be rejected
let err = validate_api_group(
"infrastructure.cluster.x-k8s.io/v1beta1",
ALLOWED_BOOTSTRAP_API_GROUPS,
"bootstrap",
)
.unwrap_err();
assert!(err.to_string().contains("not allowed"));
}
#[test]
fn test_validate_api_group_rejects_kube_system_trick() {
// Attempt to sneak in a system API group
let err = validate_api_group(
"admissionregistration.k8s.io/v1",
ALLOWED_BOOTSTRAP_API_GROUPS,
"bootstrap",
)
.unwrap_err();
assert!(err.to_string().contains("not allowed"));
}
// ========================================================================
// build_phase_transition_event — pure function, no API calls
// ========================================================================
#[test]
fn test_phase_event_normal_type_for_active_transition() {
use kube::runtime::events::EventType;
let event = build_phase_transition_event(
Some("Pending"),
"Active",
"MachineCreated",
"CAPI Machine created",
);
assert_eq!(event.type_, EventType::Normal);
}
#[test]
fn test_phase_event_warning_type_for_error_transition() {
use kube::runtime::events::EventType;
let event = build_phase_transition_event(
Some("Pending"),
"Error",
"MachineCreationFailed",
"CAPI API unreachable",
);
assert_eq!(event.type_, EventType::Warning);
}
#[test]
fn test_phase_event_warning_type_for_terminated_transition() {
use kube::runtime::events::EventType;
let event = build_phase_transition_event(
Some("Active"),
"Terminated",
"KillSwitch",
"Kill switch activated",
);
assert_eq!(event.type_, EventType::Warning);
}
#[test]
fn test_phase_event_note_contains_from_and_to_phase() {
let event = build_phase_transition_event(
Some("Inactive"),
"Pending",
"ScheduleActive",
"Schedule became active",
);
let note = event.note.expect("note should be set");
assert!(note.contains("Inactive"), "note should contain from-phase");
assert!(note.contains("Pending"), "note should contain to-phase");
}
#[test]
fn test_phase_event_unknown_from_phase_when_none() {
let event =
build_phase_transition_event(None, "Inactive", "ScheduleInactive", "Outside schedule");
let note = event.note.expect("note should be set");
assert!(
note.contains("Unknown"),
"note should show 'Unknown' for missing from-phase"
);
}
#[test]
fn test_phase_event_action_contains_to_phase() {
let event = build_phase_transition_event(
Some("Pending"),
"Active",
"MachineCreated",
"Machine ready",
);
assert!(
event.action.contains("Active"),
"action should reference the target phase"
);
}
#[test]
fn test_phase_event_reason_matches_input() {
let event = build_phase_transition_event(
Some("Active"),
"ShuttingDown",
"GracePeriod",
"Outside schedule window",
);
assert_eq!(event.reason, "GracePeriod");
}
// Additional coverage: every non-error phase → Normal
#[test]
fn test_phase_event_normal_for_all_non_error_phases() {
use kube::runtime::events::EventType;
for phase in &["Pending", "Active", "ShuttingDown", "Inactive", "Disabled"] {
let event = build_phase_transition_event(None, phase, "Reason", "msg");
assert_eq!(
event.type_,
EventType::Normal,
"phase '{phase}' should produce Normal event"
);
}
}
#[test]
fn test_phase_event_note_contains_message() {
let event = build_phase_transition_event(
Some("Pending"),
"Active",
"MachineCreated",
"CAPI resources provisioned",
);
let note = event.note.expect("note should be set");
assert!(
note.contains("CAPI resources provisioned"),
"note should include the message"
);
}
#[test]
fn test_phase_event_secondary_is_none() {
// secondary object reference is not used for phase transitions
let event =
build_phase_transition_event(Some("Inactive"), "Active", "ScheduleActive", "msg");
assert!(event.secondary.is_none());
}
// ========================================================================
// update_phase — mock API tests
// ========================================================================
use http::{Request, Response};
use kube::client::Body;
use std::pin::pin;
use tower_test::mock;
fn mock_client_pair() -> (kube::Client, mock::Handle<Request<Body>, Response<Body>>) {
let (svc, handle) = mock::pair::<Request<Body>, Response<Body>>();
(kube::Client::new(svc, "default"), handle)
}
fn make_test_context(client: kube::Client) -> crate::reconcilers::Context {
crate::reconcilers::Context::new(client, 0, 1)
}
/// Minimal `ScheduledMachine` JSON for `patch_status` responses.
fn sm_response_body(name: &str, namespace: &str, phase: &str) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({
"apiVersion": "5spot.finos.org/v1alpha1",
"kind": "ScheduledMachine",
"metadata": {
"name": name,
"namespace": namespace,
"resourceVersion": "2"
},
"spec": {
"clusterName": "test",
"bootstrapSpec": {
"apiVersion": "bootstrap.cluster.x-k8s.io/v1beta1",
"kind": "K0sWorkerConfig",
"spec": {}
},
"infrastructureSpec": {
"apiVersion": "infrastructure.cluster.x-k8s.io/v1beta1",
"kind": "RemoteMachine",
"spec": {}
},
"schedule": {
"daysOfWeek": ["mon-fri"],
"hoursOfDay": ["9-17"],
"timezone": "UTC",
"enabled": true
},
"gracefulShutdownTimeout": "5m",
"nodeDrainTimeout": "5m"
},
"status": { "phase": phase }
}))
.unwrap()
}
/// Minimal events.k8s.io/v1 Event JSON for recorder responses.
fn k8s_event_response_body() -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({
"apiVersion": "events.k8s.io/v1",
"kind": "Event",
"metadata": {
"name": "5spot-test.17a0b1c",
"namespace": "default",
"resourceVersion": "1"
},
"eventTime": "2026-04-08T00:00:00.000000Z",
"reportingController": "5spot-controller",
"reportingInstance": "5spot-0",
"action": "PhaseTransitionToActive",
"reason": "MachineCreated",
"type": "Normal",
"regarding": {
"apiVersion": "5spot.finos.org/v1alpha1",
"kind": "ScheduledMachine",
"name": "test-sm",
"namespace": "default"
}
}))
.unwrap()
}
fn k8s_error_body(code: u16, msg: &str) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({
"kind": "Status",
"apiVersion": "v1",
"status": "Failure",
"message": msg,
"code": code
}))
.unwrap()
}
// ---- Positive: successful full path ----
#[tokio::test]
async fn test_update_phase_success_patches_status() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
// 1. Event publication (events.k8s.io)
let (_req, send) = h.next_request().await.expect("expected events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
// 2. Status patch
let (req, send) = h.next_request().await.expect("expected patch_status call");
assert_eq!(req.method(), http::Method::PATCH);
assert!(
req.uri().path().ends_with("/status"),
"should target /status subresource, got: {}",
req.uri().path()
);
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body("test-sm", "default", "Active")))
.unwrap(),
);
});
update_phase(
&ctx,
"default",
"test-sm",
Some("Pending"),
"Active",
Some("MachineCreated"),
Some("CAPI Machine created"),
true,
)
.await
.expect("update_phase should return Ok on success");
srv.await.unwrap();
}
#[tokio::test]
async fn test_update_phase_uses_default_reason_when_none() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (_req, send) = h.next_request().await.expect("patch_status call");
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body(
"test-sm", "default", "Inactive",
)))
.unwrap(),
);
});
// Passing None for reason and message — should use defaults without panicking
update_phase(
&ctx, "default", "test-sm", None, "Inactive", None, None, false,
)
.await
.expect("should succeed with default reason/message");
srv.await.unwrap();
}
// ---- Negative: Kubernetes API returns an error on patch_status ----
#[tokio::test]
async fn test_update_phase_returns_kube_error_when_patch_fails() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
// Event call succeeds
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
// Status patch returns 500
let (_req, send) = h.next_request().await.expect("patch_status call");
send.send_response(
Response::builder()
.status(500)
.header("content-type", "application/json")
.body(Body::from(k8s_error_body(500, "internal server error")))
.unwrap(),
);
});
let result = update_phase(
&ctx,
"default",
"test-sm",
Some("Active"),
"Error",
None,
None,
false,
)
.await;
assert!(result.is_err(), "should return Err when patch_status fails");
assert!(
matches!(result.unwrap_err(), ReconcilerError::KubeError(_)),
"error variant should be KubeError"
);
srv.await.unwrap();
}
#[tokio::test]
async fn test_update_phase_returns_kube_error_on_404_not_found() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (_req, send) = h.next_request().await.expect("patch_status call");
send.send_response(
Response::builder()
.status(404)
.header("content-type", "application/json")
.body(Body::from(k8s_error_body(
404,
"scheduledmachines \"test-sm\" not found",
)))
.unwrap(),
);
});
let result = update_phase(
&ctx,
"default",
"test-sm",
Some("Pending"),
"Active",
None,
None,
true,
)
.await;
assert!(result.is_err(), "should return Err on 404");
assert!(matches!(result.unwrap_err(), ReconcilerError::KubeError(_)));
srv.await.unwrap();
}
// ---- Exception: event recording fails — best-effort, must not block status patch ----
#[tokio::test]
async fn test_update_phase_event_failure_is_best_effort_patch_still_succeeds() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
// Event call fails with 500
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(500)
.header("content-type", "application/json")
.body(Body::from(k8s_error_body(500, "events API unavailable")))
.unwrap(),
);
// Status patch MUST still be called and returns success
let (req, send) = h
.next_request()
.await
.expect("patch_status must be called even after event failure");
assert_eq!(req.method(), http::Method::PATCH);
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body("test-sm", "default", "Active")))
.unwrap(),
);
});
let result = update_phase(
&ctx,
"default",
"test-sm",
Some("Pending"),
"Active",
None,
None,
true,
)
.await;
assert!(
result.is_ok(),
"event failure must not abort phase transition, got: {result:?}",
);
srv.await.unwrap();
}
#[tokio::test]
async fn test_update_phase_event_failure_plus_patch_failure_returns_kube_error() {
// Both event AND patch fail — should still return the patch error, not the event error
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
// Event fails
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(503)
.header("content-type", "application/json")
.body(Body::from(k8s_error_body(503, "service unavailable")))
.unwrap(),
);
// Patch also fails
let (_req, send) = h.next_request().await.expect("patch_status call");
send.send_response(
Response::builder()
.status(500)
.header("content-type", "application/json")
.body(Body::from(k8s_error_body(500, "internal error")))
.unwrap(),
);
});
let result = update_phase(
&ctx,
"default",
"test-sm",
Some("Active"),
"Error",
None,
None,
false,
)
.await;
assert!(
result.is_err(),
"should propagate patch error when both calls fail"
);
assert!(matches!(result.unwrap_err(), ReconcilerError::KubeError(_)));
srv.await.unwrap();
}
// ---- update_phase_with_grace_period ----
#[tokio::test]
async fn test_update_phase_with_grace_period_success() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (req, send) = h.next_request().await.expect("patch_status call");
assert!(req.uri().path().ends_with("/status"));
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body(
"test-sm",
"default",
"ShuttingDown",
)))
.unwrap(),
);
});
update_phase_with_grace_period(
&ctx,
"default",
"test-sm",
Some("Active"),
"ShuttingDown",
None,
None,
false,
)
.await
.expect("grace period update should succeed");
srv.await.unwrap();
}
#[tokio::test]
async fn test_update_phase_with_grace_period_patch_failure() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (_req, send) = h.next_request().await.expect("patch_status call");
send.send_response(
Response::builder()
.status(409)
.header("content-type", "application/json")
.body(Body::from(k8s_error_body(
409,
"conflict: resource version mismatch",
)))
.unwrap(),
);
});
let result = update_phase_with_grace_period(
&ctx,
"default",
"test-sm",
Some("Active"),
"ShuttingDown",
None,
None,
false,
)
.await;
assert!(result.is_err(), "409 conflict should return error");
assert!(matches!(result.unwrap_err(), ReconcilerError::KubeError(_)));
srv.await.unwrap();
}
// ---- ready-field projection on status patch ----
#[tokio::test]
async fn test_update_phase_active_sets_ready_true() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (req, send) = h.next_request().await.expect("patch_status call");
let body = collect_json_body(req.into_body()).await;
assert_eq!(body["status"]["phase"], "Active");
assert_eq!(
body["status"]["ready"], true,
"ready must be True when phase is Active"
);
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body("test-sm", "default", "Active")))
.unwrap(),
);
});
update_phase(
&ctx,
"default",
"test-sm",
Some("Pending"),
"Active",
None,
None,
true,
)
.await
.expect("update_phase should succeed");
srv.await.unwrap();
}
#[tokio::test]
async fn test_update_phase_inactive_sets_ready_false() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (req, send) = h.next_request().await.expect("patch_status call");
let body = collect_json_body(req.into_body()).await;
assert_eq!(body["status"]["phase"], "Inactive");
assert_eq!(
body["status"]["ready"], false,
"ready must be False for any non-Active phase"
);
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body(
"test-sm", "default", "Inactive",
)))
.unwrap(),
);
});
update_phase(
&ctx,
"default",
"test-sm",
Some("Active"),
"Inactive",
None,
None,
false,
)
.await
.expect("update_phase should succeed");
srv.await.unwrap();
}
#[tokio::test]
async fn test_update_phase_with_grace_period_shutting_down_sets_ready_false() {
let (client, handle) = mock_client_pair();
let ctx = make_test_context(client);
let srv = tokio::spawn(async move {
let mut h = pin!(handle);
let (_req, send) = h.next_request().await.expect("events call");
send.send_response(
Response::builder()
.status(201)
.header("content-type", "application/json")
.body(Body::from(k8s_event_response_body()))
.unwrap(),
);
let (req, send) = h.next_request().await.expect("patch_status call");
let body = collect_json_body(req.into_body()).await;
assert_eq!(body["status"]["phase"], "ShuttingDown");
assert_eq!(
body["status"]["ready"], false,
"ready must be False during ShuttingDown"
);
send.send_response(
Response::builder()
.status(200)
.header("content-type", "application/json")
.body(Body::from(sm_response_body(
"test-sm",
"default",
"ShuttingDown",
)))
.unwrap(),
);
});
update_phase_with_grace_period(
&ctx,
"default",
"test-sm",
Some("Active"),
"ShuttingDown",
None,
None,
false,
)
.await