SlideShare a Scribd company logo
Mastering PowerShell
Testing with Pester
Mark Wragg
Describing Speaker
[-] Error occurred in Describe block
Expected: 'The foremost expert in Pester'
But was: 'Mark Wragg’
Twitter : @markwragg
Website : http://wragg.io
GitHub : http://github.com/markwragg
DevOps Engineer, XE.com
About Me
• A PowerShell Module for testing PowerShell code
• Pester is written in PowerShell
• Pester is used to test PowerShell Core
• Pester is used to test.. Pester
• Install it via:
Install-Module Pester
• On Windows 10 its pre-installed, but you can update it via:
Install-Module Pester -Force -SkipPublisherCheck
About Pester
Testing Strategies
Pester is a versatile tool that can be used for a variety of testing strategies.
• Operational Validation:
• System / infrastructure is configured / working as expected
• Integration Testing:
• The end result of your code is correct / your code works with other modules.
• Unit Testing:
• A unit of code – does one thing
Why should you write tests?
Testing is the single most important thing you will ever do.
• You are already testing your code, Pester allows
that testing to be more detailed and thorough.
• Testing is an essential prerequisite to continuous
integration / continuous delivery (CICD). You need
tests that are run automatically when your code
changes.
• Tests act as a form of documentation (but
shouldn’t be exclusively so).
You are a developer.
Beware of imposter syndrome.
Developer
[dih-vel-uh-per]
noun
An organism capable of
converting caffeine in to
code.
PowerShell Code Maturity
Console commands (one liners)
Basic scripts (one or more commands saved as a .ps1)
Scripts that include functions but that are executed within the same script.
Scripts that define only functions
Module with functions all declared as a single .psm1 file
Module with functions organised in individual files
Module with manifest, published in the PowerShell Gallery
Module automatically tested and published via a CICD Pipeline
Not testable
Testable
Pester needs to be able to read your code and control when parts execute for it to be testable.
Getting Started
A Pester script is just a PowerShell script with some additional keywords and structure.
• Describe
• Context
• It
• Should
• Mock
A simple example
function Add-One ([int]$Number) {
$Number + 1
}
Describe 'Add-One tests' {
It 'Should add one to a number' {
Add-One 1 | Should -Be 2
}
It 'Should add one to a negative number' {
Add-One -1 | Should -Be 0
}
}
A more realistic example
function Remove-TempFile ($Path) {
$TempFiles = Get-ChildItem "$Path/*.tmp"
$TempFiles | Remove-Item
}
Describe 'Remove-TempFile tests’ {
$TestFile = New-Item /tmp/test.tmp
It 'Should return nothing' {
Remove-TempFile -Path /tmp | Should -Be $null
}
It 'Should remove the test file’ {
$TestFile | Should -Not -Exist
}
It 'Should not return an error' {
{ Remove-TempFile -Path /tmp } | Should -Not -Throw
}
}
This is also an example of the Arrange - Act -
Assert testing pattern.
Refactoring
Refactoring is the process of changing code without changing its behaviour.
• Breaking your code in to smaller
pieces (functions) so that each does
just one thing.
• Unit tests are about proving
correctness.
• A Unit of code should do only one
thing.
• A Unit test allows you to prove it
does that one thing correctly.
A refactored example
function Get-TempFile ($Path) {
Get-ChildItem "$Path/*tmp*"
}
function Remove-TempFile ($Path) {
$TempFiles = Get-TempFile -Path $Path
$TempFiles | Remove-Item
}
Describe 'Get-TempFile tests' {
New-Item TestDrive:/test.tmp
New-Item TestDrive:/tmp.doc
It 'Should return only .tmp files' {
(Get-TempFile -Path TestDrive:/).Extension | Should -Be '.tmp'
}
}
About TestDrive
TestDrive is a PSDrive for file activity limited to the scope of a Describe or Context block.
• Creates a randomly named folder under $env:temp which you can then reference
via TestDrive: or $TestDrive
• $TestDrive is the full literal path (useful if you need to do path comparisons).
• Use this as a safe space in which to do file operations, that is cleaned up
automatically for you.
• Pester will keep a record of the files present in the location before entering a
Context block and will remove any files therefore created by the Context block, but
won’t revert files that have been modified.
Mocking
Mocking is a facet of unit testing that involves replacing real cmdlets or functions with
simulated ones.
This can be useful for a number of reasons:
1. Your code relies on missing external
resources.
2. Your code makes destructive or other
permanent or undesirable changes.
3. The code you are testing is using some
secondary function that already has its own
set of tests.
A mocking example
Describe 'Remove-TempFile tests' {
Mock Remove-Item { }
New-Item TestDrive:/test.tmp
New-Item TestDrive:/tmp.doc
$TestResult = Remove-TempFile -Path TestDrive:
It 'Should return nothing' {
$TestResult | Should -Be $null
}
It 'Should call Remove-Item' {
Assert-MockCalled Remove-Item -Times 1 -Exactly
}
}
Mocking cmdlets that aren’t present
Pester needs the cmdlet or function you are mocking to exist on the current system, but you
can fake it if it doesn’t.
• If you attempt to Mock a cmdlet that isn’t currently available (e.g in a module not
installed on your system) Pester will throw an error.
• You can work around this by declaring a fake function in its place.
• You can then still also declare a Mock, so that you can use Assert-MockCalled.
• This can get complex, so use only when needed. If you can make the required
cmdlets/functions available that is more ideal.
Code Coverage
Code coverage is a measure that indicates how much of your code was executed when your
tests ran.
• Code Coverage is a useful
measure of how thorough your
tests are.
• 100% code coverage does not
equal 100% working code.
• Getting close to 100% is good,
but achieving 100% code
coverage isn’t always useful.
Why is code coverage reporting useful?
Your code likely has multiple happy (successful) and unhappy (fail, error, exception) paths.
• If your code contains any logical statements (if, switch, try..catch etc.) then there
are multiple ways in which it can be executed to either a successful or
unsuccessful conclusion.
• The code coverage report helps to highlight which of these paths have not been
taken.
How to use the code coverage feature of Pester
The Pester code coverage feature requires PowerShell version 3.0 or greater.
• To check code coverage, you need to execute pester with the –CodeCoverage parameter and
send it a list of code files that you are evaluating:
Invoke-Pester -CodeCoverage (Get-Childitem .YourModule*.ps1 -Recurse)
Summary
Writing, maintaining and executing tests is an essential and accessible PowerShell skill.
• Pester is just PowerShell with a few extra commands to learn.
• There is an excellent and detailed Wiki on the official Pester repository that
explains all the concepts:
• https://github.com/pester/Pester/wiki
• There are lots of people in the community ready and willing to help you:
• The #Pester tag on StackOverflow.com.
• PowerShell.org forums.
• r/PowerShell
• The PowerShell Slack community.
Any questions?
Thank you!
Twitter : @markwragg
Website : http://wragg.io
GitHub : https://github.com/markwragg

More Related Content

What's hot

PowerShell: Automation for everyone
PowerShell: Automation for everyonePowerShell: Automation for everyone
PowerShell: Automation for everyone
Gavin Barron
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
Anth Courtney
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
Ingo Schommer
 
Laravel 5.5 dev
Laravel 5.5 devLaravel 5.5 dev
Laravel 5.5 dev
RocketRoute
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
Nir Kaufman
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
Timothy Oxley
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
Gert Poppe
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
Gert Poppe
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
Prince Norin
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
Honza Král
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
Brian Gesiak
 
Intro to front-end testing
Intro to front-end testingIntro to front-end testing
Intro to front-end testing
Juriy Zaytsev
 
Getting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseGetting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in Eclipse
Tom Arend
 
RSpec and Rails
RSpec and RailsRSpec and Rails
RSpec and Rails
Alan Hecht
 
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon ValleyPuppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
Zsolt Fabok
 
Javascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and GulpJavascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and Gulp
All Things Open
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
Tencent
 
vienna.js - Automatic testing of (RESTful) API documentation
vienna.js - Automatic testing of (RESTful) API documentationvienna.js - Automatic testing of (RESTful) API documentation
vienna.js - Automatic testing of (RESTful) API documentation
Rouven Weßling
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
Maurice De Beijer [MVP]
 

What's hot (20)

PowerShell: Automation for everyone
PowerShell: Automation for everyonePowerShell: Automation for everyone
PowerShell: Automation for everyone
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Laravel 5.5 dev
Laravel 5.5 devLaravel 5.5 dev
Laravel 5.5 dev
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
Intro to front-end testing
Intro to front-end testingIntro to front-end testing
Intro to front-end testing
 
Getting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseGetting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in Eclipse
 
RSpec and Rails
RSpec and RailsRSpec and Rails
RSpec and Rails
 
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon ValleyPuppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon Valley
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Javascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and GulpJavascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and Gulp
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
vienna.js - Automatic testing of (RESTful) API documentation
vienna.js - Automatic testing of (RESTful) API documentationvienna.js - Automatic testing of (RESTful) API documentation
vienna.js - Automatic testing of (RESTful) API documentation
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 

Similar to Mastering PowerShell Testing with Pester

Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
Dror Helper
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
egoodwintx
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
Nikhil Mittal
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
Dror Helper
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
ICS
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
Alexander Loechel
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspec
jeffrey1ross
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
Ortus Solutions, Corp
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
wajrcs
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
Erick M'bwana
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 
How to Test PowerShell Code Using Pester
How to Test PowerShell Code Using PesterHow to Test PowerShell Code Using Pester
How to Test PowerShell Code Using Pester
Chris Wahl
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
Lilia Sfaxi
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Sergey Aganezov
 
20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial
garrett honeycutt
 

Similar to Mastering PowerShell Testing with Pester (20)

Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspec
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
How to Test PowerShell Code Using Pester
How to Test PowerShell Code Using PesterHow to Test PowerShell Code Using Pester
How to Test PowerShell Code Using Pester
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial20140406 loa days-tdd-with_puppet_tutorial
20140406 loa days-tdd-with_puppet_tutorial
 

Recently uploaded

“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 

Recently uploaded (20)

“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 

Mastering PowerShell Testing with Pester

  • 2. Describing Speaker [-] Error occurred in Describe block Expected: 'The foremost expert in Pester' But was: 'Mark Wragg’ Twitter : @markwragg Website : http://wragg.io GitHub : http://github.com/markwragg DevOps Engineer, XE.com About Me
  • 3. • A PowerShell Module for testing PowerShell code • Pester is written in PowerShell • Pester is used to test PowerShell Core • Pester is used to test.. Pester • Install it via: Install-Module Pester • On Windows 10 its pre-installed, but you can update it via: Install-Module Pester -Force -SkipPublisherCheck About Pester
  • 4. Testing Strategies Pester is a versatile tool that can be used for a variety of testing strategies. • Operational Validation: • System / infrastructure is configured / working as expected • Integration Testing: • The end result of your code is correct / your code works with other modules. • Unit Testing: • A unit of code – does one thing
  • 5. Why should you write tests? Testing is the single most important thing you will ever do. • You are already testing your code, Pester allows that testing to be more detailed and thorough. • Testing is an essential prerequisite to continuous integration / continuous delivery (CICD). You need tests that are run automatically when your code changes. • Tests act as a form of documentation (but shouldn’t be exclusively so).
  • 6. You are a developer. Beware of imposter syndrome. Developer [dih-vel-uh-per] noun An organism capable of converting caffeine in to code.
  • 7. PowerShell Code Maturity Console commands (one liners) Basic scripts (one or more commands saved as a .ps1) Scripts that include functions but that are executed within the same script. Scripts that define only functions Module with functions all declared as a single .psm1 file Module with functions organised in individual files Module with manifest, published in the PowerShell Gallery Module automatically tested and published via a CICD Pipeline Not testable Testable Pester needs to be able to read your code and control when parts execute for it to be testable.
  • 8. Getting Started A Pester script is just a PowerShell script with some additional keywords and structure. • Describe • Context • It • Should • Mock
  • 9. A simple example function Add-One ([int]$Number) { $Number + 1 } Describe 'Add-One tests' { It 'Should add one to a number' { Add-One 1 | Should -Be 2 } It 'Should add one to a negative number' { Add-One -1 | Should -Be 0 } }
  • 10. A more realistic example function Remove-TempFile ($Path) { $TempFiles = Get-ChildItem "$Path/*.tmp" $TempFiles | Remove-Item } Describe 'Remove-TempFile tests’ { $TestFile = New-Item /tmp/test.tmp It 'Should return nothing' { Remove-TempFile -Path /tmp | Should -Be $null } It 'Should remove the test file’ { $TestFile | Should -Not -Exist } It 'Should not return an error' { { Remove-TempFile -Path /tmp } | Should -Not -Throw } } This is also an example of the Arrange - Act - Assert testing pattern.
  • 11. Refactoring Refactoring is the process of changing code without changing its behaviour. • Breaking your code in to smaller pieces (functions) so that each does just one thing. • Unit tests are about proving correctness. • A Unit of code should do only one thing. • A Unit test allows you to prove it does that one thing correctly.
  • 12. A refactored example function Get-TempFile ($Path) { Get-ChildItem "$Path/*tmp*" } function Remove-TempFile ($Path) { $TempFiles = Get-TempFile -Path $Path $TempFiles | Remove-Item } Describe 'Get-TempFile tests' { New-Item TestDrive:/test.tmp New-Item TestDrive:/tmp.doc It 'Should return only .tmp files' { (Get-TempFile -Path TestDrive:/).Extension | Should -Be '.tmp' } }
  • 13. About TestDrive TestDrive is a PSDrive for file activity limited to the scope of a Describe or Context block. • Creates a randomly named folder under $env:temp which you can then reference via TestDrive: or $TestDrive • $TestDrive is the full literal path (useful if you need to do path comparisons). • Use this as a safe space in which to do file operations, that is cleaned up automatically for you. • Pester will keep a record of the files present in the location before entering a Context block and will remove any files therefore created by the Context block, but won’t revert files that have been modified.
  • 14. Mocking Mocking is a facet of unit testing that involves replacing real cmdlets or functions with simulated ones. This can be useful for a number of reasons: 1. Your code relies on missing external resources. 2. Your code makes destructive or other permanent or undesirable changes. 3. The code you are testing is using some secondary function that already has its own set of tests.
  • 15. A mocking example Describe 'Remove-TempFile tests' { Mock Remove-Item { } New-Item TestDrive:/test.tmp New-Item TestDrive:/tmp.doc $TestResult = Remove-TempFile -Path TestDrive: It 'Should return nothing' { $TestResult | Should -Be $null } It 'Should call Remove-Item' { Assert-MockCalled Remove-Item -Times 1 -Exactly } }
  • 16. Mocking cmdlets that aren’t present Pester needs the cmdlet or function you are mocking to exist on the current system, but you can fake it if it doesn’t. • If you attempt to Mock a cmdlet that isn’t currently available (e.g in a module not installed on your system) Pester will throw an error. • You can work around this by declaring a fake function in its place. • You can then still also declare a Mock, so that you can use Assert-MockCalled. • This can get complex, so use only when needed. If you can make the required cmdlets/functions available that is more ideal.
  • 17. Code Coverage Code coverage is a measure that indicates how much of your code was executed when your tests ran. • Code Coverage is a useful measure of how thorough your tests are. • 100% code coverage does not equal 100% working code. • Getting close to 100% is good, but achieving 100% code coverage isn’t always useful.
  • 18. Why is code coverage reporting useful? Your code likely has multiple happy (successful) and unhappy (fail, error, exception) paths. • If your code contains any logical statements (if, switch, try..catch etc.) then there are multiple ways in which it can be executed to either a successful or unsuccessful conclusion. • The code coverage report helps to highlight which of these paths have not been taken.
  • 19. How to use the code coverage feature of Pester The Pester code coverage feature requires PowerShell version 3.0 or greater. • To check code coverage, you need to execute pester with the –CodeCoverage parameter and send it a list of code files that you are evaluating: Invoke-Pester -CodeCoverage (Get-Childitem .YourModule*.ps1 -Recurse)
  • 20. Summary Writing, maintaining and executing tests is an essential and accessible PowerShell skill. • Pester is just PowerShell with a few extra commands to learn. • There is an excellent and detailed Wiki on the official Pester repository that explains all the concepts: • https://github.com/pester/Pester/wiki • There are lots of people in the community ready and willing to help you: • The #Pester tag on StackOverflow.com. • PowerShell.org forums. • r/PowerShell • The PowerShell Slack community.
  • 22. Thank you! Twitter : @markwragg Website : http://wragg.io GitHub : https://github.com/markwragg