Unit testing PowerShell Code with Pester

Source: Internet
Author: User
Tags assert

Summary:guest Blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerShell code.

Note This was a Five-part series that includes the following posts:

    • What's Pester and why should I care?
      Learn about a new test framework for PowerShell called Pester
    • Getting Started with Pester
      Learn how to get information back from Pester
    • Unit testing PowerShell Code with Pester
      Use Pester to analyze small pieces of Windows PowerShell code
    • Testing Script Modules with Pester
      Use Pester for testing PowerShell modules
    • More Pester Features and Resources
      Learn about more Pester resources

Before we get into the technical details today and let ' s define a few terms. There is several categories of automated testing, all of which is used in a continuous delivery pipeline. For the purposes of Windows PowerShell code, I tend to refer to three:

    • Unit Tests
    • Integration tests
    • Acceptance tests
Unit Tests

A unit test is the smallest and fastest type, and it's the first thing that'll be run in your pipeline. It can usually is executed on the developer's machine before checking in the code to source control. Unit tests is responsible for verifying the behavior of a single unit of code, which in PowerShell, typically means a fun Ction.

If The function is testing depends on anything other than the parameters that is passed in, you'll want to isolate Y Our code from those other dependencies in the unit test. These dependencies could is anything, including a Web service of some sort, the state of the computer where the script run s, or even calls to other PowerShell functions or cmdlets.

Integration tests

Integration tests is pretty much the opposite of unit tests. Instead of isolating your code from the other parts, you run everything in all its glory, and make sure it ' s behaving prop Erly when all of the bits is working together. This might require-to-set up a further complicated test environment, so the necessary Web services, for example, is Avai Lable. This means, integration tests is more expensive to run. It's for this reason, that's the only move on to integration tests if the unit tests has already passed.

Acceptance tests

Acceptance tests is fundamentally the same as integration tests, except they refer to tests so you run after your code is deployed into production. You can use the them as a quick sanity check to make sure everything's up and running. You might also hear these referred to as "smoke tests."

The examples of Pester that you ' ve seen so far is perfect for integration or acceptance tests. They make calls to a API (without caring what it internals do), and write test cases against the results. For a unit test, though, we need some the isolating we function under test from its dependencies. That's where mocking comes into play.

Pester has a built-in mocking framework, that allows, to create dummy versions of the other PowerShell commands. A picture was worth a thousand words so here's a PowerShell function that needs some mocking to be properly un It tested:

This was a fairly simple function, but it contains calls to four other cmdlets:get-date, Get-aduser, Where-object, and Dis Able-adaccount. Of these, we can ignore where-object because it ' s simply a logic construct-and indeed, it is the what we ' re testing. (The function is written this-instead of using the better Search-adaccount cmdlet simply to give us + to work Withi n the Pester examples.)

To test this code without requiring an actual Active Directory domain, we need to consider a few things:

    • Make Get-date return a specific Date and time. (This was optional, but not a bad idea.)
    • Make Get-aduser return a set of test objects. We want some of these to be "disabled," and others should is left alone. The test cases would make sure the proper objects is passed to Disable-adaccount.
    • Make Disable-adaccount does nothing, other than give us a-to-track how it is called, so we know which users would be di Sabled.

Here's what the might look like:

In this example, we ' re seeing the new Pester commands: mock and assert-mockcalled. When you use mock and temporarily replace the behavior of a PowerShell command with whatever you want it to be.  ; Mock is active only inside the describe or context block where it is defined. If we had another describe block in the Example, get-date, get-aduser, And disable-adaccount  would go back to their normal behavior. When mock was called On disable-adaccount, we didn ' t even bother to specify an implementation; It defaults to doing nothing.

In my experience, the most mocks fall into one of these and categories:you either want them to return objects that your tests Define, or you want them to does nothing (and then later verify how they were called). I can ' t think of a situation where I ' ve had a mock return output later and be verified via the assert-mockcalled command b Ecause those tests would be redundant.

There is a few things to notice about mocking ...

  • Notice that I didn ' t need-specify any parameter-blocks for my mocks-and Indeed, you should not even try-to-do. This is because Pester would examine the original command that ' s being mocked, and it'll inject its parameters (including Dynamic parameters) into the mock for you automatically.
  • The Mock and assert-mockcalled commands have a parameter called–parameterfilter. This allows-control under what circumstances the mocking is effective (or whether the assertion should succeed or fail ), based on the parameters that was used when the mock was called. Incidentally, can mock the same command multiple times, with different parameter filters and different implementations , if you need to.
  • Mocking works by taking advantage of the command resolution order in Windows PowerShell, as detailed in theabout_command_p Recedence help file. When multiple PowerShell commands exist with the same name, the function version would be executed instead of cmdlets or ex ternal commands. When your define a mock in Pester, it creates a function with the name of the the command so want to mock, and that would Being what gets executed instead of the original command.

It ' s important to understand how this works, because your scripts might need some small modifications Cking in Pester. For example, let's revise our Active Directory example slightly:

In this version, the calls to Get-aduser and Disable-adaccount has been module-qualified (in Activedirectory\get-aduser). This gives PowerShell some extra information on which command to execute, and causes it to skip your mocked command an D Execute the live commands instead.

To do the code friendly to mocking, you ' d need to remove the module-qualified calls. Or You can wrap those calls in your own internal function, which can is mocked instead of the Active Directory cmdlets. Wrapping code into a function to facilitate mocking are a pretty common occurrence, such as if you want to mocks calls to a . NET class or method (which Pester can ' t do).

There is nuances to the Mock and assert-mockcalled commands, some of which we'll talk about tomorrow when we look a T unit testing code in script modules. To find more help and information on Pester, see:

    • Pester Help Files
    • Pester Home page and Pester Powershell BDD style testing Framework on GitHub
    • Pester Group on Google

~dave

Thanks, dave!

I invite you to follow me on Twitter and Facebook. If you had any questions, send e-mail to me at [email protected], or post your questions on the official Scriptin G Guys Forum. See you tomorrow. Until then, peace.

Unit testing PowerShell Code with Pester

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.