Skip to content

Commit

Permalink
InitialSessionState: Add unit tests for Location
Browse files Browse the repository at this point in the history
  • Loading branch information
MatejKafka committed Apr 17, 2024
1 parent e29354d commit 271eb67
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions 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<DriveNotFoundException>(() => { GetIssLocation(iss); });
}

[Fact]
public void TestInvalidCustomLocationPath()
{
var iss = InitialSessionState.CreateDefault2();
iss.Location = Path.GetTempPath() + Path.DirectorySeparatorChar + "a nonexistent test directory";

Assert.Throws<ItemNotFoundException>(() => { 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<PathInfo>().Single();
}
}

0 comments on commit 271eb67

Please sign in to comment.