From 42173541a54cb0e8e4d461816675b194f9f6445d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Jun 2021 12:26:34 +0000 Subject: [PATCH 1/7] Bump Newtonsoft.Json from 12.0.2 to 13.0.1 Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 12.0.2 to 13.0.1. - [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases) - [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/12.0.2...13.0.1) Signed-off-by: dependabot[bot] --- .../PowerShellEditorServices.Test.E2E.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PowerShellEditorServices.Test.E2E/PowerShellEditorServices.Test.E2E.csproj b/test/PowerShellEditorServices.Test.E2E/PowerShellEditorServices.Test.E2E.csproj index 2c443e008..af00ee177 100644 --- a/test/PowerShellEditorServices.Test.E2E/PowerShellEditorServices.Test.E2E.csproj +++ b/test/PowerShellEditorServices.Test.E2E/PowerShellEditorServices.Test.E2E.csproj @@ -9,7 +9,7 @@ - + From de25fc0f9b1bb3d436e78ed6ea1c20a492bc3db5 Mon Sep 17 00:00:00 2001 From: dkattan <1424395+dkattan@users.noreply.github.com> Date: Tue, 13 Jul 2021 12:39:40 -0500 Subject: [PATCH 2/7] Changed all references to languagemode to initialSessionState --- .../Commands/StartEditorServicesCommand.cs | 4 +- .../Configuration/EditorServicesConfig.cs | 6 +-- .../Internal/EditorServicesRunner.cs | 2 +- .../Hosting/HostStartupInfo.cs | 13 +++--- .../PowerShellContextService.cs | 40 +++++++------------ .../PowerShellContextFactory.cs | 5 +-- 6 files changed, 30 insertions(+), 40 deletions(-) diff --git a/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs b/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs index 0e698f812..acc52700a 100644 --- a/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs +++ b/src/PowerShellEditorServices.Hosting/Commands/StartEditorServicesCommand.cs @@ -349,6 +349,8 @@ private EditorServicesConfig CreateConfigObject() var profile = (PSObject)GetVariableValue("profile"); var hostInfo = new HostInfo(HostName, HostProfileId, HostVersion); + var iss = Runspace.DefaultRunspace.InitialSessionState; + iss.LanguageMode = Runspace.DefaultRunspace.SessionStateProxy.LanguageMode; var editorServicesConfig = new EditorServicesConfig(hostInfo, Host, SessionDetailsPath, bundledModulesPath, LogPath) { FeatureFlags = FeatureFlags, @@ -357,7 +359,7 @@ private EditorServicesConfig CreateConfigObject() AdditionalModules = AdditionalModules, LanguageServiceTransport = GetLanguageServiceTransport(), DebugServiceTransport = GetDebugServiceTransport(), - LanguageMode = Runspace.DefaultRunspace.SessionStateProxy.LanguageMode, + InitialSessionState = iss, ProfilePaths = new ProfilePathConfig { AllUsersAllHosts = GetProfilePathFromProfileObject(profile, ProfileUserKind.AllUsers, ProfileHostKind.AllHosts), diff --git a/src/PowerShellEditorServices.Hosting/Configuration/EditorServicesConfig.cs b/src/PowerShellEditorServices.Hosting/Configuration/EditorServicesConfig.cs index 5228ceced..79d49b83c 100644 --- a/src/PowerShellEditorServices.Hosting/Configuration/EditorServicesConfig.cs +++ b/src/PowerShellEditorServices.Hosting/Configuration/EditorServicesConfig.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Host; +using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.EditorServices.Hosting { @@ -111,10 +112,9 @@ public EditorServicesConfig( public ProfilePathConfig ProfilePaths { get; set; } /// - /// The language mode inherited from the orginal PowerShell process. - /// This will be used when creating runspaces so that we honor the same language mode. + /// The InitialSessionState to use when creating runspaces. LanguageMode can be set here. /// - public PSLanguageMode LanguageMode { get; internal set; } + public InitialSessionState InitialSessionState { get; internal set; } public string StartupBanner { get; set; } = @" diff --git a/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs b/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs index e49da8527..a68842876 100644 --- a/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs +++ b/src/PowerShellEditorServices.Hosting/Internal/EditorServicesRunner.cs @@ -288,7 +288,7 @@ private HostStartupInfo CreateHostStartupInfo() profilePaths, _config.FeatureFlags, _config.AdditionalModules, - _config.LanguageMode, + _config.InitialSessionState, _config.LogPath, (int)_config.LogLevel, consoleReplEnabled: _config.ConsoleRepl != ConsoleReplKind.None, diff --git a/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs b/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs index 9fc788e0d..be1491471 100644 --- a/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs +++ b/src/PowerShellEditorServices/Hosting/HostStartupInfo.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Host; +using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.EditorServices.Hosting { @@ -92,10 +93,10 @@ public sealed class HostStartupInfo public string LogPath { get; } /// - /// The language mode inherited from the orginal PowerShell process. - /// This will be used when creating runspaces so that we honor the same language mode. + /// The initialSessionState will be inherited from the orginal PowerShell process. + /// This will be used when creating runspaces so that we honor the same initialSessionState including allowed modules, cmdlets and language mode. /// - public PSLanguageMode LanguageMode { get; } + public InitialSessionState InitialSessionState { get; } /// /// The minimum log level of log events to be logged. @@ -135,7 +136,7 @@ public sealed class HostStartupInfo /// The path to the user specific profile. /// Flags of features to enable. /// Names or paths of additional modules to import. - /// The language mode inherited from the orginal PowerShell process. This will be used when creating runspaces so that we honor the same language mode. + /// The language mode inherited from the orginal PowerShell process. This will be used when creating runspaces so that we honor the same initialSessionState including allowed modules, cmdlets and language mode. /// The path to log to. /// The minimum log event level. /// Enable console if true. @@ -149,7 +150,7 @@ public HostStartupInfo( ProfilePathInfo profilePaths, IReadOnlyList featureFlags, IReadOnlyList additionalModules, - PSLanguageMode languageMode, + InitialSessionState initialSessionState, string logPath, int logLevel, bool consoleReplEnabled, @@ -163,7 +164,7 @@ public HostStartupInfo( ProfilePaths = profilePaths; FeatureFlags = featureFlags ?? Array.Empty(); AdditionalModules = additionalModules ?? Array.Empty(); - LanguageMode = languageMode; + InitialSessionState = initialSessionState; LogPath = logPath; LogLevel = logLevel; ConsoleReplEnabled = consoleReplEnabled; diff --git a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs index 198cd26d9..9c32ff317 100644 --- a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs +++ b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs @@ -219,7 +219,7 @@ public static PowerShellContextService Create( EditorServicesPSHostUserInterface hostUserInterface = hostStartupInfo.ConsoleReplEnabled - ? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, hostStartupInfo.PSHost, logger) + ? (EditorServicesPSHostUserInterface)new TerminalPSHostUserInterface(powerShellContext, hostStartupInfo.PSHost, logger) : new ProtocolPSHostUserInterface(languageServer, powerShellContext, logger); EditorServicesPSHost psHost = @@ -230,7 +230,7 @@ public static PowerShellContextService Create( logger); logger.LogTrace("Creating initial PowerShell runspace"); - Runspace initialRunspace = PowerShellContextService.CreateRunspace(psHost, hostStartupInfo.LanguageMode); + Runspace initialRunspace = PowerShellContextService.CreateRunspace(psHost, hostStartupInfo.InitialSessionState); powerShellContext.Initialize(hostStartupInfo.ProfilePaths, initialRunspace, true, hostUserInterface); powerShellContext.ImportCommandsModuleAsync(); @@ -274,7 +274,7 @@ public static Runspace CreateRunspace( var psHost = new EditorServicesPSHost(powerShellContext, hostDetails, hostUserInterface, logger); powerShellContext.ConsoleWriter = hostUserInterface; powerShellContext.ConsoleReader = hostUserInterface; - return CreateRunspace(psHost, hostDetails.LanguageMode); + return CreateRunspace(psHost, hostDetails.InitialSessionState); } /// @@ -283,20 +283,8 @@ public static Runspace CreateRunspace( /// The PSHost that will be used for this Runspace. /// The language mode inherited from the orginal PowerShell process. This will be used when creating runspaces so that we honor the same language mode. /// - public static Runspace CreateRunspace(PSHost psHost, PSLanguageMode languageMode) + public static Runspace CreateRunspace(PSHost psHost, InitialSessionState initialSessionState) { - InitialSessionState initialSessionState; - if (Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1") { - initialSessionState = InitialSessionState.CreateDefault(); - } else { - initialSessionState = InitialSessionState.CreateDefault2(); - } - - // Create and initialize a new Runspace while honoring the LanguageMode of the original runspace - // that started PowerShell Editor Services. This is because the PowerShell Integrated Console - // should have the same LanguageMode of whatever is set by the system. - initialSessionState.LanguageMode = languageMode; - // We set the process scope's execution policy (which is really the runspace's scope) to // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this @@ -612,7 +600,7 @@ public async Task> ExecuteCommandAsync( // cancelled prompt when it's called again. if (executionOptions.AddToHistory) { - this.PromptContext.AddToHistory(executionOptions.InputString ?? psCommand.Commands[0].CommandText); + this.PromptContext.AddToHistory(executionOptions.InputString ?? psCommand.Commands [0].CommandText); } bool hadErrors = false; @@ -666,7 +654,7 @@ public async Task> ExecuteCommandAsync( // Instruct PowerShell to send output and errors to the host if (executionOptions.WriteOutputToHost) { - psCommand.Commands[0].MergeMyResults( + psCommand.Commands [0].MergeMyResults( PipelineResultTypes.Error, PipelineResultTypes.Output); @@ -701,7 +689,7 @@ public async Task> ExecuteCommandAsync( if (executionOptions.WriteInputToHost) { this.WriteOutput( - executionOptions.InputString ?? psCommand.Commands[0].CommandText, + executionOptions.InputString ?? psCommand.Commands [0].CommandText, includeNewLine: true); } @@ -1014,7 +1002,7 @@ public Task> ExecuteScriptStringAsync( Validate.IsNotNull(nameof(scriptString), scriptString); PSCommand command = null; - if(CurrentRunspace.Runspace.SessionStateProxy.LanguageMode != PSLanguageMode.FullLanguage) + if (CurrentRunspace.Runspace.SessionStateProxy.LanguageMode != PSLanguageMode.FullLanguage) { try { @@ -1029,7 +1017,7 @@ public Task> ExecuteScriptStringAsync( } // fall back to old behavior - if(command == null) + if (command == null) { command = new PSCommand().AddScript(scriptString.Trim()); } @@ -1729,7 +1717,7 @@ internal static string WildcardEscapePath(string path, bool escapeSpaces = false var sb = new StringBuilder(); for (int i = 0; i < path.Length; i++) { - char curr = path[i]; + char curr = path [i]; switch (curr) { // Escape '[', ']', '?' and '*' with '`' @@ -1783,11 +1771,11 @@ internal static string UnescapeWildcardEscapedPath(string wildcardEscapedPath) for (int i = 0; i < wildcardEscapedPath.Length; i++) { // If we see a backtick perform a lookahead - char curr = wildcardEscapedPath[i]; + char curr = wildcardEscapedPath [i]; if (curr == '`' && i + 1 < wildcardEscapedPath.Length) { // If the next char is an escapable one, don't add this backtick to the new string - char next = wildcardEscapedPath[i + 1]; + char next = wildcardEscapedPath [i + 1]; switch (next) { case '[': @@ -2178,14 +2166,14 @@ private void SetExecutionPolicy() // set to expected values, so we must sift through those. ExecutionPolicy policyToSet = ExecutionPolicy.Bypass; - var currentUserPolicy = (ExecutionPolicy)policies[policies.Count - 2].Members["ExecutionPolicy"].Value; + var currentUserPolicy = (ExecutionPolicy)policies [policies.Count - 2].Members ["ExecutionPolicy"].Value; if (currentUserPolicy != ExecutionPolicy.Undefined) { policyToSet = currentUserPolicy; } else { - var localMachinePolicy = (ExecutionPolicy)policies[policies.Count - 1].Members["ExecutionPolicy"].Value; + var localMachinePolicy = (ExecutionPolicy)policies [policies.Count - 1].Members ["ExecutionPolicy"].Value; if (localMachinePolicy != ExecutionPolicy.Undefined) { policyToSet = localMachinePolicy; diff --git a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs index 41c3e4730..3ed92a98e 100644 --- a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs +++ b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Management.Automation; +using System.Management.Automation.Runspaces; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -49,9 +50,7 @@ public static PowerShellContextService Create(ILogger logger) TestProfilePaths, new List(), new List(), - // TODO: We want to replace this property with an entire initial session state, - // which would then also control the process-scoped execution policy. - PSLanguageMode.FullLanguage, + InitialSessionState.CreateDefault(), null, 0, consoleReplEnabled: false, From 11fe8269009c820eba1013d762ff44524f674929 Mon Sep 17 00:00:00 2001 From: dkattan <1424395+dkattan@users.noreply.github.com> Date: Tue, 13 Jul 2021 12:57:45 -0500 Subject: [PATCH 3/7] Fixed whitespace issues --- .../PowerShellContextService.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs index 9c32ff317..2e1fa6ea8 100644 --- a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs +++ b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs @@ -58,7 +58,7 @@ static PowerShellContextService() { MethodInfo setterInfo = typeof(Runspace).GetProperty("ApartmentState").GetSetMethod(); Delegate setter = Delegate.CreateDelegate(typeof(Action), firstArgument: null, method: setterInfo); - s_runspaceApartmentStateSetter = (Action)setter; + s_runspaceApartmentStateSetter = (Action) setter; } if (VersionUtils.IsPS7OrGreater) @@ -219,7 +219,7 @@ public static PowerShellContextService Create( EditorServicesPSHostUserInterface hostUserInterface = hostStartupInfo.ConsoleReplEnabled - ? (EditorServicesPSHostUserInterface)new TerminalPSHostUserInterface(powerShellContext, hostStartupInfo.PSHost, logger) + ? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, hostStartupInfo.PSHost, logger) : new ProtocolPSHostUserInterface(languageServer, powerShellContext, logger); EditorServicesPSHost psHost = @@ -600,7 +600,7 @@ public async Task> ExecuteCommandAsync( // cancelled prompt when it's called again. if (executionOptions.AddToHistory) { - this.PromptContext.AddToHistory(executionOptions.InputString ?? psCommand.Commands [0].CommandText); + this.PromptContext.AddToHistory(executionOptions.InputString ?? psCommand.Commands[0].CommandText); } bool hadErrors = false; @@ -654,7 +654,7 @@ public async Task> ExecuteCommandAsync( // Instruct PowerShell to send output and errors to the host if (executionOptions.WriteOutputToHost) { - psCommand.Commands [0].MergeMyResults( + psCommand.Commands[0].MergeMyResults( PipelineResultTypes.Error, PipelineResultTypes.Output); @@ -689,7 +689,7 @@ psCommand.Commands [0].MergeMyResults( if (executionOptions.WriteInputToHost) { this.WriteOutput( - executionOptions.InputString ?? psCommand.Commands [0].CommandText, + executionOptions.InputString ?? psCommand.Commands[0].CommandText, includeNewLine: true); } @@ -1717,7 +1717,7 @@ internal static string WildcardEscapePath(string path, bool escapeSpaces = false var sb = new StringBuilder(); for (int i = 0; i < path.Length; i++) { - char curr = path [i]; + char curr = path[i]; switch (curr) { // Escape '[', ']', '?' and '*' with '`' @@ -1771,11 +1771,11 @@ internal static string UnescapeWildcardEscapedPath(string wildcardEscapedPath) for (int i = 0; i < wildcardEscapedPath.Length; i++) { // If we see a backtick perform a lookahead - char curr = wildcardEscapedPath [i]; + char curr = wildcardEscapedPath[i]; if (curr == '`' && i + 1 < wildcardEscapedPath.Length) { // If the next char is an escapable one, don't add this backtick to the new string - char next = wildcardEscapedPath [i + 1]; + char next = wildcardEscapedPath[i + 1]; switch (next) { case '[': @@ -2166,14 +2166,14 @@ private void SetExecutionPolicy() // set to expected values, so we must sift through those. ExecutionPolicy policyToSet = ExecutionPolicy.Bypass; - var currentUserPolicy = (ExecutionPolicy)policies [policies.Count - 2].Members ["ExecutionPolicy"].Value; + var currentUserPolicy = (ExecutionPolicy) policies[policies.Count - 2].Members["ExecutionPolicy"].Value; if (currentUserPolicy != ExecutionPolicy.Undefined) { policyToSet = currentUserPolicy; } else { - var localMachinePolicy = (ExecutionPolicy)policies [policies.Count - 1].Members ["ExecutionPolicy"].Value; + var localMachinePolicy = (ExecutionPolicy) policies[policies.Count - 1].Members["ExecutionPolicy"].Value; if (localMachinePolicy != ExecutionPolicy.Undefined) { policyToSet = localMachinePolicy; @@ -2345,7 +2345,7 @@ private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs ar case RunspaceState.Closed: case RunspaceState.Broken: // If the runspace closes or fails, pop the runspace - ((IHostSupportsInteractiveSession)this).PopRunspace(); + ((IHostSupportsInteractiveSession) this).PopRunspace(); break; } } @@ -2357,7 +2357,7 @@ private static IEnumerable GetLoadableProfilePaths(ProfilePathInfo profi yield break; } - foreach (string path in new [] { profilePaths.AllUsersAllHosts, profilePaths.AllUsersCurrentHost, profilePaths.CurrentUserAllHosts, profilePaths.CurrentUserCurrentHost }) + foreach (string path in new[] { profilePaths.AllUsersAllHosts, profilePaths.AllUsersCurrentHost, profilePaths.CurrentUserAllHosts, profilePaths.CurrentUserCurrentHost }) { if (path != null && File.Exists(path)) { @@ -2389,12 +2389,12 @@ private void StartCommandLoopOnRunspaceAvailable() void availabilityChangedHandler(object runspace, RunspaceAvailabilityEventArgs eventArgs) { if (eventArgs.RunspaceAvailability != RunspaceAvailability.Available || - this.versionSpecificOperations.IsDebuggerStopped(this.PromptNest, (Runspace)runspace)) + this.versionSpecificOperations.IsDebuggerStopped(this.PromptNest, (Runspace) runspace)) { return; } - ((Runspace)runspace).AvailabilityChanged -= availabilityChangedHandler; + ((Runspace) runspace).AvailabilityChanged -= availabilityChangedHandler; Interlocked.Exchange(ref this.isCommandLoopRestarterSet, 0); this.ConsoleReader?.StartCommandLoop(); } From edf177fadc348362e8836d3ed8fada0b63aeefff Mon Sep 17 00:00:00 2001 From: dkattan <1424395+dkattan@users.noreply.github.com> Date: Tue, 13 Jul 2021 20:12:28 -0500 Subject: [PATCH 4/7] Renamed SetExecutionPolicy to RestoreExecutionPolicy and moved it to the Create method used in production to prevent tests from failing when it restores the machine's execution policy. --- .../PowerShellContextService.cs | 23 +++++-------------- .../PowerShellContextFactory.cs | 19 +++++++++++---- .../Session/PowerShellContextTests.cs | 2 +- 3 files changed, 21 insertions(+), 23 deletions(-) diff --git a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs index 2e1fa6ea8..5a9130aa7 100644 --- a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs +++ b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs @@ -251,7 +251,10 @@ public static PowerShellContextService Create( sendErrorToHost: true); #pragma warning restore CS4014 } - + if(VersionUtils.IsWindows) + { + powerShellContext.RestoreExecutionPolicy(); + } return powerShellContext; } @@ -263,7 +266,7 @@ public static PowerShellContextService Create( /// The EditorServicesPSHostUserInterface to use for this instance. /// An ILogger implementation to use for this instance. /// - public static Runspace CreateRunspace( + public static Runspace CreateTestRunspace( HostStartupInfo hostDetails, PowerShellContextService powerShellContext, EditorServicesPSHostUserInterface hostUserInterface, @@ -285,15 +288,6 @@ public static Runspace CreateRunspace( /// public static Runspace CreateRunspace(PSHost psHost, InitialSessionState initialSessionState) { - // We set the process scope's execution policy (which is really the runspace's scope) to - // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI - // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this - // behavior for consistency such that unit tests can pass in a similar environment. - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; - } - Runspace runspace = RunspaceFactory.CreateRunspace(psHost, initialSessionState); // Windows PowerShell must be hosted in STA mode @@ -421,11 +415,6 @@ public void Initialize( { this.PromptContext = new LegacyReadLineContext(this); } - - if (VersionUtils.IsWindows) - { - this.SetExecutionPolicy(); - } } /// @@ -2140,7 +2129,7 @@ private static string GetStringForPSCommand(PSCommand psCommand) return stringBuilder.ToString(); } - private void SetExecutionPolicy() + private void RestoreExecutionPolicy() { this.logger.LogTrace("Setting execution policy..."); diff --git a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs index 3ed92a98e..603e9a2f3 100644 --- a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs +++ b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs @@ -6,6 +6,7 @@ using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; +using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -37,11 +38,19 @@ internal static class PowerShellContextFactory TestUtilities.NormalizePath("../../../../../module")); public static System.Management.Automation.Runspaces.Runspace InitialRunspace; - + public static PowerShellContextService Create(ILogger logger) { PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, isPSReadLineEnabled: false); - + var initialSessionState = InitialSessionState.CreateDefault(); + // We set the process scope's execution policy (which is really the runspace's scope) to + // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI + // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this + // behavior for consistency such that unit tests can pass in a similar environment. + if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; + } HostStartupInfo testHostDetails = new HostStartupInfo( "PowerShell Editor Services Test Host", "Test.PowerShellEditorServices", @@ -50,19 +59,19 @@ public static PowerShellContextService Create(ILogger logger) TestProfilePaths, new List(), new List(), - InitialSessionState.CreateDefault(), + initialSessionState, null, 0, consoleReplEnabled: false, usesLegacyReadLine: false, bundledModulePath: BundledModulePath); - InitialRunspace = PowerShellContextService.CreateRunspace( + InitialRunspace = PowerShellContextService.CreateTestRunspace( testHostDetails, powerShellContext, new TestPSHostUserInterface(powerShellContext, logger), logger); - + powerShellContext.Initialize( TestProfilePaths, InitialRunspace, diff --git a/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs b/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs index ba1e07611..c772a9a33 100644 --- a/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs +++ b/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs @@ -130,7 +130,7 @@ public async Task CanResolveAndLoadProfilesForHostId() "$($profile.AllUsersCurrentHost) " + "$($profile.CurrentUserAllHosts) " + "$($profile.CurrentUserCurrentHost) " + - "$(Assert-ProfileLoaded)\""); + "$(Assert-ProfileLoaded)\"");//.Commands[0].MergeMyResults(System.Management.Automation.Runspaces.PipelineResultTypes.All, System.Management.Automation.Runspaces.PipelineResultTypes.Output); var result = await this.powerShellContext.ExecuteCommandAsync( From 5cfc62ef0ebcb9e88dc6031e988814b65692476d Mon Sep 17 00:00:00 2001 From: dkattan <1424395+dkattan@users.noreply.github.com> Date: Tue, 13 Jul 2021 20:24:37 -0500 Subject: [PATCH 5/7] Removed unnecessary test change --- .../Session/PowerShellContextTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs b/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs index c772a9a33..ba1e07611 100644 --- a/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs +++ b/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs @@ -130,7 +130,7 @@ public async Task CanResolveAndLoadProfilesForHostId() "$($profile.AllUsersCurrentHost) " + "$($profile.CurrentUserAllHosts) " + "$($profile.CurrentUserCurrentHost) " + - "$(Assert-ProfileLoaded)\"");//.Commands[0].MergeMyResults(System.Management.Automation.Runspaces.PipelineResultTypes.All, System.Management.Automation.Runspaces.PipelineResultTypes.Output); + "$(Assert-ProfileLoaded)\""); var result = await this.powerShellContext.ExecuteCommandAsync( From 384606cc40a62e956491a8a865c14d379864bd7e Mon Sep 17 00:00:00 2001 From: dkattan <1424395+dkattan@users.noreply.github.com> Date: Wed, 14 Jul 2021 13:08:38 -0500 Subject: [PATCH 6/7] Added back logic that sets ExecutionPolicy to Bypass as this is necessary for the modules to load in E2E tests and production. --- .../PowerShellContext/PowerShellContextService.cs | 9 +++++++++ .../PowerShellContextFactory.cs | 9 +-------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs index 5a9130aa7..6f0a5b774 100644 --- a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs +++ b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs @@ -288,6 +288,15 @@ public static Runspace CreateTestRunspace( /// public static Runspace CreateRunspace(PSHost psHost, InitialSessionState initialSessionState) { + // We set the process scope's execution policy (which is really the runspace's scope) to + // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI + // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this + // behavior for consistency such that unit tests can pass in a similar environment. + if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; + } + Runspace runspace = RunspaceFactory.CreateRunspace(psHost, initialSessionState); // Windows PowerShell must be hosted in STA mode diff --git a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs index 603e9a2f3..1e3de847f 100644 --- a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs +++ b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs @@ -43,14 +43,7 @@ public static PowerShellContextService Create(ILogger logger) { PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, isPSReadLineEnabled: false); var initialSessionState = InitialSessionState.CreateDefault(); - // We set the process scope's execution policy (which is really the runspace's scope) to - // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI - // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this - // behavior for consistency such that unit tests can pass in a similar environment. - if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; - } + HostStartupInfo testHostDetails = new HostStartupInfo( "PowerShell Editor Services Test Host", "Test.PowerShellEditorServices", From b91bb5c0fa9a6733ce41d9b20d200f238d51a8f3 Mon Sep 17 00:00:00 2001 From: dkattan <1424395+dkattan@users.noreply.github.com> Date: Wed, 14 Jul 2021 16:08:00 -0500 Subject: [PATCH 7/7] Moved both bypass and restore of execution policy to only happen for tests. Tests pass locally. --- .../PowerShellContextService.cs | 16 ++-------------- .../PowerShellContextFactory.cs | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs index 6f0a5b774..f04e9c8ea 100644 --- a/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs +++ b/src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs @@ -251,10 +251,7 @@ public static PowerShellContextService Create( sendErrorToHost: true); #pragma warning restore CS4014 } - if(VersionUtils.IsWindows) - { - powerShellContext.RestoreExecutionPolicy(); - } + return powerShellContext; } @@ -288,15 +285,6 @@ public static Runspace CreateTestRunspace( /// public static Runspace CreateRunspace(PSHost psHost, InitialSessionState initialSessionState) { - // We set the process scope's execution policy (which is really the runspace's scope) to - // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI - // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this - // behavior for consistency such that unit tests can pass in a similar environment. - if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; - } - Runspace runspace = RunspaceFactory.CreateRunspace(psHost, initialSessionState); // Windows PowerShell must be hosted in STA mode @@ -2138,7 +2126,7 @@ private static string GetStringForPSCommand(PSCommand psCommand) return stringBuilder.ToString(); } - private void RestoreExecutionPolicy() + internal void RestoreExecutionPolicy() { this.logger.LogTrace("Setting execution policy..."); diff --git a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs index 1e3de847f..801d8f2f3 100644 --- a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs +++ b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs @@ -15,6 +15,7 @@ using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.PowerShellContext; using Microsoft.PowerShell.EditorServices.Test.Shared; +using Microsoft.PowerShell.EditorServices.Utility; namespace Microsoft.PowerShell.EditorServices.Test { @@ -43,7 +44,14 @@ public static PowerShellContextService Create(ILogger logger) { PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, isPSReadLineEnabled: false); var initialSessionState = InitialSessionState.CreateDefault(); - + // We set the process scope's execution policy (which is really the runspace's scope) to + // Bypass so we can import our bundled modules. This is equivalent in scope to the CLI + // argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this + // behavior for consistency such that unit tests can pass in a similar environment. + if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass; + } HostStartupInfo testHostDetails = new HostStartupInfo( "PowerShell Editor Services Test Host", "Test.PowerShellEditorServices", @@ -70,7 +78,10 @@ public static PowerShellContextService Create(ILogger logger) InitialRunspace, ownsInitialRunspace: true, consoleHost: null); - + if(VersionUtils.IsWindows) + { + powerShellContext.RestoreExecutionPolicy(); + } return powerShellContext; } }