Sunday, October 12, 2014

Compare arrays in powershell using Pester

Recently I had to create deployment scripts using powershell. At some point our team realised that we need some way to test behavior of our scripts. After googling and comparing different libraries we decided to go with pester. It fits our needs and is actively supported, plus it's really easy to integrate into CI server.

Let's take a look at very simple examples.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Describe 'Pester demo' {
 Context 'Basic math' {   

  It 'Should add 2 numbers' {
   $sum = 2 + 7

   $sum | Should Be 9
  }

  It 'Should deduct 2 numbers' {
   $sum = 10 - 3

   $sum | Should Be 7
  }
 }
}

Nothing special, assertions work as pipeline functions. I personally like that library, it supports different kind of assertions, the only problem that I had is how to assert arrays equality.
Let's try to comapre two arrays.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Describe 'Compare arrays' {
 Context 'There are 2 arrays' {
  $array1 = 1, 2, 3
  $array2 = 1, 2, 3

  It 'Should be green' {
   $array1 | Should Be $array2
  }
 }
}

Output







Looks ok, let's break the test.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Describe 'Compare arrays' {
 Context 'There are 2 arrays' {
  $array1 = 1, 2, 4
  $array2 = 1, 2, 3

  It 'Should be green' {
   $array1 | Should Be $array2
  }
 }
}

Output



It's not really clear  what is really broken.
Let's see how we can improve it:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Describe 'Compare arrays' {
 Context 'There are 2 arrays' {
  $array1 = 1, 2, 4
  $array2 = 1, 2, 3

  $arrayStr1 = $array1 -join ', '
  $arrayStr2 = $array2 -join ', '

  It 'Should be green' {
   $arrayStr1 | Should Be $arrayStr2
  }
 }
}

Output













Now it makes more sense.

No comments:

Post a Comment