Home > Software engineering >  Writing Powershell Pester Test to check output contains multiple values
Writing Powershell Pester Test to check output contains multiple values

Time:11-09

I'm trying to check the permissions for an app registration in Azure and running

(Get-AzRoleAssignment -ObjectId $objectId).RoleDefinitionName 

It returns multiple values, e.g "Owner, Contributor, Reader, KeyVault Secret User" etc.

I'm trying to write a Pester test to ensure it has either two values, or one.

As an example, $objectId should contain "Contributor" and KeyVault Secret User, OR, "Owner". So the test is happy as long as it has 'Owner', or 'Contributor/KeyVault Secret User'. Just to note, the test should still pass if it has all 3.

I have the below so far but can't seem to get this working from what I've found online.

BeforeALL {
    
    $objectId = "<App-Reg-Object-Id>"
    $RoleDefName = Get-AzRoleAssignment -ObjectId $objectId
}

Describe "Permissions Role Definition Checks" {


    It "Checked the App Reg and it has the correct permissions" {
        if ($RoleDefName.RoleDefinitionName | Should -Contain 'Owner')
        {
            Write-Host "Owner permission successfully found"
        }
        else {
            $RoleDefName.RoleDefinitionName | Should -Contain 'Contributor'|'User Access Administrator'
        }
    }
}
    
}

Any help would be greatly appreciated

EDIT

This is now working with the help of Mark Wraggs' comment! I had to move the logic to the left of the Should, with a ForEach for the multiple roles. Below is how I got this working.

Describe "Permissions Role Definition Checks" {

    It "Checked the App Reg and it has the correct permissions" -ForEach 'User Access Administrator','Contributor' {
        $RoleDefName.RoleDefinitionName -Contains 'Owner' -Or $RoleDefName.RoleDefinitionName -Contains $_ | Should -Be $true

    }
} 

CodePudding user response:

For this assertion, you need to do:

$RoleDefName.RoleDefinitionName | Should -Contain 'Contributor','User Access Administrator'

But because your scenario is a bit complex (where you want to check for two different results) it might be better to move the logic to the left of the Should. For example:

$RoleDefName.RoleDefinitionName -Contains 'Owner' -Or $RoleDefName.RoleDefinitionName -Contains 'Contributor','User Access Administrator' | Should -Be $true
  • Related