| 1 |
use amdgpu_sysfs::{gpu_handle::GpuHandle, sysfs::SysFS}; |
| 2 |
use rust_embed::RustEmbed; |
| 3 |
use std::fs; |
| 4 |
use tempfile::{tempdir, TempDir}; |
| 5 |
|
| 6 |
#[derive(RustEmbed)] |
| 7 |
#[folder = "tests/data/"] |
| 8 |
struct Asset; |
| 9 |
|
| 10 |
pub struct MockSysFs { |
| 11 |
temp_dir: TempDir, |
| 12 |
} |
| 13 |
|
| 14 |
impl MockSysFs { |
| 15 |
pub fn new(name: &str) -> Self { |
| 16 |
let temp_dir = tempdir().expect("Failed to create temp dir"); |
| 17 |
let path = temp_dir.path(); |
| 18 |
|
| 19 |
let path_prefix = format!("{name}/"); |
| 20 |
for file_name in Asset::iter() { |
| 21 |
if let Some(stripped_name) = file_name.strip_prefix(&path_prefix) { |
| 22 |
let target_path = path.join(stripped_name); |
| 23 |
|
| 24 |
if let Some(parent) = target_path.parent() { |
| 25 |
fs::create_dir_all(parent).expect("Could not create parent dir in temp dir"); |
| 26 |
} |
| 27 |
|
| 28 |
let contents = Asset::get(&file_name) |
| 29 |
.expect("Could not read file from embedded fs") |
| 30 |
.data; |
| 31 |
fs::write(target_path, contents).expect("Could not write contents to temp dir"); |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
Self { temp_dir } |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
impl SysFS for MockSysFs { |
| 40 |
fn get_path(&self) -> &std::path::Path { |
| 41 |
self.temp_dir.path() |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
pub fn create_mock_gpu_handle(name: &str) -> (GpuHandle, MockSysFs) { |
| 46 |
let mockfs = MockSysFs::new(name); |
| 47 |
|
| 48 |
( |
| 49 |
GpuHandle::new_from_path(mockfs.get_path().to_path_buf()) |
| 50 |
.expect("Failed to create GPU handle"), |
| 51 |
mockfs, |
| 52 |
) |
| 53 |
} |
| 54 |
|
| 55 |
#[macro_export] |
| 56 |
macro_rules! test_with_handle { |
| 57 |
($sysfs_name:expr, $($test_name:ident => {$($code:expr, $expected:expr),* $(,)?}),* $(,)?) => { |
| 58 |
$( |
| 59 |
#[test] |
| 60 |
fn $test_name() { |
| 61 |
let (handle, _mockfs) = $crate::sysfs::create_mock_gpu_handle($sysfs_name); |
| 62 |
$( |
| 63 |
let value = $code(&handle); |
| 64 |
pretty_assertions::assert_eq!(value, $expected); |
| 65 |
)* |
| 66 |
} |
| 67 |
)* |
| 68 |
}; |
| 69 |
} |
| 70 |
|
| 71 |
#[macro_export] |
| 72 |
macro_rules! test_with_hw_mon { |
| 73 |
($sysfs_name:expr, $($test_name:ident => {$($code:expr, $expected:expr),* $(,)?}),* $(,)?) => { |
| 74 |
$( |
| 75 |
#[test] |
| 76 |
fn $test_name() { |
| 77 |
let (handle, _mockfs) = $crate::sysfs::create_mock_gpu_handle($sysfs_name); |
| 78 |
let hw_mon = handle.hw_monitors.first().expect("Handle has no hw monitor"); |
| 79 |
$( |
| 80 |
let value = $code(&hw_mon); |
| 81 |
pretty_assertions::assert_eq!(value, $expected); |
| 82 |
)* |
| 83 |
} |
| 84 |
)* |
| 85 |
}; |
| 86 |
} |