Functions/Get-GSuiteAccessToken.Tests.ps1

Describe "GSuite/Get-GSuiteAccessToken" -Tag "task", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Get-GSuiteAccessToken.ps1"

    # Declare external functions and mocks
    function Invoke-RestMethod {
        param ($Uri, $Headers, $Body, $Method)
        return @{
            expires_in   = 3600
            access_token = "token"
        }
    }

    context "when there are no issues" {
        # Declare mocks
        mock Invoke-RestMethod {
            param ($Uri, $Headers, $Body, $Method)
            return @{
                expires_in   = 3600
                access_token = "token"
            }
        }

        it "retrieves the authentication token given the input values" {
            # Call the function
            $output = Get-GSuiteAccessToken -ApplicationId "id" -ClientSecret "secret" `
                -RefreshToken "refreshToken" -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify the mocks
            Assert-MockCalled Invoke-RestMethod -Times 1 -Exactly -ParameterFilter {
                $Uri -eq "https://www.googleapis.com/oauth2/v4/token" -and
                $Headers.'Content-Type' -eq "application/json" -and
                $Method -eq "POST" -and
                $Body -eq @{
                    client_id     = "id"
                    client_secret = "secret"
                    grant_type    = "refresh_token"
                    refresh_token = "refreshToken"
                } | ConvertTo-Json
            } -Scope it

            # Verify the output
            $output | Should Be "token"
            $errorVariable | Should BeNullOrEmpty
        }
    }

    context "when Invoke-RestMethod throws an exception" {
        # Declare mocks
        mock Invoke-RestMethod {
            throw "error"
        }

        it "outputs an error and returns null" {
            # Call the function
            $output = Get-GSuiteAccessToken -ApplicationId "id" -ClientSecret "secret" `
                -RefreshToken "refreshToken" -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify the output
            $output | Should Be $null
            $errorVariable | Should Not BeNullOrEmpty
        }
    }

    context "when Invoke-RestMethod does not return the token" {
        # Declare mocks
        mock Invoke-RestMethod {
            return @{
                expires_in = 3600
            }
        }

        it "outputs an error and returns null" {
            # Call the function
            $output = Get-GSuiteAccessToken -ApplicationId "id" -ClientSecret "secret" `
                -RefreshToken "refreshToken" -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify the output
            $output | Should Be $null
            $errorVariable | Should Not BeNullOrEmpty
        }
    }
}