Partager via


PowerShell CI pipeline using VSTS and Pester

I talked about BDD on PowerShell meetup Tokyo.  I'd like to share some tips for enabling BDD and Continuous Integration using VSTS.

bddpowershell

If you create a decent Unit tests when you write a PowerShell, you can feel safe and sound. Also if you have continuous integration system for your PowerShell, You can notice the problem of your PowerShell.

Let's get started.

I use Pester for BDD framework for PowerShell.

You can clone my GitHub repository for setting up your environment.

https://github.com/TsuyoshiUshio/PowerShellCISampl

  1. Setting up Pester module

SetupPester.ps1 enable us to setup Pester module.  You need to copy Pester files to the UserModulePath.

 function Get-UserModulePath {
 
 $Path = $env:PSModulePath -split ";" -match $env:USERNAME
 
 if (-not (Test-Path -Path $Path))
 {
 New-Item -Path $Path -ItemType Container | Out-Null
 }
 $Path
}
$path = Get-UserModulePath
Write-Output $path 
Copy-Item -Path Pester -Destination $path -Recurse
Import-Module Pester
Get-Module -Name Pester | Select -ExpandProperty ExportedCommands | Write-Output

Then import Paster Module. See UnitTest.ps1

 Unblock-File -Path "..\..\Pester-master.zip"
Import-Module Pester
Invoke-Pester -OutputFile TEST-RESULT.xml -OutputFormat "LegacyNUnitXml"

2. Unit Testing

This command Generate a PowerShell and  an UnitTest.

 PS1 > New-Fixture -Path HelloWorldExample -Name Get-HelloWorld

HelloWorld.ps1

 function Get-HelloWorld {
 
}

HelloWorld.Test.ps1

 $here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "Get-HelloWorld" {
 It "outputs 'Hello World!" {
 Get-HelloWorld | Should Be 'Hello World!'
 }
}

Invoke-Pester command invokes your powershell unit testing. This is an example of failure of an unit test.

 PS1 > Invoke-Pester

Describing Get-HelloWorld
 [-] outputs 'Hello World! 152ms
 Expected: {Hello World!}
 But was: {}
 7: Get-HelloWorld | Should Be 'Hello World!'
 at <ScriptBlock>, C:\Users\tsushi\Codes\PowerShell\Pester\HelloWorldExample\HelloWorldExample\Get-HelloWorld.Tests.ps1: line
 7

3. Continuous Integration

Enable Continuous Integration using VSTS. Clone my Repository . Import it on your Git of VSTS.

Then you can define pipeline like this. pipeline01pipeline02pipeline03

Then you can build and test automatically.

build

It is very easy. Enjoy coding.

This is the presentation for PowerShell meetup Tokyo.

https://docs.com/ushio-tsuyoshi/7418/behavior-driven-development-for-powershell-with