SlideShare a Scribd company logo
1 of 22
Download to read offline
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 everyoneGavin Barron
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit TestingPrince Norin
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django ApplicationsHonza Král
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 
Intro to front-end testing
Intro to front-end testingIntro to front-end testing
Intro to front-end testingJuriy 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 EclipseTom Arend
 
RSpec and Rails
RSpec and RailsRSpec and Rails
RSpec and RailsAlan 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 ValleyPuppet
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to TestZsolt 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 GulpAll Things Open
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent EventTencent
 
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 documentationRouven Weßling
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introMaurice 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

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 2013Dror Helper
 
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 - HRUGegoodwintx
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration TestersNikhil Mittal
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
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 applicationsOrtus 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 Rspecjeffrey1ross
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingOrtus 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 CIwajrcs
 
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 TestSeb 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 - KenyaErick M'bwana
 
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 PesterChris 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 TrainingRam Awadh Prasad, PMP
 
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_tutorialgarrett 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

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

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