Files
betterxen/crates/loader/tests/imports_sync.rs
T

201 lines
7.9 KiB
Rust

// SPDX-License-Identifier: GPL-3.0-or-later
//! Integration tests for the `xenora imports sync` import compatibility generator.
//!
//! Tests verify:
//! - `iter_registered` lists all canonical handlers exactly once.
//! - `iter_aliases` identifies API-set alias registrations.
//! - The import backlog generator produces deterministic (idempotent) output
//! for a synthetic imports.csv input.
use std::sync::Arc;
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
fn standard_registry() -> ImportRegistry {
let mut registry = ImportRegistry::new();
register_standard_services(
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
registry
}
/// `iter_registered` must return each canonical service descriptor exactly once,
/// not duplicated by alias registrations.
#[test]
fn iter_registered_contains_each_handler_exactly_once() {
let registry = standard_registry();
let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
for (module, symbol, _status) in registry.iter_registered() {
let key = (module.to_ascii_lowercase(), symbol.to_string());
assert!(
seen.insert(key.clone()),
"duplicate canonical registration: {}!{}",
key.0,
key.1
);
}
assert!(!seen.is_empty(), "registry must not be empty");
}
/// All registered handlers must report a recognized status.
#[test]
fn all_registered_handlers_have_valid_status() {
let registry = standard_registry();
for (module, symbol, status) in registry.iter_registered() {
assert!(
matches!(
status,
ServiceStatus::Implemented | ServiceStatus::Partial | ServiceStatus::Stub
),
"unrecognized status for {}!{}: {:?}",
module,
symbol,
status
);
}
}
/// `iter_aliases` must yield API-set DLL names whose canonical module differs.
/// For example, `api-ms-win-core-processthreads-l1-1-0.dll` aliases to `kernel32.dll`.
#[test]
fn iter_aliases_yields_api_set_entries() {
let registry = standard_registry();
let aliases: Vec<_> = registry.iter_aliases().collect();
// There must be at least one API-set alias registered
assert!(
!aliases.is_empty(),
"expected at least one API-set alias; registry has none"
);
for (alias_module, _symbol, canonical_module) in &aliases {
// The alias module must differ from the canonical module
assert_ne!(
alias_module.to_ascii_lowercase(),
canonical_module.to_ascii_lowercase(),
"alias module must differ from canonical: {alias_module} vs {canonical_module}"
);
}
}
/// Idempotence: running the import backlog generator twice with identical input
/// produces byte-identical output.
#[test]
fn import_backlog_generator_is_idempotent() {
// Build a minimal synthetic imports.csv with a mix of supported, alias, and missing imports.
let synthetic_csv = r#"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster
"kernel32.dll","GetCurrentProcess",0x00001000,Windows Core Subsystems,true,implemented,false,"kernel32.dll",1,process and thread identity and handles
"api-ms-win-core-processthreads-l1-1-0.dll","GetCurrentProcess",0x00001008,Windows Core Subsystems,true,implemented,true,"kernel32.dll",1,process and thread identity and handles
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x00001010,Windows Core Subsystems,false,unsupported,false,"",1,process and thread identity and handles
"xmem.dll","XMemAlloc",0x00001018,Xbox Memory Management,true,partial,false,"xmem.dll",5,virtual memory and allocation lifecycle
"d3d12_xs.dll","D3D12CreateDevice",0x00001020,Xbox Graphics & Compute,false,missing,false,"",9,platform services and graphics
"#;
let dir = std::env::temp_dir().join(format!(
"xenora-imports-sync-idempotence-{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("imports.csv"), synthetic_csv).unwrap();
// Helper: generate the backlog and return its content.
let generate = || -> String {
let registry = standard_registry();
// Build the backlog directly using the same logic as the CLI.
let mut md = String::new();
md.push_str("# Xenora import compatibility backlog\n\n");
md.push_str("Generated by `xenora imports sync`. Do not edit manually.\n");
md.push_str("Re-run after adding service handlers to refresh this file.\n\n");
// Parse imports.csv
let csv_text = std::fs::read_to_string(dir.join("imports.csv")).unwrap();
let mut counts: std::collections::BTreeMap<&'static str, usize> = Default::default();
let mut total = 0usize;
let mut missing_entries: Vec<(u8, String, String)> = Vec::new();
for line in csv_text.lines().skip(1) {
let fields: Vec<&str> = line.splitn(10, ',').collect();
if fields.len() < 2 {
continue;
}
let module = fields[0].trim_matches('"').to_string();
let symbol = fields[1].trim_matches('"').to_string();
if module.is_empty() || symbol.is_empty() {
continue;
}
let binding = registry.binding(&module, &symbol);
let status = binding.map(|b| b.status);
let label: &'static str = match status {
Some(ServiceStatus::Implemented) => "implemented",
Some(ServiceStatus::Partial) => "partial",
Some(ServiceStatus::Stub) => "stub",
None => "missing",
};
*counts.entry(label).or_default() += 1;
total += 1;
if binding.is_none() {
fn priority_key(m: &str) -> u8 {
if m.contains("processthreads") {
1
} else if m.contains("core-synch") {
3
} else if m == "xmem.dll" {
5
} else {
9
}
}
missing_entries.push((priority_key(&module), module, symbol));
}
}
md.push_str("## Summary\n\n");
md.push_str(&format!("Total: {total}\n"));
for (label, count) in &counts {
md.push_str(&format!("{label}: {count}\n"));
}
missing_entries.sort();
md.push_str("\n## Missing\n");
for (_p, module, symbol) in &missing_entries {
md.push_str(&format!("- `{module}!{symbol}`\n"));
}
md
};
let first = generate();
let second = generate();
assert_eq!(
first, second,
"import backlog generator must produce identical output on identical input"
);
std::fs::remove_dir_all(&dir).unwrap();
}
/// `has_binding` must agree with `iter_registered` for well-known services.
#[test]
fn has_binding_matches_iter_registered() {
let registry = standard_registry();
// Collect all canonical keys from iter_registered
let registered: std::collections::HashSet<(String, String)> = registry
.iter_registered()
.map(|(m, s, _)| (m.to_ascii_lowercase(), s.to_string()))
.collect();
// All canonically registered services must respond true to has_binding
for (module, symbol) in &registered {
assert!(
registry.has_binding(module, symbol),
"has_binding must return true for canonical {module}!{symbol}"
);
}
// A known-absent service must respond false
assert!(
!registry.has_binding("d3d12_xs.dll", "D3D12CreateDevice"),
"d3d12_xs.dll!D3D12CreateDevice must not be registered"
);
}