Test Environment Data in Chef Integration tests with PowerShell/Pester

I was reviewing a set of integration tests for a cookbook the other day and realized I had hard-coded a folder name in the test . 

Pester Integration Test

The test was passing because the hard-coded folder and the folder used in the recipe matched.  What happens if we change the folder in the future?  The integration test would start failing unless we also remembered to update the path in the integration test.  Not a big deal but this is unnecessary duplication which causes fragility in the test. 

it “should create logs folder” {

test-path ‘C:/logs” | should be $true

}

Recipe

In this case, my recipe was getting the path from a node attribute:

dsc_resource “#{cookbook_name}_Create_Log_Folder” do

  resource :file

  property :destinationpath, node[“infrastructure”][“win_constants”][“log_base_dir”]

property :type, ‘Directory’

end

Kitchen Config

I configured Kitchen to use my test environment data in the .kitchen.yml file under the provisioner section:

provisioner:

  name: chef_zero

  environments_path: test/support/environments

  client_rb:

    environment: test

Attributes are so useful both in the context of the tests and also across environments on the Chef Server.  The problem is I wasn’t using these values in my integration tests. 

image

The Fix

I first tried to access the test.json file in the test/support/environments folder from the integration tests.  The problem is Kitchen runs the integration tests on the target test VM (SUT)  and only copies over the test suite files during the kitchen verify step, so it couldn’t find the environment file.

So I asked Steve Murawski if there was a common solution for this scenario.  He said there wasn’t but the cookbook files should still be on the target node from the kitchen converge run in the $env:temp/kitchen folder.  Of course he was right so I just repointed my PowerShell script

$testEnvironmentData = Get-Content “$env:temp/kitchen/environments/test.json” | Out-String | ConvertFrom-Json

With this I can access all my environment data from within my Pester integration tests.

it “should create logs folder” {

test-path $testEnvironmentData.default_attributes.infrastructure.win_constants.log_base_dir | should be $true

}

If you found this post helpful or you have questions about this solution please post a comment below.

Happy Testing!

2 thoughts on “Test Environment Data in Chef Integration tests with PowerShell/Pester

Leave a Reply