简体   繁体   中英

Pester v5 - Failed to run multiple test files

Good morning, I am trying to run several tests in different files test.ps1

The first file always works without problem, but the second one fails. If I add the content of the second file to the first file it works without any problem.

I run the tests with the following configuration (I was using version 4 before and maybe this is where all my confusion comes from)

$pathPs1Tests ="c:/Tests/Sol1/UnitTests/*.tests.ps1"
$pathCodeCoverage = "c:/Tests/Sol1/*.psm1"
$pathOutputCodeCoverage = "c:/Tests/Sol1/Coverage/Coverage-$($sName).xml"
$pathTestXml = "c:/Tests/Sol1/UnitTests/TEST-$($sName).xml"

$container = New-PesterContainer -Path $pathPs1Tests
    $pesterConfig = New-PesterConfiguration
    $pesterConfig.Run.Container = $container
    $pesterConfig.Run.PassThru = $true
    $pesterConfig.CodeCoverage.Enabled = $true
    $pesterConfig.CodeCoverage.Path = $pathCodeCoverage
    $pesterConfig.CodeCoverage.CoveragePercentTarget = 50
    $pesterConfig.CodeCoverage.OutputPath = $pathOutputCodeCoverage
    $pesterConfig.TestResult.OutputFormat = "NUnitXml"
    $pesterConfig.TestResult.OutputPath = $pathTestXml
    $result = Invoke-Pester -Configuration $pesterConfig 

$container contains:

Type Item                                                       Data
---- ----                                                       ----
File C:/Tests/Sol1\UnitTests\AAA.GraphCommon.Component.tests.ps1 {}
File C:/Tests/Sol1\UnitTests\AAA.User.Component.tests.ps1        {}

So I see that pester is loading the two files well with the $pathPs1Tests pattern

Structure for my files: 图片

I think the error is because pester is making the real call, not the "mock call". Output:

Starting discovery in 2 files.
Discovery found 7 tests in 138ms.
Starting code coverage.
Running tests.
[+] C:\Tests\Sol1\UnitTests\AAA.GraphCommon.Component.tests.ps1 541ms (209ms|257ms)
[-] Revoke-AAAUserSignInSessions.Validate 'Revoke-AAAUserSignInSessions' founded and revoked 222ms (219ms|3ms)
 WriteErrorException: It has not been possible to revoke the tokens. Microsoft.PowerShell.Commands.HttpResponseException: Response status code does not indicate success: 401 (Unauthorized).
    at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord).
 at Revoke-AAAUserSignInSessions, C:\Tests\Sol1\AAA.User.psm1:19
 at <ScriptBlock>, C:\Tests\Sol1\UnitTests\AAA.User.Component.tests.ps1:23
[-] Revoke-AAAUserSignInSessions.Validate 'Revoke-AAAUserSignInSessions' not found 179ms (178ms|1ms)
 WriteErrorException: It has not been possible to revoke the tokens. Microsoft.PowerShell.Commands.HttpResponseException: Response status code does not indicate success: 401 (Unauthorized).
    at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord).
 at Revoke-AAAUserSignInSessions, C:\Tests\Sol1\AAA.User.psm1:19
 at <ScriptBlock>, C:\Tests\Sol1\UnitTests\AAA.User.Component.tests.ps1:31
Tests completed in 1.37s
Tests Passed: 5, Failed: 2, Skipped: 0 NotRun: 0
Processing code coverage result.
Covered 94,87% / 50%. 39 analyzed Commands in 2 Files.

if I run the two separate files, both tests work. If I put the content of the second one in the first one also, but if I run it with the code that I have put above it fails because it is not able to fake the call. file 1:

PS C:\ . 'c:\Tests\.vscode\extensions\ms-vscode.powershell-2021.12.0\modules\PowerShellEditorServices\InvokePesterStub.ps1' -ScriptPath 'C:\Tests\Sol1\UnitTests\AAA.GraphCommon.Component.tests.ps1' -All -Output 'FromPreference'


Starting discovery in 1 files.
Discovery found 5 tests in 75ms.
Running tests.
[+] C:\Tests\Sol1\UnitTests\AAA.GraphCommon.Component.tests.ps1 519ms (138ms|309ms)
Tests completed in 521ms
Tests Passed: 5, Failed: 0, Skipped: 0 NotRun: 0

File 2:

PS C:\ . 'c:\Tests\.vscode\extensions\ms-vscode.powershell-2021.12.0\modules\PowerShellEditorServices\InvokePesterStub.ps1' -ScriptPath 'C:\Tests\Sol1\UnitTests\AAA.User.Component.tests.ps1' -All -Output 'FromPreference'

Starting discovery in 1 files.
Discovery found 2 tests in 58ms.
Running tests.
[+] C:\Tests\Sol1\UnitTests\AAA.User.Component.tests.ps1 531ms (179ms|295ms)
Tests completed in 532ms
Tests Passed: 2, Failed: 0, Skipped: 0 NotRun: 0

The AAA.MicrosoftGraph.Component.psd1 has: 图片

the test files are both the same: FILE1 (AAA.GraphCommon.Component.tests.ps1

Set-StrictMode -Version Latest
# Remove any loaded version of this module so only the files imported below are being tested.
Get-Module AAA.MicrosoftGraph.Component | Remove-Module -Force

$VerbosePreference = "Continue"
$ErrorActionPreference = "Stop"

BeforeAll {
    # Load the modules we want to test and any dependencies
    Import-Module "c:\Tests\Sol1\AAA.MicrosoftGraph.Component.psd1" -Force
}

Describe "Valid Token Get-AAAGraphToken" {
    BeforeAll {
        $parameters = @{
            clientId            = "AAA-000"
            ClientSecret        = "yyyy"
            TenantId            = "testTenant"
            AuthorizationHeader = $true
        }
        Mock Invoke-RestMethod { return @{ access_token = "xxxxxxxx" } } -ModuleName AAA.GraphCommon
    }

    It "Get-AAGraphToken OK" {
        $result = Get-AAAGraphToken @parameters
        $result.Authorization | Should -be "Bearer xxxxxxxx"
    }
}

FILE2 (AAA.User.Component.tests.ps1

Set-StrictMode -Version Latest
# Remove any loaded version of this module so only the files imported below are being tested.
Get-Module AAA.MicrosoftGraph.Component | Remove-Module -Force

$VerbosePreference = "Continue"
$ErrorActionPreference = "Stop"

BeforeAll {
    # Load the modules we want to test and any dependencies
    Import-Module "c:\Tests\Sol1\AAA.MicrosoftGraph.Component.psd1" -Force
}

Describe "Revoke-AAAUserSignInSessions" {
    BeforeAll {
        $parameters = @{
            UserPrincipalName = "testuser@test.com"
            AuthorizationHeader = @{ Authorization = "Bearer xxxx" }
        }
        Mock Write-Verbose -MockWith {} -ModuleName AAA.User
    }

    It "Validate 'Revoke-AAAUserSignInSessions' founded and revoked" {
        Mock Invoke-RestMethod { return $true } -ModuleName AAA.User
        $result = Revoke-AAAUserSignInSessions @parameters
        $result | Should -be $true
        Should -Invoke -CommandName Invoke-RestMethod -Exactly -Times 1 -ModuleName AAA.User
        Should -Invoke -CommandName Write-Verbose -Exactly -Times 3 -ModuleName AAA.User
    }

    It "Validate 'Revoke-AAAUserSignInSessions' not found" {
        Mock Invoke-RestMethod { return $null } -ModuleName AAA.User
        $result = Revoke-AAAUserSignInSessions @parameters
        $result | Should -be $false
        Should -Invoke -CommandName Invoke-RestMethod -Exactly -Times 1 -ModuleName AAA.User
        Should -Invoke -CommandName Write-Verbose -Exactly -Times 2 -ModuleName AAA.User
    }
}

Thanks in advance I'm going crazy:(

Revoke-AAAUserSignInSessions probably use Get-AAAGraphToken to get the authorization-token. I assume Get-AAAGraphToken is defined in the AAA.GraphCommon module.

In File2 you haven't mocked the Invoke-RestMethod that Get-AAAGraphToken calls (it would need -ModuleName AAA.GraphCommon ). Try adding the same mock that worked in File1 into File2:

$parameters = @{
    clientId            = "AAA-000"
    ClientSecret        = "yyyy"
    TenantId            = "testTenant"
    AuthorizationHeader = $true
}
Mock Invoke-RestMethod { return @{ access_token = "xxxxxxxx" } } -ModuleName AAA.GraphCommon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM