footing 0.1.22

Feature-gated foundations for Rust backend services
Documentation
use std::sync::Arc;

use crate::observability::{
    MetricKind, MetricLabels, MetricRecorder, MetricRegistry, MetricsError, MetricsSnapshot,
};

use super::assert_no_metric;

#[derive(Debug, Clone, Default)]
/// A shared metrics registry with assertions for tests.
/// Inject [`Self::recorder`] into the code under test and inspect its results here.
pub struct TestMetrics {
    registry: Arc<MetricRegistry>,
}

impl TestMetrics {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    /// Returns a shared recorder backed by this test registry.
    pub fn recorder(&self) -> Arc<dyn MetricRecorder> {
        self.registry.clone()
    }

    #[must_use]
    /// Returns the registry.
    pub fn registry(&self) -> &Arc<MetricRegistry> {
        &self.registry
    }

    /// Returns an immutable snapshot.
    pub fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
        self.registry.snapshot()
    }

    /// Asserts that the matching series is a counter with the expected value.
    pub fn assert_counter(&self, name: &str, labels: MetricLabels, expected: u64) {
        assert_eq!(self.counter_value(name, &labels), expected as f64);
    }

    /// Asserts that the matching series is a counter meeting the minimum value.
    pub fn assert_counter_at_least(&self, name: &str, labels: MetricLabels, expected: u64) {
        let value = self.counter_value(name, &labels);
        assert!(
            value >= expected as f64,
            "counter {name} value {value} should be at least {expected}"
        );
    }

    fn counter_value(&self, name: &str, labels: &MetricLabels) -> f64 {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        let sample = snapshot
            .samples()
            .iter()
            .find(|sample| sample.name() == name && sample.labels() == labels.as_slice())
            .unwrap_or_else(|| panic!("counter sample {name} with expected labels was not found"));
        assert_eq!(
            sample.kind(),
            MetricKind::Counter,
            "metric {name} with expected labels should be a counter"
        );
        sample.value()
    }

    /// Asserts no metric.
    pub fn assert_no_metric(&self, name: &str, labels: MetricLabels) {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        assert_no_metric(&snapshot, name, labels);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testkit::{assert_metric_value, assert_metric_value_at_least};

    #[test]
    fn counter_assertions_reject_other_metric_kinds_with_matching_values() {
        for kind in [MetricKind::Gauge, MetricKind::Histogram] {
            let metrics = TestMetrics::new();
            let labels = MetricLabels::single("queue", "outbox").unwrap();
            match kind {
                MetricKind::Gauge => {
                    metrics
                        .registry()
                        .set_gauge("jobs_total", 3.0, labels.clone())
                }
                MetricKind::Histogram => {
                    metrics
                        .registry()
                        .observe_histogram("jobs_total", 3.0, labels.clone())
                }
                MetricKind::Counter => unreachable!(),
            }
            .unwrap();
            let snapshot = metrics.snapshot().unwrap();
            assert_metric_value(&snapshot, "jobs_total", labels.clone(), 3.0);
            assert_metric_value_at_least(&snapshot, "jobs_total", labels.clone(), 3.0);
            assert!(
                std::panic::catch_unwind(|| {
                    metrics.assert_counter("jobs_total", labels.clone(), 3);
                })
                .is_err(),
                "exact counter assertion accepted {kind:?}"
            );
            assert!(
                std::panic::catch_unwind(|| {
                    metrics.assert_counter_at_least("jobs_total", labels.clone(), 3);
                })
                .is_err(),
                "minimum counter assertion accepted {kind:?}"
            );
        }
    }

    #[test]
    fn counter_assertions_check_values_and_label_identity() {
        let metrics = TestMetrics::new();
        let labels = MetricLabels::single("queue", "outbox").unwrap();
        metrics
            .recorder()
            .increment_counter("jobs_total", 3, labels.clone())
            .unwrap();
        metrics.assert_counter("jobs_total", labels.clone(), 3);
        metrics.assert_counter_at_least("jobs_total", labels.clone(), 2);
        metrics.assert_counter_at_least("jobs_total", labels.clone(), 3);

        for (name, labels, expected) in [
            ("jobs_total", labels, 4),
            ("jobs_total", MetricLabels::default(), 3),
            ("missing_total", MetricLabels::default(), 0),
        ] {
            assert!(
                std::panic::catch_unwind(|| {
                    metrics.assert_counter(name, labels.clone(), expected);
                })
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(|| {
                    metrics.assert_counter_at_least(name, labels.clone(), expected);
                })
                .is_err()
            );
        }
    }
}