-
Notifications
You must be signed in to change notification settings - Fork 457
/
Test-ModuleLocally.ps1
346 lines (293 loc) · 14.2 KB
/
Test-ModuleLocally.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<#
.SYNOPSIS
This function helps with testing a module locally
.DESCRIPTION
This function helps with testing a module locally. Use this function To perform Pester testing for a module and then attempting to deploy it. It also allows you to use your own
subscription Id, principal Id, tenant ID and other parameters that need to be tokenized.
.PARAMETER TemplateFilePath
Mandatory. Path to the Bicep/ARM module that is being tested
.PARAMETER ModuleTestFilePath
Optional. Path to the template file/folder that is to be tested with the template file. Defaults to the module's default '.test' folder. Will be used if the DeploymentTest/ValidationTest switches are set.
.PARAMETER PesterTest
Optional. A switch parameter that triggers a Pester test for the module
.PARAMETER ValidateOrDeployParameters
Optional. An object consisting of the components that are required when using the Validate test or DeploymentTest switch parameter. Mandatory if the DeploymentTest/ValidationTest switches are set.
.PARAMETER DeploymentTest
Optional. A switch parameter that triggers the deployment of the module
.PARAMETER ValidationTest
Optional. A switch parameter that triggers the validation of the module only without deployment
.PARAMETER WhatIfTest
Optional. A switch parameter that triggers the what-if test of the module only without deployment
.PARAMETER SkipParameterFileTokens
Optional. A switch parameter that enables you to skip the search for local custom parameter file tokens.
.PARAMETER AdditionalTokens
Optional. A hashtable parameter that contains custom tokens to be replaced in the paramter files for deployment
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
ModuleTestFilePath = 'C:\network\route-table\.test\common\main.test.bicep'
PesterTest = $false
DeploymentTest = $false
WhatIfTest = $false
ValidationTest = $true
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run a Test-Az*Deployment using a test file with the provided tokens
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
ModuleTestFilePath = 'C:\network\route-table\tests\e2e\defaults\main.test.bicep'
PesterTest = $false
DeploymentTest = $false
WhatIfTest = $true
ValidationTest = $false
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Get What-If deployment result using a specific test-template combination with the provided tokens
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
ModuleTestFilePath = 'C:\network\route-table\.test\common\main.test.bicep'
PesterTest = $false
DeploymentTest = $false
WhatIfTest = $true
ValidationTest = $false
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Get What-If deployment result using a test file with the provided tokens
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
PesterTest = $true
DeploymentTest = $false
WhatIfTest = $false
ValidationTest = $true
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run all Pester tests for a given template and a Test-Az*Deployment using each test file in the module's default test folder ('.test') in combination with the template and the provided tokens
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
PesterTest = $true
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run all Pester tests for the given template file
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
PesterTest = $true
ValidateOrDeployParameters = @{
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run all Pester tests for the given template file including tests for the use of tokens
.NOTES
- Make sure you provide the right information in the 'ValidateOrDeployParameters' parameter for this function to work.
- Ensure you have the ability to perform the deployment operations using your account (if planning to test deploy or performing what-if validation.)
#>
function Test-ModuleLocally {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[string] $TemplateFilePath,
[Parameter(Mandatory = $false)]
[string] $ModuleTestFilePath = (Join-Path (Split-Path $TemplateFilePath -Parent) 'tests'),
[Parameter(Mandatory = $false)]
[string] $PesterTestFilePath = 'utilities/pipelines/staticValidation/module.tests.ps1',
[Parameter(Mandatory = $false)]
[Psobject] $ValidateOrDeployParameters = @{},
[Parameter(Mandatory = $false)]
[hashtable] $AdditionalTokens = @{},
[Parameter(Mandatory = $false)]
[switch] $PesterTest,
[Parameter(Mandatory = $false)]
[switch] $DeploymentTest,
[Parameter(Mandatory = $false)]
[switch] $ValidationTest,
[Parameter(Mandatory = $false)]
[switch] $WhatIfTest
)
begin {
$repoRootPath = (Get-Item $PSScriptRoot).Parent.Parent
$ModuleName = Split-Path (Split-Path $TemplateFilePath -Parent) -Leaf
$utilitiesFolderPath = Split-Path $PSScriptRoot -Parent
Write-Verbose "Running local tests for [$ModuleName]"
# Load Tokens Converter Scripts
. (Join-Path $utilitiesFolderPath 'pipelines' 'tokensReplacement' 'Convert-TokensInFileList.ps1')
# Load Modules Validation / Deployment Scripts
. (Join-Path $utilitiesFolderPath 'pipelines' 'resourceDeployment' 'New-TemplateDeployment.ps1')
. (Join-Path $utilitiesFolderPath 'pipelines' 'resourceDeployment' 'Test-TemplateDeployment.ps1')
. (Join-Path $PSScriptRoot 'helper' 'Get-TemplateDeploymentWhatIf.ps1')
}
process {
# Find Test Parameter Files
# -------------------------
if ((Get-Item -Path $ModuleTestFilePath) -is [System.IO.DirectoryInfo]) {
$moduleTestFiles = (Get-ChildItem -Path $ModuleTestFilePath -File).FullName
} else {
$moduleTestFiles = @($ModuleTestFilePath)
}
# Construct Token Configuration Input
$GlobalVariablesObject = Get-Content -Path (Join-Path $repoRootPath 'settings.yml') | ConvertFrom-Yaml -ErrorAction Stop | Select-Object -ExpandProperty 'variables'
$tokenConfiguration = @{
FilePathList = $moduleTestFiles
Tokens = @{}
TokenPrefix = $GlobalVariablesObject | Select-Object -ExpandProperty 'tokenPrefix'
TokenSuffix = $GlobalVariablesObject | Select-Object -ExpandProperty 'tokenSuffix'
}
# Add Enforced Tokens
$enforcedTokenList = @{}
if ($ValidateOrDeployParameters.ContainsKey('subscriptionId')) {
$enforcedTokenList['subscriptionId'] = $ValidateOrDeployParameters.SubscriptionId
}
if ($ValidateOrDeployParameters.ContainsKey('managementGroupId')) {
$enforcedTokenList['managementGroupId'] = $ValidateOrDeployParameters.ManagementGroupId
}
if ($AdditionalTokens.ContainsKey('tenantId')) {
$enforcedTokenList['tenantId'] = $AdditionalTokens['tenantId']
}
$tokenConfiguration.Tokens += $enforcedTokenList
# Add local (source control) tokens
foreach ($localToken in ($GlobalVariablesObject.Keys | ForEach-Object { if ($PSItem.contains('localToken_')) { $PSItem } })) {
$tokenConfiguration.Tokens[$localToken.Replace('localToken_', '', 'OrdinalIgnoreCase')] = $GlobalVariablesObject.$localToken
}
# Add Other Parameter File Tokens (For Testing)
$AdditionalTokens.Keys | ForEach-Object {
$tokenConfiguration.Tokens[$PSItem] = $AdditionalTokens.$PSItem
}
################
# PESTER Tests #
################
if ($PesterTest) {
Write-Verbose "Pester Testing Module: $ModuleName"
# Construct Pester Token Configuration Input
$PesterTokenConfiguration = @{
FilePathList = $moduleTestFiles
Tokens = $enforcedTokenList
TokenPrefix = $GlobalVariablesObject | Select-Object -ExpandProperty tokenPrefix
TokenSuffix = $GlobalVariablesObject | Select-Object -ExpandProperty tokenSuffix
}
try {
Invoke-Pester -Configuration @{
Run = @{
Container = New-PesterContainer -Path (Join-Path $repoRootPath $PesterTestFilePath) -Data @{
repoRootPath = $repoRootPath
moduleFolderPaths = Split-Path $TemplateFilePath -Parent
tokenConfiguration = $PesterTokenConfiguration
}
}
Output = @{
Verbosity = 'Detailed'
}
}
} catch {
$PSItem.Exception.Message
}
}
#################################
# Validation & Deployment tests #
#################################
if (($ValidationTest -or $DeploymentTest -or $WhatIfTest) -and $ValidateOrDeployParameters) {
# Invoke Token Replacement Functionality and Convert Tokens in Parameter Files
$null = Convert-TokensInFileList @tokenConfiguration
# Deployment & Validation Testing
# -------------------------------
$functionInput = @{
TemplateFilePath = $TemplateFilePath
location = $ValidateOrDeployParameters.Location
resourceGroupName = $ValidateOrDeployParameters.ResourceGroupName
subscriptionId = $ValidateOrDeployParameters.SubscriptionId
managementGroupId = $ValidateOrDeployParameters.ManagementGroupId
Verbose = $true
}
try {
# Validate template
# -----------------
if ($ValidationTest) {
# Loop through test files
foreach ($moduleTestFile in $moduleTestFiles) {
Write-Verbose ('Validating module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)) -Verbose
Test-TemplateDeployment @functionInput -TemplateFilePath $moduleTestFile
}
}
# What-If validation for template
# -----------------
if ($WhatIfTest) {
# Loop through test files
foreach ($moduleTestFile in $moduleTestFiles) {
Write-Verbose ('Get Deployment What-If result for module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)) -Verbose
Get-TemplateDeploymentWhatIf @functionInput -TemplateFilePath $moduleTestFile
}
}
# Deploy template
# ---------------
if ($DeploymentTest) {
$functionInput['retryLimit'] = 1 # Overwrite default of 3
# Loop through test files
foreach ($moduleTestFile in $moduleTestFiles) {
Write-Verbose ('Deploy Module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)) -Verbose
if ($PSCmdlet.ShouldProcess(('Module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)), 'Deploy')) {
New-TemplateDeployment @functionInput -TemplateFilePath $moduleTestFile
}
}
}
} catch {
Write-Error $_
} finally {
# Restore test files
# ------------------
if (($ValidationTest -or $DeploymentTest) -and $ValidateOrDeployParameters) {
# Replace Values with Tokens For Repo Updates
Write-Verbose 'Restoring Tokens'
$null = Convert-TokensInFileList @tokenConfiguration -SwapValueWithName $true
}
}
}
}
end {
}
}