footing 0.1.21

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

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

use super::{assert_metric_value, assert_metric_value_at_least, 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 counter.
    pub fn assert_counter(&self, name: &str, labels: MetricLabels, expected: u64) {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        assert_metric_value(&snapshot, name, labels, expected as f64);
    }

    /// Asserts counter at least.
    pub fn assert_counter_at_least(&self, name: &str, labels: MetricLabels, expected: u64) {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        assert_metric_value_at_least(&snapshot, name, labels, expected as f64);
    }

    /// 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);
    }
}