Testing Self-Contained PowerShell Script with Pester

In this post, I am going to share how to unit testing helper functions in a self-contained PowerShell script. I have the opportunity to write AWS Systems Manager Command Documents that are actually PowerShell scripts. The SSM documents (PowerShell scripts) are then executed by on triggers so I rely less on the Windows Scheduled Task. This is one of the cases that I prefer managing code in a self-contained PowerShell script rather than modules. (Another one is PowerShell Lambda). Self-contained scripts are the scripts that contain helper functions and business logic codes in the same file. When evaluating the dependency management effort versus delivering results, I'm really less inclined to use config management tooling to configure my Windows worker server. Anyway, that's another topic for another post.

<TL;DR>
In the Pester test file, use Powershell Abstract Syntax Tree (AST) to parse out the helper functions from the main PowerShell script. Then, save each function to the Pester TesetDrive individually. When uniting testing each helper function, dot source the helper function in the scope and there you go. 😁
</TL;DR>

The code examples below show you how things are connected together. In the ScriptWithFunction.ps1, I have three helper functions as well as the codes to fulfill the business logic.

In the BeforeAll {} of  the Pester test files below, you can see that I defined path to the script to be tested; used [System.Management.Automation.Language.Parser]::ParseFile() to get the AST object; used the AST object to find all the functions; and finally exported the function definition to Pester TestDrive with filename patching function name. When I reach the It {} block, I then dot source the functions I want to unit test for. I can add necessary mocking here to cover my test cases. I can also specify tags to control tests.

I really enjoyed using AST in this case. Unlike, parsing the script using regex or any other string parsing magic, AST allows me to access what PowerShell sees with few lines of code. I can then use that information together with Pester to elevate the quality of my code.

What do you think about this testing pattern? Is it useful to you? What are other ways or ideas you have? I'd love to hear about them. Please ping me on Twitter (@CPoweredLion) or leave a comment below.


---- ---- ----

Comments

Popular posts from this blog

PowerShell Universal Dashboard and AWS Elastic Beanstalk

Quick review on my career after learning PowerShell

The next chapter... or rather next page. :)