Skip to content

Commit 6595086

Browse files
Refactor common Pester test infrastructure (#112)
The Pester test files contained _a lot_ of duplicated test setup/configuration. This update factors all of that out to Test/Common.ps1 so that _just about_ the entire content of a Pester test file can be unique to the code being tested.
1 parent 67f9c5b commit 6595086

10 files changed

+164
-643
lines changed

Tests/Common.ps1

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
# Caches if the tests are actively configured with an access token.
5+
$script:accessTokenConfigured = $false
6+
7+
# The path to a file storing the contents of the user's config file before tests got underway
8+
$script:originalConfigFile = $null
9+
10+
function Initialize-CommonTestSetup
11+
{
12+
<#
13+
.SYNOPSIS
14+
Configures the tests to run with the authentication information stored in the project's
15+
Azure DevOps pipeline (if that information exists in the environment).
16+
17+
.DESCRIPTION
18+
Configures the tests to run with the authentication information stored in the project's
19+
Azure DevOps pipeline (if that information exists in the environment).
20+
21+
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
22+
23+
.NOTES
24+
Internal-only helper method.
25+
26+
The only reason this exists is so that we can leverage CodeAnalysis.SuppressMessageAttribute,
27+
which can only be applied to functions.
28+
29+
This method is invoked immediately after the declaration.
30+
#>
31+
[CmdletBinding()]
32+
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Justification="Needed to configure with the stored, encrypted string value in AppVeyor.")]
33+
param()
34+
35+
$moduleRootPath = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
36+
. (Join-Path -Path $moduleRootPath -ChildPath 'Tests\Config\Settings.ps1')
37+
Import-Module -Name (Join-Path -Path $moduleRootPath -ChildPath 'PowerShellForGitHub.psd1') -Force
38+
39+
if ([string]::IsNullOrEmpty($env:avAccessToken))
40+
{
41+
$message = @(
42+
'The tests are using the configuration settings defined in Tests\Config\Settings.ps1.',
43+
'If you haven''t locally modified those values, your tests are going to fail since you',
44+
'don''t have access to the default accounts referenced. If that is the case, you should',
45+
'cancel the existing tests, modify the values to ones you have access to, call',
46+
'Set-GitHubAuthentication to cache your AccessToken, and then try running the tests again.')
47+
Write-Warning -Message ($message -join [Environment]::NewLine)
48+
}
49+
else
50+
{
51+
$secureString = $env:avAccessToken | ConvertTo-SecureString -AsPlainText -Force
52+
$cred = New-Object System.Management.Automation.PSCredential "<username is ignored>", $secureString
53+
Set-GitHubAuthentication -Credential $cred
54+
55+
$script:ownerName = $env:avOwnerName
56+
$script:organizationName = $env:avOrganizationName
57+
58+
Write-Warning -Message 'This run is being executed in the AppVeyor environment.'
59+
}
60+
61+
$script:accessTokenConfigured = Test-GitHubAuthenticationConfigured
62+
if (-not $script:accessTokenConfigured)
63+
{
64+
$message = @(
65+
'GitHub API Token not defined. Most of these tests are going to fail since they require authentication.',
66+
'403 errors may also start to occur due to the GitHub hourly limit for unauthenticated queries.')
67+
Write-Warning -Message ($message -join [Environment]::NewLine)
68+
}
69+
70+
# Backup the user's configuration before we begin, and ensure we're at a pure state before running
71+
# the tests. We'll restore it at the end.
72+
$script:originalConfigFile = New-TemporaryFile
73+
74+
Backup-GitHubConfiguration -Path $script:originalConfigFile
75+
Set-GitHubConfiguration -DisableTelemetry # Avoid the telemetry event from calling Reset-GitHubConfiguration
76+
Reset-GitHubConfiguration
77+
Set-GitHubConfiguration -DisableTelemetry # We don't want UT's to impact telemetry
78+
Set-GitHubConfiguration -LogRequestBody # Make it easier to debug UT failures
79+
}
80+
81+
Initialize-CommonTestSetup

Tests/GitHubAnalytics.tests.ps1

Lines changed: 9 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -6,78 +6,12 @@
66
Tests for GitHubAnalytics.ps1 module
77
#>
88

9-
[String] $root = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
10-
. (Join-Path -Path $root -ChildPath 'Tests\Config\Settings.ps1')
11-
Import-Module -Name $root -Force
12-
13-
function Initialize-AppVeyor
14-
{
15-
<#
16-
.SYNOPSIS
17-
Configures the tests to run with the authentication information stored in AppVeyor
18-
(if that information exists in the environment).
19-
20-
.DESCRIPTION
21-
Configures the tests to run with the authentication information stored in AppVeyor
22-
(if that information exists in the environment).
23-
24-
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
25-
26-
.NOTES
27-
Internal-only helper method.
28-
29-
The only reason this exists is so that we can leverage CodeAnalysis.SuppressMessageAttribute,
30-
which can only be applied to functions.
31-
32-
We call this immediately after the declaration so that AppVeyor initialization can heppen
33-
(if applicable).
34-
35-
#>
36-
[CmdletBinding()]
37-
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Justification="Needed to configure with the stored, encrypted string value in AppVeyor.")]
38-
param()
39-
40-
if ($env:AppVeyor)
41-
{
42-
$secureString = $env:avAccessToken | ConvertTo-SecureString -AsPlainText -Force
43-
$cred = New-Object System.Management.Automation.PSCredential "<username is ignored>", $secureString
44-
Set-GitHubAuthentication -Credential $cred
45-
46-
$script:ownerName = $env:avOwnerName
47-
$script:organizationName = $env:avOrganizationName
48-
49-
$message = @(
50-
'This run is executed in the AppVeyor environment.',
51-
'The GitHub Api Token won''t be decrypted in PR runs causing some tests to fail.',
52-
'403 errors possible due to GitHub hourly limit for unauthenticated queries.',
53-
'Use Set-GitHubAuthentication manually. modify the values in Tests\Config\Settings.ps1,',
54-
'and run tests on your machine first.')
55-
Write-Warning -Message ($message -join [Environment]::NewLine)
56-
}
57-
}
58-
59-
Initialize-AppVeyor
60-
61-
$script:accessTokenConfigured = Test-GitHubAuthenticationConfigured
62-
if (-not $script:accessTokenConfigured)
63-
{
64-
$message = @(
65-
'GitHub API Token not defined, some of the tests will be skipped.',
66-
'403 errors possible due to GitHub hourly limit for unauthenticated queries.')
67-
Write-Warning -Message ($message -join [Environment]::NewLine)
68-
}
69-
70-
# Backup the user's configuration before we begin, and ensure we're at a pure state before running
71-
# the tests. We'll restore it at the end.
72-
$configFile = New-TemporaryFile
9+
# This is common test code setup logic for all Pester test files
10+
$moduleRootPath = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
11+
. (Join-Path -Path $moduleRootPath -ChildPath 'Tests\Common.ps1')
7312

7413
try
7514
{
76-
Backup-GitHubConfiguration -Path $configFile
77-
Reset-GitHubConfiguration
78-
Set-GitHubConfiguration -DisableTelemetry # We don't want UT's to impact telemetry
79-
Set-GitHubConfiguration -LogRequestBody # Make it easier to debug UT failures
80-
8115
Describe 'Obtaining issues for repository' {
8216
$repo = New-GitHubRepository -RepositoryName ([Guid]::NewGuid().Guid) -AutoInit
8317

@@ -378,6 +312,10 @@ try
378312
}
379313
finally
380314
{
381-
# Restore the user's configuration to its pre-test state
382-
Restore-GitHubConfiguration -Path $configFile
315+
if (Test-Path -Path $script:originalConfigFile -PathType Leaf)
316+
{
317+
# Restore the user's configuration to its pre-test state
318+
Restore-GitHubConfiguration -Path $script:originalConfigFile
319+
$script:originalConfigFile = $null
320+
}
383321
}

Tests/GitHubAssignees.tests.ps1

Lines changed: 9 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -6,78 +6,12 @@
66
Tests for GitHubAssignees.ps1 module
77
#>
88

9-
[String] $root = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
10-
. (Join-Path -Path $root -ChildPath 'Tests\Config\Settings.ps1')
11-
Import-Module -Name $root -Force
12-
13-
function Initialize-AppVeyor
14-
{
15-
<#
16-
.SYNOPSIS
17-
Configures the tests to run with the authentication information stored in AppVeyor
18-
(if that information exists in the environment).
19-
20-
.DESCRIPTION
21-
Configures the tests to run with the authentication information stored in AppVeyor
22-
(if that information exists in the environment).
23-
24-
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
25-
26-
.NOTES
27-
Internal-only helper method.
28-
29-
The only reason this exists is so that we can leverage CodeAnalysis.SuppressMessageAttribute,
30-
which can only be applied to functions.
31-
32-
We call this immediately after the declaration so that AppVeyor initialization can happen
33-
(if applicable).
34-
35-
#>
36-
[CmdletBinding()]
37-
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Justification="Needed to configure with the stored, encrypted string value in AppVeyor.")]
38-
param()
39-
40-
if ($env:AppVeyor)
41-
{
42-
$secureString = $env:avAccessToken | ConvertTo-SecureString -AsPlainText -Force
43-
$cred = New-Object System.Management.Automation.PSCredential "<username is ignored>", $secureString
44-
Set-GitHubAuthentication -Credential $cred
45-
46-
$script:ownerName = $env:avOwnerName
47-
$script:organizationName = $env:avOrganizationName
48-
49-
$message = @(
50-
'This run is executed in the AppVeyor environment.',
51-
'The GitHub Api Token won''t be decrypted in PR runs causing some tests to fail.',
52-
'403 errors possible due to GitHub hourly limit for unauthenticated queries.',
53-
'Use Set-GitHubAuthentication manually. modify the values in Tests\Config\Settings.ps1,',
54-
'and run tests on your machine first.')
55-
Write-Warning -Message ($message -join [Environment]::NewLine)
56-
}
57-
}
58-
59-
Initialize-AppVeyor
60-
61-
$script:accessTokenConfigured = Test-GitHubAuthenticationConfigured
62-
if (-not $script:accessTokenConfigured)
63-
{
64-
$message = @(
65-
'GitHub API Token not defined, some of the tests will be skipped.',
66-
'403 errors possible due to GitHub hourly limit for unauthenticated queries.')
67-
Write-Warning -Message ($message -join [Environment]::NewLine)
68-
}
69-
70-
# Backup the user's configuration before we begin, and ensure we're at a pure state before running
71-
# the tests. We'll restore it at the end.
72-
$configFile = New-TemporaryFile
9+
# This is common test code setup logic for all Pester test files
10+
$moduleRootPath = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
11+
. (Join-Path -Path $moduleRootPath -ChildPath 'Tests\Common.ps1')
7312

7413
try
7514
{
76-
Backup-GitHubConfiguration -Path $configFile
77-
Reset-GitHubConfiguration
78-
Set-GitHubConfiguration -DisableTelemetry # We don't want UT's to impact telemetry
79-
Set-GitHubConfiguration -LogRequestBody # Make it easier to debug UT failures
80-
8115
$repo = New-GitHubRepository -RepositoryName ([Guid]::NewGuid().Guid) -AutoInit
8216
$issue = New-GitHubIssue -Uri $repo.svn_url -Title "Test issue"
8317

@@ -131,6 +65,10 @@ try
13165
}
13266
finally
13367
{
134-
# Restore the user's configuration to its pre-test state
135-
Restore-GitHubConfiguration -Path $configFile
68+
if (Test-Path -Path $script:originalConfigFile -PathType Leaf)
69+
{
70+
# Restore the user's configuration to its pre-test state
71+
Restore-GitHubConfiguration -Path $script:originalConfigFile
72+
$script:originalConfigFile = $null
73+
}
13674
}

Tests/GitHubComments.tests.ps1

Lines changed: 10 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -6,79 +6,13 @@
66
Tests for GitHubComments.ps1 module
77
#>
88

9-
[String] $root = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
10-
. (Join-Path -Path $root -ChildPath 'Tests\Config\Settings.ps1')
11-
Import-Module -Name $root -Force
9+
# This is common test code setup logic for all Pester test files
10+
$moduleRootPath = Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)
11+
. (Join-Path -Path $moduleRootPath -ChildPath 'Tests\Common.ps1')
1212

13-
function Initialize-AppVeyor
14-
{
15-
<#
16-
.SYNOPSIS
17-
Configures the tests to run with the authentication information stored in AppVeyor
18-
(if that information exists in the environment).
19-
20-
.DESCRIPTION
21-
Configures the tests to run with the authentication information stored in AppVeyor
22-
(if that information exists in the environment).
23-
24-
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
25-
26-
.NOTES
27-
Internal-only helper method.
28-
29-
The only reason this exists is so that we can leverage CodeAnalysis.SuppressMessageAttribute,
30-
which can only be applied to functions.
31-
32-
We call this immediately after the declaration so that AppVeyor initialization can heppen
33-
(if applicable).
34-
35-
#>
36-
[CmdletBinding()]
37-
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Justification="Needed to configure with the stored, encrypted string value in AppVeyor.")]
38-
param()
39-
40-
if ($env:AppVeyor)
41-
{
42-
$secureString = $env:avAccessToken | ConvertTo-SecureString -AsPlainText -Force
43-
$cred = New-Object System.Management.Automation.PSCredential "<username is ignored>", $secureString
44-
Set-GitHubAuthentication -Credential $cred
45-
46-
$script:ownerName = $env:avOwnerName
47-
$script:organizationName = $env:avOrganizationName
48-
49-
$message = @(
50-
'This run is executed in the AppVeyor environment.',
51-
'The GitHub Api Token won''t be decrypted in PR runs causing some tests to fail.',
52-
'403 errors possible due to GitHub hourly limit for unauthenticated queries.',
53-
'Use Set-GitHubAuthentication manually. modify the values in Tests\Config\Settings.ps1,',
54-
'and run tests on your machine first.')
55-
Write-Warning -Message ($message -join [Environment]::NewLine)
56-
}
57-
}
58-
59-
Initialize-AppVeyor
60-
61-
$script:accessTokenConfigured = Test-GitHubAuthenticationConfigured
62-
if (-not $script:accessTokenConfigured)
63-
{
64-
$message = @(
65-
'GitHub API Token not defined, some of the tests will be skipped.',
66-
'403 errors possible due to GitHub hourly limit for unauthenticated queries.')
67-
Write-Warning -Message ($message -join [Environment]::NewLine)
68-
}
69-
70-
# Backup the user's configuration before we begin, and ensure we're at a pure state before running
71-
# the tests. We'll restore it at the end.
72-
$configFile = New-TemporaryFile
7313
try
7414
{
75-
Backup-GitHubConfiguration -Path $configFile
76-
Reset-GitHubConfiguration
77-
Set-GitHubConfiguration -DisableTelemetry # We don't want UT's to impact telemetry
78-
Set-GitHubConfiguration -LogRequestBody # Make it easier to debug UT failures
79-
8015
# Define Script-scoped, readonly, hidden variables.
81-
8216
@{
8317
defaultIssueTitle = "Test Title"
8418
defaultCommentBody = "This is a test body."
@@ -157,6 +91,10 @@ try
15791
}
15892
finally
15993
{
160-
# Restore the user's configuration to its pre-test state
161-
Restore-GitHubConfiguration -Path $configFile
162-
}
94+
if (Test-Path -Path $script:originalConfigFile -PathType Leaf)
95+
{
96+
# Restore the user's configuration to its pre-test state
97+
Restore-GitHubConfiguration -Path $script:originalConfigFile
98+
$script:originalConfigFile = $null
99+
}
100+
}

0 commit comments

Comments
 (0)