|
| 1 | +#[cfg(test)] |
| 2 | +mod tests { |
| 3 | + use super::*; |
| 4 | + use std::time::Duration; |
| 5 | + use temp_env; |
| 6 | + |
| 7 | + #[test] |
| 8 | + fn test_k8s_resource_detector_with_env_vars() { |
| 9 | + // Temporarily set environment variables for the test |
| 10 | + temp_env::with_vars( |
| 11 | + [ |
| 12 | + ("K8S_POD_NAME", Some("test-pod")), |
| 13 | + ("K8S_NAMESPACE_NAME", Some("test-namespace")), |
| 14 | + ("K8S_NODE_NAME", Some("test-node")), |
| 15 | + ], |
| 16 | + || { |
| 17 | + // Create the K8sResourceDetector |
| 18 | + let detector = K8sResourceDetector::new(); |
| 19 | + // Use the detector to fetch the resources |
| 20 | + let resource = detector.detect(Duration::from_secs(5)); |
| 21 | + |
| 22 | + // Assert that the detected resource attributes match the expected values |
| 23 | + assert_eq!( |
| 24 | + resource, |
| 25 | + Resource::new(vec![ |
| 26 | + KeyValue::new("k8s.pod.name", "test-pod"), |
| 27 | + KeyValue::new("k8s.namespace.name", "test-namespace"), |
| 28 | + KeyValue::new("k8s.node.name", "test-node"), |
| 29 | + ]) |
| 30 | + ); |
| 31 | + }, |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + #[test] |
| 36 | + fn test_k8s_resource_detector_with_missing_env_vars() { |
| 37 | + // Temporarily set only one environment variable to test defaults |
| 38 | + temp_env::with_vars( |
| 39 | + [("K8S_POD_NAME", Some("test-pod"))], |
| 40 | + || { |
| 41 | + // Create the K8sResourceDetector |
| 42 | + let detector = K8sResourceDetector::new(); |
| 43 | + // Use the detector to fetch the resources |
| 44 | + let resource = detector.detect(Duration::from_secs(5)); |
| 45 | + |
| 46 | + // Assert that missing values use the default "unknown" values |
| 47 | + assert_eq!( |
| 48 | + resource, |
| 49 | + Resource::new(vec![ |
| 50 | + KeyValue::new("k8s.pod.name", "test-pod"), |
| 51 | + KeyValue::new("k8s.namespace.name", "unknown_namespace"), |
| 52 | + KeyValue::new("k8s.node.name", "unknown_node"), |
| 53 | + ]) |
| 54 | + ); |
| 55 | + }, |
| 56 | + ); |
| 57 | + } |
| 58 | +} |
0 commit comments