sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
#![cfg(feature = "system")]
#![allow(clippy::assertions_on_constants)]

use sinf::{system::ProcessesToUpdate, system::System};

#[test]
fn test_refresh_system() {
    let Ok(mut sys) = System::new() else { return };
    sys.refresh_memory();
    sys.refresh_cpu_usage();
    assert!(sys.total_memory() != 0);
    assert!(sys.free_memory() != 0);
    assert!(sys.total_memory() >= sys.free_memory());
    assert!(sys.total_swap() >= sys.free_swap());
}

#[test]
fn test_refresh_process() {
    let Ok(mut sys) = System::new() else { return };
    assert!(sys.processes().is_empty(), "no process should be listed!");
    // Unsupported systems are not tested.

    if cfg!(not(feature = "apple-sandbox")) {
        assert_eq!(
            sys.refresh_processes(
                ProcessesToUpdate::Some(&[
                    sinf::system::get_current_pid().expect("failed to get current pid")
                ]),
                false
            ),
            1,
            "process not listed",
        );
        // Ensure that the process was added to the list.
        assert!(
            sys.process(sinf::system::get_current_pid().expect("failed to get current pid"))
                .is_some()
        );
    }
}

#[test]
fn test_get_process() {
    let Ok(mut sys) = System::new() else { return };
    sys.refresh_processes(ProcessesToUpdate::All, false);
    let current_pid = match sinf::system::get_current_pid() {
        Ok(pid) => pid,
        _ => panic!("get_current_pid should work!"),
    };
    if let Some(p) = sys.process(current_pid) {
        assert!(p.memory() > 0);
    }
}

#[test]
fn check_hostname_has_no_nuls() {
    if let Ok(hostname) = System::host_name() {
        assert!(!hostname.contains('\u{0}'))
    }
}

#[test]
fn check_uptime() {
    if System::new().is_ok() {
        let uptime = System::uptime();
        std::thread::sleep(std::time::Duration::from_millis(1000));
        let new_uptime = System::uptime().unwrap();
        assert!(uptime.unwrap() < new_uptime);
    }
}

#[test]
fn check_boot_time() {
    if System::new().is_ok() {
        assert_ne!(System::boot_time().unwrap(), 0);
    }
}

// This test verifies that the CPU usage computation remains sane when refreshed too frequently (multiple times in a row within a very small interval).
#[test]
fn test_consecutive_cpu_usage_update() {
    use sinf::{system::Pid, system::ProcessRefreshKind};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;

    if std::env::var("NETBSD_CI").is_ok() {
        // FIXME
        return;
    }

    let Ok(mut sys) = System::new_all() else {
        return;
    };
    assert!(!sys.cpus().is_empty());
    sys.refresh_processes_specifics(
        ProcessesToUpdate::All,
        true,
        ProcessRefreshKind::nothing().with_cpu(),
    );

    let stop = Arc::new(AtomicBool::new(false));
    // Spawn a few threads so that the CPU usage is actually affected.
    for it in 0..sys.cpus().len() / 2 + 1 {
        let stop_c = Arc::clone(&stop);
        std::thread::spawn(move || {
            while !stop_c.load(Ordering::Relaxed) {
                if it != 0 {
                    // The first thread runs at 100% so that it is noticeable.
                    std::thread::sleep(Duration::from_millis(1));
                }
            }
        });
    }

    let mut pids = sys.processes().keys().copied().take(2).collect::<Vec<_>>();
    let pid = std::process::id();
    pids.push(Pid::from_u32(pid));
    assert_eq!(pids.len(), 3);

    for it in 0..3 {
        std::thread::sleep(sinf::system::MINIMUM_CPU_UPDATE_INTERVAL + Duration::from_millis(1));
        for pid in &pids {
            sys.refresh_processes_specifics(
                ProcessesToUpdate::Some(&[*pid]),
                true,
                ProcessRefreshKind::nothing().with_cpu(),
            );
        }
        let usage = sys.process(pids[2]).unwrap().cpu_usage();
        assert!(
            usage.is_finite() && (0.0..=sys.cpus().len() as f32 * 100.).contains(&usage),
            "invalid CPU usage {usage} at iteration {it}",
        );
    }
    stop.store(true, Ordering::Relaxed);
}

#[test]
fn test_refresh_memory() {
    // CI may not have swap, so some checks are disabled in that case to prevent the test from failing.
    fn has_swap() -> bool {
        if cfg!(target_os = "macos") {
            // Swap can be 0 on macOS.
            return false;
        } else if !cfg!(any(target_os = "linux", target_os = "android")) {
            return true;
        }
        std::fs::read_to_string("/proc/meminfo")
            .ok()
            .and_then(|s| {
                s.lines()
                    .find(|l| l.starts_with("SwapTotal:"))
                    .and_then(|l| l.split_whitespace().nth(1)?.parse::<u64>().ok())
            })
            .is_some_and(|bytes| bytes != 0)
    }

    // On Linux, memory information is always retrieved because it comes from the same file.
    let is_linux = cfg!(any(target_os = "linux", target_os = "android"));
    let has_swap = has_swap();
    let Ok(mut s) = System::new() else { return };
    assert_eq!(s.total_memory(), 0);
    assert_eq!(s.free_memory(), 0);

    s.refresh_memory_specifics(sinf::system::MemoryRefreshKind::nothing().with_ram());
    assert_ne!(s.total_memory(), 0);
    assert_ne!(s.free_memory(), 0);

    if is_linux && has_swap {
        assert_ne!(s.total_swap(), 0);
        assert_ne!(s.free_swap(), 0);
    } else {
        assert_eq!(s.total_swap(), 0);
        assert_eq!(s.free_swap(), 0);
    }

    let mut s = System::new().unwrap();
    assert_eq!(s.total_swap(), 0);
    assert_eq!(s.free_swap(), 0);

    if std::env::var("APPLE_CI").is_ok() {
        // macOS CI apparently has no swap, so the test cannot proceed past this point.
        return;
    }

    s.refresh_memory_specifics(sinf::system::MemoryRefreshKind::nothing().with_swap());

    if has_swap {
        assert_ne!(s.total_swap(), 0);
        assert_ne!(s.free_swap(), 0);
    }

    if is_linux {
        assert_ne!(s.total_memory(), 0);
        assert_ne!(s.free_memory(), 0);
    } else {
        assert_eq!(s.total_memory(), 0);
        assert_eq!(s.free_memory(), 0);
    }

    let mut s = System::new().unwrap();
    s.refresh_memory();
    if has_swap {
        assert_ne!(s.total_swap(), 0);
        assert_ne!(s.free_swap(), 0);
    }
    assert_ne!(s.total_memory(), 0);
    assert_ne!(s.free_memory(), 0);
}

#[test]
#[cfg(feature = "multithread")]
fn same_pid_multithreaded_refresh() {
    use sinf::{system::ProcessRefreshKind, system::System, system::UpdateKind};

    let Ok(mut system) = System::new() else {
        return;
    };
    let pid = sinf::system::get_current_pid().expect("failed to get current pid");
    let kind = ProcessRefreshKind::nothing()
        .with_cmd(UpdateKind::Always)
        .with_environ(UpdateKind::Always);
    system.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, kind);
    let pids = vec![pid; 20000];
    system.refresh_processes_specifics(ProcessesToUpdate::Some(&pids), false, kind);
}