Wednesday, January 21, 2015

Creating your own unit test framework for PowerShell - Part 6


The authorization manager helps control the execution of commands for the runspace. When you try to execute a PowerShell script from C#, and haven't changed PowerShell's default execution policy, the scripts that are executed under the execution policy set on the machine. If you want the tests executed from C# to bypass the default security policy, then you need to either use a null AuthorizationManager implementation for the runspace or create a custom implementation of the AuthorizationManager and override the policy based on any condition you have. Deriving from the AuthorizationManager class allows you to override the ShouldRun method and add the logic specific to your needs like set up a reason parameter with a custom execption with proper explanation and details on why this command was blocked etc.
In the testing framework, I decided to use the second approach and created the custom authorization manager implementation as

internal class TestContextAuthorizationManager : AuthorizationManager
{
    public TestContextAuthorizationManager(string shellId) : base(shellId)
    {

    }

    protected override bool ShouldRun(CommandInfo commandInfo, CommandOrigin origin, PSHost host, out Exception reason)
    {
        base.ShouldRun(commandInfo, origin, host, out reason);
        return true;
    }
}

In the LoadPSTestHost method you can now use this implementation instead of the default AuthorizationManager as
var state = InitialSessionState.CreateDefault2();
state.AuthorizationManager = new TestContextAuthorizationManager("VSTestShellId");

No comments: