sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
#![cfg(all(feature = "system", feature = "disk"))]

use std::fs::{File, remove_file};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::thread::sleep;

use itertools::Itertools;
use sinf::disk::{DiskKind, DiskRefreshKind, Disks};

mod common;

fn should_skip() -> bool {
    if common::skip_unsupported(Disks::new()).is_none() {
        return true;
    }
    // With no physical core present, the environment is very likely a VM.
    sinf::system::System::physical_core_count().unwrap_or_default() == 0
}

#[test]
fn test_disks() {
    if should_skip() {
        return;
    }

    let mut disks = Disks::new().unwrap();
    assert!(disks.is_empty());
    disks.refresh(false);
    // Some disks are sometimes not retrieved on NetBSD.
    if std::env::var("NETBSD_CI").is_ok() {
        return;
    }
    assert!(!disks.is_empty());
}

#[test]
fn test_disk_refresh_kind() {
    if should_skip() {
        return;
    }

    if std::env::var("FREEBSD_CI").is_ok() {
        return;
    }

    for fs in [
        DiskRefreshKind::with_kind,
        DiskRefreshKind::without_kind,
        DiskRefreshKind::with_storage,
        DiskRefreshKind::without_storage,
        DiskRefreshKind::with_io_usage,
        DiskRefreshKind::without_io_usage,
    ]
    .iter()
    .powerset()
    {
        let mut refreshes = DiskRefreshKind::nothing();
        for f in fs {
            refreshes = f(refreshes);
        }

        let assertions = |name: &'static str, disks: &Disks| {
            if refreshes.kind() {
                // This would ideally assert that *all* are refreshed, but a weaker assertion is used because failures cannot be distinguished from
                #[cfg(not(any(
                    target_os = "freebsd",
                    target_os = "netbsd",
                    target_os = "windows"
                )))]
                assert!(
                    disks
                        .iter()
                        .any(|disk| disk.kind() != DiskKind::Unknown(-1)),
                    "{name}: disk.kind should be refreshed"
                );
            } else {
                assert!(
                    disks
                        .iter()
                        .all(|disk| disk.kind() == DiskKind::Unknown(-1)),
                    "{name}: disk.kind should not be refreshed"
                );
            }

            if refreshes.storage() {
                // This can fail in NetBSD CI, so skip it for now.
                if std::env::var("NETBSD_CI").is_err() {
                    // This would ideally assert that *all* are refreshed, but a weaker assertion is used because failures cannot be distinguished from
                    assert!(
                        disks
                            .iter()
                            .any(|disk| disk.available_space() != Default::default()),
                        "{name}: disk.available_space should be refreshed"
                    );
                    assert!(
                        disks
                            .iter()
                            .any(|disk| disk.total_space() != Default::default()),
                        "{name}: disk.total_space should be refreshed"
                    );
                }
                // Nothing can be asserted about booleans, since false is indistinguishable from not-refreshed.
            } else {
                assert!(
                    disks
                        .iter()
                        .all(|disk| disk.available_space() == Default::default()),
                    "{name}: disk.available_space should not be refreshed"
                );
                assert!(
                    disks
                        .iter()
                        .all(|disk| disk.total_space() == Default::default()),
                    "{name}: disk.total_space should not be refreshed"
                );
            }

            if refreshes.io_usage() {
                // This can fail in NetBSD CI, so skip it for now.
                if std::env::var("NETBSD_CI").is_err() {
                    // This would ideally assert that *all* are refreshed, but a weaker assertion is used because failures cannot be distinguished from
                    assert!(
                        disks.iter().any(|disk| disk.usage() != Default::default()),
                        "{name}: disk.usage should be refreshed"
                    );
                }
            } else {
                assert!(
                    disks.iter().all(|disk| disk.usage() == Default::default()),
                    "{name}: disk.usage should not be refreshed"
                );
            }
        };

        // Loading and refreshing with the requested details should work.
        let disks = Disks::new_with_refreshed_list_specifics(refreshes).unwrap();
        assertions("full", &disks);

        // Loading with a minimal `DiskRefreshKind`, then refreshing for additional detail, should also work.
        let mut disks =
            Disks::new_with_refreshed_list_specifics(DiskRefreshKind::nothing()).unwrap();
        disks.refresh_specifics(false, refreshes);
        assertions("incremental", &disks);
    }
}

#[test]
fn test_disks_usage() {
    if should_skip() {
        return;
    }

    // The test always fails in CI on Linux: /proc/diskstats does not update, regardless of how long the test waits.
    if cfg!(target_os = "linux") && std::env::var("CI").is_ok() {
        return;
    }
    if std::env::var("NETBSD_CI").is_ok() || std::env::var("FREEBSD_CI").is_ok() {
        return;
    }

    let mut disks = Disks::new_with_refreshed_list().unwrap();

    let path = match std::env::var("CARGO_TARGET_DIR") {
        Ok(p) => Path::new(&p).join("data.tmp"),
        _ => PathBuf::from("target/data.tmp"),
    };
    let mut file = File::create(&path).expect("failed to create temporary file");

    // Write 10 MB of data to the temporary file.
    let data = vec![1u8; 10 * 1024 * 1024];
    file.write_all(&data).unwrap();
    // The sync_all call ensures that all data is persisted to disk; without it, the test is flaky.
    file.sync_all().unwrap();

    // Wait briefly as a precaution.
    sleep(std::time::Duration::from_millis(500));
    disks.refresh(false);

    // Depending on the OS and disk configuration, several disks may report identical usage.
    let mut disk_usages = disks.iter().map(|d| d.usage()).collect::<Vec<_>>();
    disk_usages.dedup();

    let mut written_bytes = 0;
    for disk_usage in disk_usages {
        written_bytes += disk_usage.written_bytes;
    }

    let _ = remove_file(path);

    // written_bytes should have increased by about 10 MB, but this is not fully reliable on CI Linux.
    assert!(written_bytes > 0);
}