From 60a930c9baf4eda4cb91b3c3bf62a5cc869749f9 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 11 Oct 2019 11:34:53 -0700 Subject: [PATCH] Add test for the even handler leaking fix (#10768) Add a test for the even handler leaking fix addressed in #10626 https://github.com/PowerShell/PowerShell/pull/10626 The test is added to verify that PowerShell unregister the 'AppDomain.ProcessExit' event handler when a Runspace closes. --- test/xUnit/csharp/test_Runspace.cs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/test/xUnit/csharp/test_Runspace.cs b/test/xUnit/csharp/test_Runspace.cs index 2042ee7d6f..c0239e7db3 100644 --- a/test/xUnit/csharp/test_Runspace.cs +++ b/test/xUnit/csharp/test_Runspace.cs @@ -2,9 +2,9 @@ // Licensed under the MIT License. using System; -using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Runspaces; +using System.Reflection; using Xunit; namespace PSTests.Sequential @@ -101,5 +101,29 @@ namespace PSTests.Sequential runspace.Close(); } } + + [SkippableFact] + public void TestAppDomainProcessExitEvenHandlerNotLeaking() + { + Skip.IfNot(Platform.IsWindows); + + EventHandler eventHandler; + Delegate[] delegates; + FieldInfo field = typeof(AppContext).GetField("ProcessExit", BindingFlags.NonPublic | BindingFlags.Static); + + // Open runspace and invoke script. + using (var ps = PowerShell.Create()) + { + ps.AddScript("1").Invoke(); + eventHandler = (EventHandler)field.GetValue(null); + delegates = eventHandler.GetInvocationList(); + Assert.Contains(delegates, d => d.Method.Name == "CurrentDomain_ProcessExit"); + } + + // Handler registered by PowerShell should be unregistered. + eventHandler = (EventHandler)field.GetValue(null); + delegates = eventHandler.GetInvocationList(); + Assert.DoesNotContain(delegates, d => d.Method.Name == "CurrentDomain_ProcessExit"); + } } }