diff --git a/test/xUnit/csharp/test_InitialSessionState.cs b/test/xUnit/csharp/test_InitialSessionState.cs new file mode 100644 index 00000000000..4abfdd90f0f --- /dev/null +++ b/test/xUnit/csharp/test_InitialSessionState.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using Xunit; +using DriveNotFoundException = System.Management.Automation.DriveNotFoundException; + +namespace PSTests.Parallel; + +public class InitialSessionStateTests +{ + [Fact] + public void TestDefaultLocation() + { + var iss = InitialSessionState.CreateDefault2(); + + var wd = GetIssLocation(iss); + Assert.Equal(Environment.CurrentDirectory, wd.Path); + } + + [Fact] + public void TestCustomFileSystemLocation() + { + // any path different from the process working directory would work here + var location = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar); + + // sanity check to ensure the test is not running from the tmp dir + Assert.NotEqual(location, Environment.CurrentDirectory); + + var iss = InitialSessionState.CreateDefault2(); + iss.Location = location; + + var wd = GetIssLocation(iss); + Assert.Equal(location, wd.Path); + } + + [Fact] + public void TestCustomEnvLocation() + { + var iss = InitialSessionState.CreateDefault2(); + iss.Location = "Env:\\"; + + var wd = GetIssLocation(iss); + Assert.Equal("Env:\\", wd.Path); + } + + [Fact] + public void TestInvalidCustomLocationDrive() + { + var iss = InitialSessionState.CreateDefault2(); + iss.Location = "NonExistentDrive:\\"; + + Assert.Throws(() => { GetIssLocation(iss); }); + } + + [Fact] + public void TestInvalidCustomLocationPath() + { + var iss = InitialSessionState.CreateDefault2(); + iss.Location = Path.GetTempPath() + Path.DirectorySeparatorChar + "a nonexistent test directory"; + + Assert.Throws(() => { GetIssLocation(iss); }); + } + + private static PathInfo GetIssLocation(InitialSessionState iss) + { + using var runspace = RunspaceFactory.CreateRunspace(iss); + runspace.Open(); + + using var ps = PowerShell.Create(runspace); + return ps.AddCommand("pwd").Invoke().Single(); + } +}