Pester 5 test Powershell code in pipeline

Pester 5 test Powershell code in pipeline

July 17, 2022 0 By Morten Lerudjordet

Some time ago I created Pester tests for Azure Automation Runbooks as part of a pipeline to validate code before getting checked into a repo. Though this was pre version 5 of Pester, and as 5 came around there where some changes that had to be done for everything to keep working. I will go through in this post the code I use to trigger the tests as part of a pipeline, and the tests I use. The test use both PSScriptAnalyzer and some custom AST test to validate that the Powershell code follows a certain structure layout.

The pipeline is a yaml, that triggers powershell scripts that does the heavy lifting.

Pipeline Run

The image above shows a pipeline run after updating one of the Runbooks/Modules in the repo. The powershell script below triggers running the Pester tests and creates a test report that is uploaded to AzDo and will either fail or pass the run depending on the results.

The report will look like the image below for a clean run.

The pipeline code to do this is show below.

The test script takes as an input the path to publish the result report and the built in test publish task takes the file and uploads to Azure DevOps.

The pester tests are maybe not the best when it comes to following Pester established structure, but they where written a long time ago, and only updated enough to work with version 5. The tests are split into different types of tests for how Powershell code/modules are structured.

Update: Have done some rewrites to the test to be more inline with good practice for Pester 5.

Lastly a sanitized version of the build pipeline in use.

For the actual runbook and modules code, the pipeline will only copy the ones that has changed since last trigger and put them in an artifact. This artifact is then used in the release part of the pipeline to publish to the different Azure Automation environments.

Hope the tests are usefull.

Happy tinkering!