PowerShell Pester Mock Rest API 调用 [英] PowerShell Pester Mock Rest API Calls

查看:49
本文介绍了PowerShell Pester Mock Rest API 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何简单的方法可以模拟 Pester 中的 Rest API 调用.

Is there any simple approach on how to mock a Rest API Calls in Pester.

这是我的代码,我只需要模拟那些 Pester 中的 Rest API 调用 并测试它们,有人可以在这里帮助我.

Here is my code, I just need to mock those Rest API Calls in Pester and test them, could someone help me here.

Describe 'Test worldclockapi.com' {
    BeforeAll {
        $response = Invoke-WebRequest -Method 'GET' -Uri 'http://worldclockapi.com/api/json/utc/now'
        $responseContent = $response.Content | ConvertFrom-Json
        Write-Output $responseContent
    }

    It 'It should respond with 200' {
        $response.StatusCode | Should -Be 200
    }
    
    It 'It should have a null service response' {
        $responseContent.serviceResponse | Should -BeNullOrEmpty
    } 
    
    It 'It should be the right day of the week' {
        $dayOfWeek = (Get-Date).DayOfWeek
        $responseContent.dayOfTheWeek | Should -Be $dayOfWeek
    }
    
    It 'It should be the right year' {
        $year = Get-Date -Format 'yyyy'
        $responseContent.currentDateTime | Should -BeLike "*$year*"
    }
    
    It 'It should be the right month' {
        $month = Get-Date -Format 'MM'
        $responseContent.currentDateTime | Should -BeLike "*$month*"
    }
    
    # These two tests assume you are running this outside daylight savings (during the winter) .. hacky but good way to showcase the syntax ;)
    It 'It should not be daylight savings time' {
        $responseContent.isDayLightSavingsTime | Should -Not -Be $true
    }
    
    It 'It should not be daylight savings time another way' {
        $responseContent.isDayLightSavingsTime | Should -BeFalse
    }
}

推荐答案

我认为 Daniel 的回答 很棒,但如果您正在处理大型或共享存储库,那么您只需要小心管理这些 XML 文件.我使用的另一种选择是使用真实响应为所有返回的对象创建一个大型 Json 文件.它可以在 BeforeAllBeforeDiscovery 中导入,具体取决于您的测试的结构.

I think Daniel's answer is great, but if you are working on a large or shared repository then you just need to be careful about managing those XML files too. Another option, which I use, is to have one large Json file for all your returned objects using real responses. It can be imported in either BeforeAll or BeforeDiscovery depending on how your tests are structured.

我的补充答案的原因实际上也只是为了涵盖错误响应,因为让测试用例显示您如何处理 REST 调用失败是很重要的.将 Invoke-WebRequest 包装在您自己的函数中可能有助于返回个性化错误、处理标头响应以及为站点名称或一组允许的 API 路径提供常量.例如,根据 PowerShell 的版本,这就是我处理 404 的方式.

The reason for my supplementary answer is really just to cover error responses too, because it is important to have test cases that show how you deal with a REST call failing. Wrapping Invoke-WebRequest in your own function might be useful for returning personalised errors, handling header responses, and having constants for a site name or an allowed set of API paths. Depending on the version of PowerShell, this is how I might handle a 404, for example.

Context " When a path does not exist in the API" {
    BeforeAll {
        Mock Invoke-WebRequest {
            # Use the actual types returned by your function or directly from Invoke-WebRequest.
            if ($PSVersionTable.PSEdition -eq "Desktop") {
                $WR = New-MockObject -Type 'System.Net.HttpWebResponse'
                $Code = [System.Net.HttpStatusCode]::NotFound
                # Use Add-Member because StatusCode is a read-only field on HttpWebResponse
                $WR | Add-Member -MemberType NoteProperty -Name StatusCode -Value $Code -Force
                $Status = [System.Net.WebExceptionStatus]::ProtocolError
                $Ex = [System.Net.WebException]::new("404", $null, $Status, $WR)
            }
            else {
                $Message = [System.Net.Http.HttpResponseMessage]::new()
                $Message.StatusCode = [System.Net.HttpStatusCode]::NotFound
                $Ex = [Microsoft.PowerShell.Commands.HttpResponseException]::new("404", $Message)
            }
            throw $Ex
        } -ParameterFilter {
            $Uri -eq "http://worldclockapi.com/api/json/utc/NEVER" -and
            $Method -eq "Get"
        }

        $GetRestTimeParams = @{
            Uri   = "http://worldclockapi.com/api/json/utc/NEVER"
            Method = "Get"
        }
    }

    It " Get-RestTime should not run successfully" {
        { Get-RestTime @GetRestTimeParams } | Should -Throw
    }

    It " Get-RestTime should throw a 404 error" {
        $ShouldParams = @{
            # Use the actual types returned by your function or directly from Invoke-WebRequest.
            ExceptionType   = [System.Net.WebException]
            ExpectedMessage = "404: NotFound"
        }
        {
            Get-RestTime @GetRestTimeParams
        } | Should -Throw @ShouldParams
    }
}

这篇关于PowerShell Pester Mock Rest API 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆