using System.Diagnostics; using System.Linq; using WhiteMagic; using WhiteMagic.Native; using WhiteMagic.ProcessDiscovery; using Xunit; namespace WhiteMagicTest.ProcessDiscovery; /// /// Tests for process discovery via and the matching /// overloads. /// public sealed class ApplicationFinderTests { [Fact] public void Enumerate_finds_current_process_by_name() { string currentName = Process.GetCurrentProcess().ProcessName; Process[] found = ApplicationFinder.Enumerate(currentName).ToArray(); Assert.True(found.Length >= 1); Assert.Contains(found, p => p.Id == Process.GetCurrentProcess().Id); } [Fact] public void Open_by_name_returns_current_process_when_unique() { string currentName = Process.GetCurrentProcess().ProcessName; using Process process = ApplicationFinder.OpenProcess(currentName); Assert.Equal(Process.GetCurrentProcess().Id, process.Id); } [Fact] public void Open_throws_when_name_is_ambiguous() { // Look for a multi-instance system process; skip if the environment is not typical. Process[] candidates = Process.GetProcessesByName("svchost"); if (candidates.Length <= 1) { return; } InvalidOperationException ex = Assert.Throws( () => ApplicationFinder.OpenProcess("svchost")); Assert.Contains("svchost", ex.Message); Assert.Contains("ambiguous", ex.Message, StringComparison.OrdinalIgnoreCase); } [Fact] public void Open_throws_when_no_process_matches() { InvalidOperationException ex = Assert.Throws( () => ApplicationFinder.OpenProcess("probably-not-loaded-xyz.exe")); Assert.Contains("No process", ex.Message); } [Fact] public void OpenByWindowHandle_returns_owning_process() { IntPtr handle = Process.GetCurrentProcess().MainWindowHandle; if (handle == IntPtr.Zero) { return; } using Process process = ApplicationFinder.OpenByWindowHandle(handle); Assert.Equal(Process.GetCurrentProcess().Id, process.Id); } [Fact] public void OpenByWindowHandle_throws_for_zero_handle() { Assert.Throws("handle", () => ApplicationFinder.OpenByWindowHandle(IntPtr.Zero)); } [Fact] public void Magic_Open_by_name_attaches_to_current_process() { string currentName = Process.GetCurrentProcess().ProcessName; using var magic = Magic.Open(currentName); Assert.Equal(Process.GetCurrentProcess().Id, magic.Memory.ProcessId); } [Fact] public void Magic_OpenByWindowHandle_attaches_to_owning_process() { IntPtr handle = Process.GetCurrentProcess().MainWindowHandle; if (handle == IntPtr.Zero) { return; } using var magic = Magic.OpenByWindowHandle(handle); Assert.Equal(Process.GetCurrentProcess().Id, magic.Memory.ProcessId); } }