How to be sure that your PowerShell script are doing what you think?

Recently, I was required to write PowerShell script to automate some Microsoft Azure deployments. I was at first really happy to share those scripts because I knew other developers would use it. They would add functionalities and the library would grow. The idea was nice, but how to be sure that while adding some functionalities they don’t break something else? I didn’t know any unit test framework for Powershell, so I decided to do a quick search online. I was sure some kind of framework already exists. What I didn’t expect, however, was to find a framework that was really easy to use, complete and free! In this post, I will introduce you to Pester, a wonderful PowerShell framework available on github.

What is Pester?

Pester is a Business Development Driven (BDD) unit tests framework that implements a lot of functionalities like mock and exceptions management.

How to Install

The framework is available on github.com but it can also be downloaded from different repositories. My personal favorite is to download it from Chocolatey because it’s the most painless method. The Chocolatey’s command to install Pester is:
cinst pester 

Before continuing, if you try a Pester command right now, you will probably have the error message: “The term ‘___’ is not recognized as the name of a cmdlet…”. One way to fix that is to add Pester to your Profile. This can be done by executing the following command.

{Import-Module "C:\Chocolatey\lib\pester.2.0.4\tools\Pester.psm1"} | New-Item -path $profile -type file -force;. $profile

Get Started

Now that Pester is available on your machine, let’s start by creating our first test. Pester can scaffold for you an empty script file and a test file. If you add Pester to an already existing library, don’t be scared, Pester will not override the existing files.

Open a PowerShell console and type the following command:

New-Fixture c:\dev\pesterDemo pesterDemocd c:\dev\pesterDemo

You can try the new test by invoking Pester with this command:

Invoke-Pester

ResultDefaultPesterTest

As you can see a test already exists, and it failed.

Simple test

Let’s create a reel test that will read an XML file to extract a property. Here is the content of the XML file and the code for both the script and the test file.

manifest.xml
<service>
    <name>Employee Provider</name>
    <version>1.2</version>
</service>

pesterDemo.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"

Describe "#pesterDemo#" {

    Context "Test with reel XML document."{

        It "Loads a reel manifest." {
            $xml = getManifest ".\manifest.xml"
                $xml.OuterXMl | Should Be "<service><name>Employee Provider</name><version>1.2</version></service>"
        }

        It "Return the service name."{
            $sName = GetServiceName ".\manifest.xml"
                $sName | Should Be "Employee Provider"
        }

    }
}

pesterDemo.ps1
function GetManifest($manifestPath){
        if(Test-Path $manifestPath)
        {
            [xml]$xml = Get-Content $manifestPath
            return $xml
    }
    else{
        Throw "Error. Ïnvalid Manifest file path."
    }
}

function GetServiceName($manifestPath){
        $manifest = GetManifest($manifestPath)
        return $manifest.service.name
}

Result of the test

The script file contains two simple functions. The first one [GetManifest] versifies if the file exists and returns his content. Otherwise, an exception is thrown. The second function [GetServiceName] retreives the content of the XML file, and returns the value of the property [name] of the node [service].

The test file contains two tests. The first one Loads a reel manifest test that the manifest.xml file is correctly loaded and validates the content. The second test Return the service name, validate that the name of the service is the same as expected. We can now invoke the tests.

Invoke-Pester

ResultFirstPesterTest

As you can see, all tests succeeded and the output is really clear. Now what if the path passed in parameter doesn’t exist? Let assume that in our design, we wanted that the code to throw an exception. A good thing for us, Pester already has everything to manage exceptions.

Let’s do a test to validate this “requirement.” First, define a code block that calls [GetManifest] with a wrong path. Then pipe the result in the Pester command Should. If you add the filling code to the pesterDemo.tests.ps1, and invoke-Pester all tests should succeed.

It "Throw an exception when loads a manifest with invalid path." {
{$xml = GetManifest ".\WrongPath\manifest.xml" }  |  Should Throw
}

Test with Mock

Sometimes, we don’t want our tests to interact with reel components. That’s why mocks are so useful. Thankfully for us, creating a mock with Pester is a piece of cake. In all the previous tests, a real XML file was used. To make some validation on the content of the file, I could have as many different files as different scenarios, or simpler I could use some mock.

With Pester, we must set up a context where our mock will be present. Here is a test where I mock the XML file. As expected, any path will work since the file is not reel.

Context "Test with Mocks."{

    Mock GetManifest{return [xml]"<service><name>Employee Provider</name><version>1.2</version></service>"}

    It "Any path will works"{
        $xml =  GetManifest -MockWith ".\wrongPath\manifest.xml"
            $xml.OuterXMl | Should Be "<service><name>Employee Provider</name><version>1.2</version></service>"
    }
}

Wrapping up

Of course, this little introduction is not an exhaustive list of all the features of Pester. I hope that with these little code snippets, I gave you the drive you needed to test your PowerShell scripts. So next time you write this amazing script to deploy your app on Microsoft Azure, think of Pester.

References



~Frank