//! Unit tests for Memory profiling module

#[cfg(test)]
mod tests {
    use super::super::*;

    #[test]
    fn test_memory_bandwidth_measurement() {
        let result = measure_memory_bandwidth();
        assert!(result.is_ok());

        let bandwidth = result.unwrap();
        assert!(bandwidth.read_bandwidth_gbps > 0.0);
        assert!(bandwidth.write_bandwidth_gbps > 0.0);
        assert!(bandwidth.copy_bandwidth_gbps > 0.0);
        assert!(bandwidth.buffer_size_bytes > 0);
        assert!(bandwidth.iterations > 0);
    }

    #[test]
    fn test_memory_bandwidth_with_params() {
        let result = measure_memory_bandwidth_with_params(32, 3);
        assert!(result.is_ok());

        let bandwidth = result.unwrap();
        assert_eq!(bandwidth.buffer_size_bytes, 32 * 1024 * 1024);
        assert_eq!(bandwidth.iterations, 3);
        assert!(bandwidth.read_bandwidth_gbps > 0.0);
    }

    #[test]
    fn test_memory_latency_measurement() {
        let result = test_memory_latency(1024 * 1024); // 1MB
        assert!(result.is_ok());

        let latency = result.unwrap();
        assert!(latency.latency_ns > 0.0);
        assert!(latency.working_set_bytes > 0);
    }

    #[test]
    fn test_cache_performance() {
        let result = measure_cache_performance();
        assert!(result.is_ok());

        let cache = result.unwrap();
        // Verify latencies are positive (measurement worked)
        assert!(cache.l1_latency_ns > 0.0);
        assert!(cache.l2_latency_ns > 0.0);
        assert!(cache.l3_latency_ns > 0.0);
        // Note: On modern unified memory architectures (like Apple M2),
        // cache latency hierarchy may not be strictly ordered due to
        // measurement precision and cache architecture differences
    }

    #[test]
    fn test_memory_stress_test() {
        let result = run_memory_stress_test(std::time::Duration::from_secs(1));
        assert!(result.is_ok());

        let stress = result.unwrap();
        assert!(stress.peak_bandwidth_gbps >= 0.0);
    }

    #[test]
    fn test_memory_bandwidth_params_validation() {
        // Test with very small size
        let result = measure_memory_bandwidth_with_params(1, 1);
        assert!(result.is_ok());

        // Test with reasonable size
        let result = measure_memory_bandwidth_with_params(64, 5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_numa_bandwidth_call() {
        // NUMA may not be available on all systems
        let _result = crate::profiling::memory::numa::test_numa_bandwidth();
        // Just verify it doesn't panic - result may be Ok or Err
    }
}
