-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathmodule.tests.ps1
More file actions
1675 lines (1341 loc) · 80.9 KB
/
module.tests.ps1
File metadata and controls
1675 lines (1341 loc) · 80.9 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 7
param (
[Parameter(Mandatory = $false)]
[array] $moduleFolderPaths = ((Get-ChildItem $repoRootPath -Recurse -Directory -Force).FullName | Where-Object {
(Get-ChildItem $_ -File -Depth 0 -Include @('main.json', 'main.bicep') -Force).Count -gt 0
}),
[Parameter(Mandatory = $false)]
[string] $repoRootPath = (Get-Item $PSScriptRoot).Parent.Parent.Parent.FullName,
# Dedicated Tokens configuration hashtable containing the tokens and token prefix and suffix.
[Parameter(Mandatory = $false)]
[hashtable] $tokenConfiguration = @{},
[Parameter(Mandatory = $false)]
[bool] $AllowPreviewVersionsInAPITests = $true
)
Write-Verbose ("repoRootPath: $repoRootPath") -Verbose
Write-Verbose ("moduleFolderPaths: $($moduleFolderPaths.count)") -Verbose
$script:RGdeployment = 'https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#'
$script:Subscriptiondeployment = 'https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#'
$script:MGdeployment = 'https://schema.management.azure.com/schemas/2019-08-01/managementGroupDeploymentTemplate.json#'
$script:Tenantdeployment = 'https://schema.management.azure.com/schemas/2019-08-01/tenantDeploymentTemplate.json#'
$script:moduleFolderPaths = $moduleFolderPaths
# For runtime purposes, we cache the compiled template in a hashtable that uses a formatted relative module path as a key
$script:convertedTemplates = @{}
# Shared exception messages
$script:bicepTemplateCompilationFailedException = "Unable to compile the main.bicep template's content. This can happen if there is an error in the template. Please check if you can run the command ``bicep build {0} --stdout | ConvertFrom-Json -AsHashtable``." # -f $templateFilePath
$script:jsonTemplateLoadFailedException = "Unable to load the main.json template's content. This can happen if there is an error in the template. Please check if you can run the command `Get-Content {0} -Raw | ConvertFrom-Json -AsHashtable`." # -f $templateFilePath
$script:templateNotFoundException = 'No template file found in folder [{0}]' # -f $moduleFolderPath
# Import any helper function used in this test script
Import-Module (Join-Path $PSScriptRoot 'helper' 'helper.psm1') -Force
$script:crossReferencedModuleList = Get-CrossReferencedModuleList
Describe 'File/folder tests' -Tag 'Modules' {
Context 'General module folder tests' {
$moduleFolderTestCases = [System.Collections.ArrayList] @()
foreach ($moduleFolderPath in $moduleFolderPaths) {
$moduleFolderTestCases += @{
moduleFolderName = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
moduleFolderPath = $moduleFolderPath
isTopLevelModule = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1].Split('/').Count -eq 2 # <provider>/<resourceType>
}
}
It '[<moduleFolderName>] Module should contain a [` main.json ` / ` main.bicep `] file.' -TestCases $moduleFolderTestCases {
param( [string] $moduleFolderPath )
$hasARM = Test-Path (Join-Path -Path $moduleFolderPath 'main.json')
$hasBicep = Test-Path (Join-Path -Path $moduleFolderPath 'main.bicep')
($hasARM -or $hasBicep) | Should -Be $true
}
It '[<moduleFolderName>] Module should contain a [` README.md `] file.' -TestCases $moduleFolderTestCases {
param(
[string] $moduleFolderPath
)
$readMeFilePath = Join-Path -Path $moduleFolderPath 'README.md'
$pathExisting = Test-Path $readMeFilePath
$pathExisting | Should -Be $true
$file = Get-Item -Path $readMeFilePath
$file.Name | Should -BeExactly 'README.md'
}
It '[<moduleFolderName>] Module should contain a [` .test `] folder.' -TestCases ($moduleFolderTestCases | Where-Object { $_.isTopLevelModule }) {
param(
[string] $moduleFolderPath
)
$pathExisting = Test-Path (Join-Path -Path $moduleFolderPath '.test')
$pathExisting | Should -Be $true
}
It '[<moduleFolderName>] Module should contain a [` version.json `] file.' -TestCases $moduleFolderTestCases {
param (
[string] $moduleFolderPath
)
$pathExisting = Test-Path (Join-Path -Path $moduleFolderPath 'version.json')
$pathExisting | Should -Be $true
}
}
Context '.test folder' {
$folderTestCases = [System.Collections.ArrayList]@()
foreach ($moduleFolderPath in $moduleFolderPaths) {
if (Test-Path (Join-Path $moduleFolderPath '.test')) {
$folderTestCases += @{
moduleFolderName = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
moduleFolderPath = $moduleFolderPath
}
}
}
It '[<moduleFolderName>] Folder should contain one or more test files.' -TestCases $folderTestCases {
param(
[string] $moduleFolderName,
[string] $moduleFolderPath
)
$moduleTestFilePaths = Get-ModuleTestFileList -ModulePath $moduleFolderPath | ForEach-Object { Join-Path $moduleFolderPath $_ }
$moduleTestFilePaths.Count | Should -BeGreaterThan 0
}
$testFolderFilesTestCases = [System.Collections.ArrayList] @()
foreach ($moduleFolderPath in $moduleFolderPaths) {
$testFolderPath = Join-Path $moduleFolderPath '.test'
if (Test-Path $testFolderPath) {
foreach ($testFilePath in (Get-ModuleTestFileList -ModulePath $moduleFolderPath | ForEach-Object { Join-Path $moduleFolderPath $_ })) {
$testFolderFilesTestCases += @{
moduleFolderName = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
testFilePath = $testFilePath
}
}
}
}
It '[<moduleFolderName>] JSON test files in the `.test` folder should be valid json.' -TestCases $testFolderFilesTestCases {
param(
[string] $moduleFolderName,
[string] $testFilePath
)
if ((Split-Path $testFilePath -Extension) -eq '.json') {
{ (Get-Content $testFilePath) | ConvertFrom-Json } | Should -Not -Throw
} else {
Set-ItResult -Skipped -Because 'the module has no JSON test files.'
}
}
}
}
Describe 'Pipeline tests' -Tag 'Pipeline' {
$moduleFolderTestCases = [System.Collections.ArrayList] @()
foreach ($moduleFolderPath in $moduleFolderPaths) {
$resourceTypeIdentifier = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
$moduleFolderTestCases += @{
moduleFolderName = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
moduleFolderPath = $moduleFolderPath
isTopLevelModule = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1].Split('/').Count -eq 2 # <provider>/<resourceType>
templateReferences = $crossReferencedModuleList[$resourceTypeIdentifier]
}
}
if (Test-Path (Join-Path $repoRootPath '.github')) {
It '[<moduleFolderName>] Module should have a GitHub workflow.' -TestCases ($moduleFolderTestCases | Where-Object { $_.isTopLevelModule }) {
param(
[string] $moduleFolderName,
[string] $moduleFolderPath
)
$workflowsFolderName = Join-Path $repoRootPath '.github' 'workflows'
$workflowFileName = Get-PipelineFileName -ResourceIdentifier $moduleFolderName
$workflowPath = Join-Path $workflowsFolderName $workflowFileName
Test-Path $workflowPath | Should -Be $true -Because "path [$workflowPath] should exist."
}
It '[<moduleFolderName>] Module workflow should have trigger for cross-module references, if any.' -TestCases ($moduleFolderTestCases | Where-Object { $_.isTopLevelModule }) {
param(
[string] $moduleFolderName,
[string] $moduleFolderPath,
[Hashtable] $templateReferences
)
$localReferences = $templateReferences.localPathReferences
if (-not $localReferences) {
Set-ItResult -Skipped -Because 'the module has no local cross module references.'
return
}
$workflowsFolderName = Join-Path $repoRootPath '.github' 'workflows'
$workflowFileName = Get-PipelineFileName -ResourceIdentifier $moduleFolderName
$workflowFilePath = Join-Path $workflowsFolderName $workflowFileName
$workflowContent = Get-Content -Path $workflowFilePath
# Get paths start index
$workflowPathsIndex = $workflowContent | ForEach-Object {
if ($_ -match '^\s*paths:\s*$') {
return $workflowContent.IndexOf($Matches[0])
}
}
$workflowPathsStartIndex = $workflowPathsIndex + 1
# Get paths end index
$workflowPathsEndIndex = $workflowPathsStartIndex
while ($workflowContent[($workflowPathsEndIndex + 1)] -match "^\s*- '.+$") {
$workflowPathsEndIndex++
}
# Extract data
$extractedPaths = $workflowContent[$workflowPathsStartIndex .. $workflowPathsEndIndex] | ForEach-Object {
$null = $_ -match "^\s*- '(.+)'$"
$Matches[1]
}
# Re-create result set
$workflowModuleTriggerPaths = $extractedPaths | Where-Object { $_ -match '^modules\/.*$' }
$missingCrossModuleReferenceTriggers = [System.Collections.ArrayList] @()
foreach ($localReference in $localReferences) {
$expectedPath = "modules/$localReference/**"
if ($workflowModuleTriggerPaths -notcontains $expectedPath) {
$missingCrossModuleReferenceTriggers += $expectedPath
}
}
$missingCrossModuleReferenceTriggers.Count | Should -Be 0 -Because ('the list of missing pipeline triggers [{0}] should be empty' -f ($missingCrossModuleReferenceTriggers -join ','))
}
}
if (Test-Path (Join-Path $repoRootPath '.azuredevops')) {
It '[<moduleFolderName>] Module should have an Azure DevOps pipeline.' -TestCases ($moduleFolderTestCases | Where-Object { $_.isTopLevelModule }) {
param(
[string] $moduleFolderName,
[string] $moduleFolderPath
)
$pipelinesFolderName = Join-Path $repoRootPath '.azuredevops' 'modulePipelines'
$pipelineFileName = Get-PipelineFileName -ResourceIdentifier $moduleFolderName
Write-Verbose "pipelineFileName $pipelineFileName" -Verbose
$pipelinePath = Join-Path $pipelinesFolderName $pipelineFileName
Test-Path $pipelinePath | Should -Be $true -Because "path [$pipelinePath] should exist."
}
It '[<moduleFolderName>] Module pipeline should have trigger for cross-module references, if any.' -TestCases ($moduleFolderTestCases | Where-Object { $_.isTopLevelModule }) {
param(
[string] $moduleFolderName,
[string] $moduleFolderPath,
[Hashtable] $templateReferences
)
$localReferences = $templateReferences.localPathReferences
if (-not $localReferences) {
Set-ItResult -Skipped -Because 'the module has no local cross module references.'
return
}
$pipelinesFolderName = Join-Path $repoRootPath '.azuredevops' 'modulePipelines'
$pipelineFileName = Get-PipelineFileName -ResourceIdentifier $moduleFolderName
$pipelineFilePath = Join-Path $pipelinesFolderName $pipelineFileName
$pipelineContent = Get-Content -Path $pipelineFilePath
# Get paths include start index
$pipelinePathsIncludeIndex = $pipelineContent | ForEach-Object {
if ($_ -match '^\s*paths:\s*$') {
return $pipelineContent.IndexOf($Matches[0]) + 1 # Adding one index to shift to 'include:'
}
}
$pipelinePathsIncludeStartIndex = $pipelinePathsIncludeIndex + 1
# Get paths end index
$pipelinePathsIncludeEndIndex = $pipelinePathsIncludeStartIndex
while ($pipelineContent[($pipelinePathsIncludeEndIndex + 1)] -match "^\s*- '.+$") {
$pipelinePathsIncludeEndIndex++
}
# Extract data
$extractedPaths = $pipelineContent[$pipelinePathsIncludeStartIndex .. $pipelinePathsIncludeEndIndex] | ForEach-Object {
$null = $_ -match "^\s*- '(.+)'$"
$Matches[1]
}
# Re-create result set
$moduleTriggerPaths = $extractedPaths | Where-Object { $_ -match '^\/modules\/.*$' }
$missingCrossModuleReferenceTriggers = [System.Collections.ArrayList] @()
foreach ($localReference in $localReferences) {
$expectedPath = "/modules/$localReference/*"
if ($moduleTriggerPaths -notcontains $expectedPath) {
$missingCrossModuleReferenceTriggers += $expectedPath
}
}
$missingCrossModuleReferenceTriggers.Count | Should -Be 0 -Because ('the list of missing pipeline triggers [{0}] should be empty' -f ($missingCrossModuleReferenceTriggers -join ','))
}
}
}
Describe 'Module tests' -Tag 'Module' {
Context 'Readme content tests' -Tag 'Readme' {
$readmeFileTestCases = [System.Collections.ArrayList] @()
foreach ($moduleFolderPath in $moduleFolderPaths) {
# For runtime purposes, we cache the compiled template in a hashtable that uses a formatted relative module path as a key
$moduleFolderPathKey = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1].Trim('/').Replace('/', '-')
if (-not ($convertedTemplates.Keys -contains $moduleFolderPathKey)) {
if (Test-Path (Join-Path $moduleFolderPath 'main.bicep')) {
$templateFilePath = Join-Path $moduleFolderPath 'main.bicep'
$templateContent = bicep build $templateFilePath --stdout | ConvertFrom-Json -AsHashtable
if (-not $templateContent) {
throw ($bicepTemplateCompilationFailedException -f $templateFilePath)
}
} elseIf (Test-Path (Join-Path $moduleFolderPath 'main.json')) {
$templateFilePath = Join-Path $moduleFolderPath 'main.json'
$templateContent = Get-Content $templateFilePath -Raw | ConvertFrom-Json -AsHashtable
if (-not $templateContent) {
throw ($jsonTemplateLoadFailedException -f $templateFilePath)
}
} else {
throw ($templateNotFoundException -f $moduleFolderPath)
}
$convertedTemplates[$moduleFolderPathKey] = @{
templateFilePath = $templateFilePath
templateContent = $templateContent
}
} else {
$templateContent = $convertedTemplates[$moduleFolderPathKey].templateContent
$templateFilePath = $convertedTemplates[$moduleFolderPathKey].templateFilePath
}
$resourceTypeIdentifier = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
$readmeFileTestCases += @{
moduleFolderName = $resourceTypeIdentifier
moduleFolderPath = $moduleFolderPath
templateContent = $templateContent
templateFilePath = $templateFilePath
readMeFilePath = Join-Path -Path $moduleFolderPath 'README.md'
readMeContent = Get-Content (Join-Path -Path $moduleFolderPath 'README.md')
isTopLevelModule = $resourceTypeIdentifier.Split('/').Count -eq 2 # <provider>/<resourceType>
resourceTypeIdentifier = $resourceTypeIdentifier
templateReferences = $crossReferencedModuleList[$resourceTypeIdentifier]
}
}
It '[<moduleFolderName>] `README.md` file should not be empty.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[object[]] $readMeContent
)
$readMeContent | Should -Not -BeNullOrEmpty
}
It '[<moduleFolderName>] `README.md` file should contain these sections in order: Navigation, Resource Types, Parameters, Outputs, Cross-referenced modules, Deployment examples.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[object[]] $readMeContent,
[boolean] $isTopLevelModule
)
$expectedHeadersInOrder = @('Navigation', 'Resource types', 'Parameters', 'Outputs', 'Cross-referenced modules')
if ($isTopLevelModule) {
# Only top-level modules have parameter files and hence deployment examples
$expectedHeadersInOrder += 'Deployment examples'
}
$actualHeadersInOrder = $readMeContent | Where-Object { $_ -like '#*' } | ForEach-Object { ($_ -replace '#', '').TrimStart() }
$filteredActuals = $actualHeadersInOrder | Where-Object { $expectedHeadersInOrder -contains $_ }
$missingHeaders = $expectedHeadersInOrder | Where-Object { $actualHeadersInOrder -notcontains $_ }
$missingHeaders.Count | Should -Be 0 -Because ('the list of missing headers [{0}] should be empty.' -f ($missingHeaders -join ','))
$filteredActuals | Should -Be $expectedHeadersInOrder -Because 'the headers should exist in the expected order'
}
It '[<moduleFolderName>] Resources section should contain all resources from the template file.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent
)
# Get ReadMe data
$tableStartIndex, $tableEndIndex = Get-TableStartAndEndIndex -ReadMeContent $readMeContent -MarkdownSectionIdentifier '*# Resource Types'
$ReadMeResourcesList = [System.Collections.ArrayList]@()
for ($index = $tableStartIndex + 2; $index -lt $tableEndIndex; $index++) {
$ReadMeResourcesList += $readMeContent[$index].Split('|')[1].Replace('`', '').Trim()
}
# Get template data
$templateResources = (Get-NestedResourceList -TemplateFileContent $templateContent | Where-Object {
$_.type -notin @('Microsoft.Resources/deployments') -and $_ }).type | Select-Object -Unique
# Compare
$differentiatingItems = $templateResources | Where-Object { $ReadMeResourcesList -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ("list of template resources missing from the ReadMe's list [{0}] should be empty" -f ($differentiatingItems -join ','))
}
It '[<moduleFolderName>] Resources section should not contain more resources than the template file.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent
)
# Get ReadMe data
$tableStartIndex, $tableEndIndex = Get-TableStartAndEndIndex -ReadMeContent $readMeContent -MarkdownSectionIdentifier '*# Resource Types'
$ReadMeResourcesList = [System.Collections.ArrayList]@()
for ($index = $tableStartIndex + 2; $index -lt $tableEndIndex; $index++) {
$ReadMeResourcesList += $readMeContent[$index].Split('|')[1].Replace('`', '').Trim()
}
# Get template data
$templateResources = (Get-NestedResourceList -TemplateFileContent $templateContent | Where-Object {
$_.type -notin @('Microsoft.Resources/deployments') -and $_ }).type | Select-Object -Unique
# Compare
$differentiatingItems = $templateResources | Where-Object { $ReadMeResourcesList -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ("list of resources in the ReadMe's list [{0}] not in the template file should be empty" -f ($differentiatingItems -join ','))
}
It '[<moduleFolderName>] Parameters section should contain a table for each existing parameter category in the following order: Required, Conditional, Optional, Generated.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent
)
$expectColumnsInOrder = @('Required', 'Conditional', 'Optional', 'Generated')
## Get all descriptions
$descriptions = $templateContent.parameters.Values.metadata.description
## Get the module parameter categories
$expectedParamCategories = $descriptions | ForEach-Object { $_.Split('.')[0] } | Select-Object -Unique # Get categories in template
$expectedParamCategoriesInOrder = $expectColumnsInOrder | Where-Object { $_ -in $expectedParamCategories } # add required ones in order
$expectedParamCategoriesInOrder += $expectedParamCategories | Where-Object { $_ -notin $expectColumnsInOrder } # add non-required ones after
$actualParamCategories = $readMeContent | Select-String -Pattern '^\*\*(.+) parameters\*\*$' -AllMatches | ForEach-Object { $_.Matches.Groups[1].Value } # get actual in readme
$actualParamCategories | Should -Be $expectedParamCategoriesInOrder
}
It '[<moduleFolderName>] Parameter tables should provide columns in the following order: Parameter Name, Type, Default Value, Allowed Values, Description. Each column should be present unless empty for all the rows.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent
)
## Get all descriptions
$descriptions = $templateContent.parameters.Values.metadata.description
## Get the module parameter categories
$paramCategories = $descriptions | ForEach-Object { $_.Split('.')[0] } | Select-Object -Unique
foreach ($paramCategory in $paramCategories) {
# Filter to relevant items
[array] $categoryParameters = $templateContent.parameters.Values | Where-Object { $_.metadata.description -like "$paramCategory. *" } | Sort-Object -Property 'Name' -Culture 'en-US'
# Check properties for later reference
$shouldHaveDefault = $categoryParameters.defaultValue.count -gt 0
$shouldHaveAllowed = $categoryParameters.allowedValues.count -gt 0
$expectedColumnsInOrder = @('Parameter Name', 'Type')
if ($shouldHaveDefault) { $expectedColumnsInOrder += @('Default Value') }
if ($shouldHaveAllowed) { $expectedColumnsInOrder += @('Allowed Values') }
$expectedColumnsInOrder += @('Description')
$readMeCategoryIndex = $readMeContent | Select-String -Pattern "^\*\*$paramCategory parameters\*\*$" | ForEach-Object { $_.LineNumber }
$tableStartIndex = $readMeCategoryIndex
while ($readMeContent[$tableStartIndex] -notlike '*|*' -and -not ($tableStartIndex -ge $readMeContent.count)) {
$tableStartIndex++
}
$readmeCategoryColumns = ($readMeContent[$tableStartIndex] -split '\|') | ForEach-Object { $_.Trim() } | Where-Object { -not [String]::IsNullOrEmpty($_) }
$readmeCategoryColumns | Should -Be $expectedColumnsInOrder
}
}
It '[<moduleFolderName>] Parameters section should contain all parameters from the template file.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent
)
# Get Template data
$parameters = $templateContent.parameters.Keys
# Get ReadMe data
## Get section start index
$sectionStartIndex = Get-MarkdownSectionStartIndex -ReadMeContent $readMeContent -MarkdownSectionIdentifier '*# Parameters'
if ($sectionStartIndex -ge $readMeContent.count) {
throw 'Parameters section is missing in the Readme. Please add and re-run the tests.'
}
$parametersSectionEndIndex = Get-MarkdownSectionEndIndex -ReadMeContent $readMeContent -SectionStartIndex $sectionStartIndex
## Iterate over all parameter tables
$parametersList = [System.Collections.ArrayList]@()
$sectionIndex = $sectionStartIndex
while ($sectionIndex -lt $parametersSectionEndIndex) {
### Get table start index
$parametersTableStartIndex = $sectionIndex
while ($readMeContent[$parametersTableStartIndex] -notlike '*|*' -and -not ($parametersTableStartIndex -ge $readMeContent.count)) {
$parametersTableStartIndex++
}
Write-Verbose ("[loop] Start row of the parameter table: $parametersTableStartIndex")
### Get table end index
$parametersTableEndIndex = $parametersTableStartIndex + 2 # Header row + table separator row
while ($readMeContent[$parametersTableEndIndex] -like '*|*' -and -not ($parametersTableEndIndex -ge $readMeContent.count)) {
$parametersTableEndIndex++
}
Write-Verbose ("[loop] End row of the parameter table: $parametersTableEndIndex")
for ($tableIndex = $parametersTableStartIndex + 2; $tableIndex -lt $parametersTableEndIndex; $tableIndex++) {
$parametersList += $readMeContent[$tableIndex].Split('|')[1].Replace('`', '').Trim()
}
$sectionIndex = $parametersTableEndIndex + 1
}
# Test
$differentiatingItems = $parameters | Where-Object { $parametersList -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of template parameters missing in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
}
It '[<moduleFolderName>] Outputs section should contain a table with these column names in order: Output Name, Type.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
$readMeContent
)
$tableStartIndex, $tableEndIndex = Get-TableStartAndEndIndex -ReadMeContent $readMeContent -MarkdownSectionIdentifier '*# Outputs'
$outputsTableHeader = $readMeContent[$tableStartIndex].Split('|').Trim() | Where-Object { -not [String]::IsNullOrEmpty($_) }
# Test
$expectedOutputsTableOrder = @('Output Name', 'Type')
$differentiatingItems = $expectedOutputsTableOrder | Where-Object { $outputsTableHeader -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of "Outputs" table columns missing in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
}
It '[<moduleFolderName>] Output section should contain all outputs defined in the template file.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent
)
# Get ReadMe data
$tableStartIndex, $tableEndIndex = Get-TableStartAndEndIndex -ReadMeContent $readMeContent -MarkdownSectionIdentifier '*# Outputs'
$ReadMeOutputsList = [System.Collections.ArrayList]@()
for ($index = $tableStartIndex + 2; $index -lt $tableEndIndex; $index++) {
$ReadMeOutputsList += $readMeContent[$index].Split('|')[1].Replace('`', '').Trim()
}
# Template data
$expectedOutputs = $templateContent.outputs.Keys
# Test
$differentiatingItems = $expectedOutputs | Where-Object { $ReadMeOutputsList -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of template outputs missing in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
$differentiatingItems = $ReadMeOutputsList | Where-Object { $expectedOutputs -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of excess template outputs defined in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
}
It '[<moduleFolderName>] Dependencies section should contain all cross-references defined in the template file.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent,
[object[]] $readMeContent,
[string] $resourceTypeIdentifier,
[hashtable] $templateReferences
)
# Get ReadMe data
$tableStartIndex, $tableEndIndex = Get-TableStartAndEndIndex -ReadMeContent $readMeContent -MarkdownSectionIdentifier '*## Cross-referenced modules'
$ReadMeDependenciesList = @{
localPathReferences = @()
remoteReferences = @()
}
for ($index = $tableStartIndex + 2; $index -lt $tableEndIndex; $index++) {
$type = $readMeContent[$index].Split('|')[2].Trim()
switch ($type) {
'Local reference' {
$ReadMeDependenciesList.localPathReferences += $readMeContent[$index].Split('|')[1].Replace('`', '').Trim()
}
'Remote reference' {
$ReadMeDependenciesList.remoteReferences += $readMeContent[$index].Split('|')[1].Replace('`', '').Trim()
}
Default {
throw "Unkown type reference [$type]. Only [Local reference] & [Remote reference] are known. Please update ReadMe or test script."
}
}
}
# Test
if ($templateReferences.localPathReferences) {
$differentiatingItems = @() + $templateReferences.localPathReferences | Where-Object { $ReadMeDependenciesList.localPathReferences -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of local template dependencies missing in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
$differentiatingItems = @() + $ReadMeDependenciesList.localPathReferences | Where-Object { $templateReferences.localPathReferences -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of excess local template references defined in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
}
if ($templateReferences.remoteReferences) {
$differentiatingItems = @() + $templateReferences.remoteReferences | Where-Object { $ReadMeDependenciesList.remoteReferences -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of remote template dependencies missing in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
$differentiatingItems = @() + $ReadMeDependenciesList.remoteReferences | Where-Object { $templateReferences.remoteReferences -notcontains $_ }
$differentiatingItems.Count | Should -Be 0 -Because ('list of excess remote template references defined in the ReadMe file [{0}] should be empty.' -f ($differentiatingItems -join ','))
}
}
It '[<moduleFolderName>] `Set-ModuleReadMe` script should not apply any updates.' -TestCases $readmeFileTestCases {
param(
[string] $moduleFolderName,
[string] $templateFilePath,
[hashtable] $templateContent,
[string] $readMeFilePath
)
# Get current hash
$fileHashBefore = (Get-FileHash $readMeFilePath).Hash
# Load function
. (Join-Path $repoRootPath 'utilities' 'tools' 'Set-ModuleReadMe.ps1')
# Apply update with already compiled template content
Set-ModuleReadMe -TemplateFilePath $templateFilePath -TemplateFileContent $templateContent
# Get hash after 'update'
$fileHashAfter = (Get-FileHash $readMeFilePath).Hash
# Compare
$filesAreTheSame = $fileHashBefore -eq $fileHashAfter
if (-not $filesAreTheSame) {
$diffReponse = git diff $readMeFilePath
Write-Warning ($diffReponse | Out-String) -Verbose
# Reset readme file to original state
git checkout HEAD -- $readMeFilePath
}
$mdFormattedDiff = ($diffReponse -join '</br>') -replace '\|', '\|'
$filesAreTheSame | Should -Be $true -Because ('The file hashes before and after applying the `Set-ModuleReadMe` function should be identical and should not have diff </br><pre>{0}</pre>. Please re-run the script for this module''s template.' -f $mdFormattedDiff)
}
}
Context 'Compiled ARM template tests' -Tag 'ARM' {
$armTemplateTestCases = [System.Collections.ArrayList] @()
foreach ($moduleFolderPath in $moduleFolderPaths) {
# Skipping folders without a [main.bicep] template
$templateFilePath = Join-Path $moduleFolderPath 'main.bicep'
if (-not (Test-Path $templateFilePath)) {
continue
}
$resourceTypeIdentifier = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
$armTemplateTestCases += @{
moduleFolderName = $resourceTypeIdentifier
moduleFolderPath = $moduleFolderPath
templateFilePath = $templateFilePath
}
}
It '[<moduleFolderName>] Compiled ARM template should be latest.' -TestCases $armTemplateTestCases {
param(
[string] $moduleFolderName,
[string] $moduleFolderPath,
[string] $templateFilePath
)
$armTemplatePath = Join-Path $moduleFolderPath 'main.json'
# Current json
if (-not (Test-Path $armTemplatePath)) {
throw "[main.json] file for module [$moduleFolderName] is missing."
}
$originalJson = Remove-JSONMetadata -TemplateObject (Get-Content $armTemplatePath -Raw | ConvertFrom-Json -Depth 99 -AsHashtable)
$originalJson = ConvertTo-OrderedHashtable -JSONInputObject (ConvertTo-Json $originalJson -Depth 99)
# Recompile json
$null = Remove-Item -Path $armTemplatePath -Force
bicep build $templateFilePath
$newJson = Remove-JSONMetadata -TemplateObject (Get-Content $armTemplatePath -Raw | ConvertFrom-Json -Depth 99 -AsHashtable)
$newJson = ConvertTo-OrderedHashtable -JSONInputObject (ConvertTo-Json $newJson -Depth 99)
# compare
(ConvertTo-Json $originalJson -Depth 99) | Should -Be (ConvertTo-Json $newJson -Depth 99) -Because "the [$moduleFolderName] [main.json] should be based on the latest [main.bicep] file. Please run [` bicep build >bicepFilePath< `] using the latest Bicep CLI version."
# Reset template file to original state
git checkout HEAD -- $armTemplatePath
}
}
Context 'General template tests' -Tag 'Template' {
$deploymentFolderTestCases = [System.Collections.ArrayList] @()
foreach ($moduleFolderPath in $moduleFolderPaths) {
# For runtime purposes, we cache the compiled template in a hashtable that uses a formatted relative module path as a key
$moduleFolderPathKey = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1].Trim('/').Replace('/', '-')
if (-not ($convertedTemplates.Keys -contains $moduleFolderPathKey)) {
if (Test-Path (Join-Path $moduleFolderPath 'main.bicep')) {
$templateFilePath = Join-Path $moduleFolderPath 'main.bicep'
$templateContent = bicep build $templateFilePath --stdout | ConvertFrom-Json -AsHashtable
if (-not $templateContent) {
throw ($bicepTemplateCompilationFailedException -f $templateFilePath)
}
} elseIf (Test-Path (Join-Path $moduleFolderPath 'main.json')) {
$templateFilePath = Join-Path $moduleFolderPath 'main.json'
$templateContent = Get-Content $templateFilePath -Raw | ConvertFrom-Json -AsHashtable
if (-not $templateContent) {
throw ($jsonTemplateLoadFailedException -f $templateFilePath)
}
} else {
throw ($templateNotFoundException -f $moduleFolderPath)
}
$convertedTemplates[$moduleFolderPathKey] = @{
templateFilePath = $templateFilePath
templateContent = $templateContent
}
} else {
$templateContent = $convertedTemplates[$moduleFolderPathKey].templateContent
$templateFilePath = $convertedTemplates[$moduleFolderPathKey].templateFilePath
}
# Parameter file test cases
$testFileTestCases = @()
$templateFile_Parameters = $templateContent.parameters
$TemplateFile_AllParameterNames = $templateFile_Parameters.Keys | Sort-Object
$TemplateFile_RequiredParametersNames = ($templateFile_Parameters.Keys | Where-Object { -not $templateFile_Parameters[$_].ContainsKey('defaultValue') }) | Sort-Object
if (Test-Path (Join-Path $moduleFolderPath '.test')) {
# Can be removed after full migration to bicep test files
$moduleTestFilePaths = Get-ModuleTestFileList -ModulePath $moduleFolderPath | ForEach-Object { Join-Path $moduleFolderPath $_ }
foreach ($moduleTestFilePath in $moduleTestFilePaths) {
if ((Split-Path $moduleTestFilePath -Extension) -eq '.json') {
$rawContentHashtable = (Get-Content $moduleTestFilePath) | ConvertFrom-Json -AsHashtable
# Skipping any file that is not actually a ARM-JSON parameter file
$isParameterFile = $rawContentHashtable.'$schema' -like '*deploymentParameters*'
if (-not $isParameterFile) {
continue
}
$deploymentTestFile_AllParameterNames = $rawContentHashtable.parameters.Keys | Sort-Object
} else {
$deploymentFileContent = bicep build $moduleTestFilePath --stdout | ConvertFrom-Json -AsHashtable
$deploymentTestFile_AllParameterNames = $deploymentFileContent.resources[-1].properties.parameters.Keys | Sort-Object # The last resource should be the test
}
$testFileTestCases += @{
testFile_Path = $moduleTestFilePath
testFile_Name = Split-Path $moduleTestFilePath -Leaf
testFile_AllParameterNames = $deploymentTestFile_AllParameterNames
templateFile_AllParameterNames = $TemplateFile_AllParameterNames
templateFile_RequiredParametersNames = $TemplateFile_RequiredParametersNames
tokenConfiguration = $tokenConfiguration
}
}
}
# Test file setup
$deploymentFolderTestCases += @{
moduleFolderName = $moduleFolderPath.Replace('\', '/').Split('/modules/')[1]
templateContent = $templateContent
templateFilePath = $templateFilePath
testFileTestCases = $testFileTestCases
}
}
It '[<moduleFolderName>] The template file should not be empty.' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$templateContent | Should -Not -BeNullOrEmpty
}
It '[<moduleFolderName>] Template schema version should be the latest.' -TestCases $deploymentFolderTestCases {
# the actual value changes depending on the scope of the template (RG, subscription, MG, tenant) !!
# https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-syntax
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$Schemaverion = $templateContent.'$schema'
$SchemaArray = @()
if ($Schemaverion -eq $RGdeployment) {
$SchemaOutput = $true
} elseIf ($Schemaverion -eq $Subscriptiondeployment) {
$SchemaOutput = $true
} elseIf ($Schemaverion -eq $MGdeployment) {
$SchemaOutput = $true
} elseIf ($Schemaverion -eq $Tenantdeployment) {
$SchemaOutput = $true
} else {
$SchemaOutput = $false
}
$SchemaArray += $SchemaOutput
$SchemaArray | Should -Not -Contain $false
}
It '[<moduleFolderName>] Template schema should use HTTPS reference.' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$Schemaverion = $templateContent.'$schema'
($Schemaverion.Substring(0, 5) -eq 'https') | Should -Be $true
}
It '[<moduleFolderName>] All apiVersion properties should be set to a static, hard-coded value.' -TestCases $deploymentFolderTestCases {
#https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-best-practices
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$ApiVersion = $templateContent.resources.apiVersion
$ApiVersionArray = @()
foreach ($API in $ApiVersion) {
if ($API.Substring(0, 2) -eq '20') {
$ApiVersionOutput = $true
} elseIf ($API.substring(1, 10) -eq 'parameters') {
# An API version should not be referenced as a parameter
$ApiVersionOutput = $false
} elseIf ($API.substring(1, 10) -eq 'variables') {
# An API version should not be referenced as a variable
$ApiVersionOutput = $false
} else {
$ApiVersionOutput = $false
}
$ApiVersionArray += $ApiVersionOutput
}
$ApiVersionArray | Should -Not -Contain $false
}
It '[<moduleFolderName>] The template file should contain required elements [schema], [contentVersion], [resources].' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$templateContent.Keys | Should -Contain '$schema'
$templateContent.Keys | Should -Contain 'contentVersion'
$templateContent.Keys | Should -Contain 'resources'
}
It '[<moduleFolderName>] If delete lock is implemented, the template should have a lock parameter with an empty default value.' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
if ($lock = $templateContent.parameters.lock) {
$lock.Keys | Should -Contain 'defaultValue'
$lock.defaultValue | Should -Be ''
}
}
It '[<moduleFolderName>] Parameter names should be camel-cased (no dashes or underscores and must start with lower-case letter).' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
if (-not $templateContent.parameters) {
Set-ItResult -Skipped -Because 'the module template has no parameters.'
return
}
$CamelCasingFlag = @()
$Parameter = $templateContent.parameters.Keys
foreach ($Param in $Parameter) {
if ($Param.substring(0, 1) -cnotmatch '[a-z]' -or $Param -match '-' -or $Param -match '_') {
$CamelCasingFlag += $false
} else {
$CamelCasingFlag += $true
}
}
$CamelCasingFlag | Should -Not -Contain $false
}
It '[<moduleFolderName>] Variable names should be camel-cased (no dashes or underscores and must start with lower-case letter).' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
if (-not $templateContent.variables) {
Set-ItResult -Skipped -Because 'the module template has no variables.'
return
}
$CamelCasingFlag = @()
$Variable = $templateContent.variables.Keys
foreach ($Variab in $Variable) {
if ($Variab.substring(0, 1) -cnotmatch '[a-z]' -or $Variab -match '-') {
$CamelCasingFlag += $false
} else {
$CamelCasingFlag += $true
}
}
$CamelCasingFlag | Should -Not -Contain $false
}
It '[<moduleFolderName>] Output names should be camel-cased (no dashes or underscores and must start with lower-case letter).' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$CamelCasingFlag = @()
$Outputs = $templateContent.outputs.Keys
foreach ($Output in $Outputs) {
if ($Output.substring(0, 1) -cnotmatch '[a-z]' -or $Output -match '-' -or $Output -match '_') {
$CamelCasingFlag += $false
} else {
$CamelCasingFlag += $true
}
}
$CamelCasingFlag | Should -Not -Contain $false
}
It '[<moduleFolderName>] CUA ID deployment should be present in the template.' -TestCases $deploymentFolderTestCases {
param(
[string] $moduleFolderName,
[hashtable] $templateContent
)
$enableDefaultTelemetryFlag = @()
$Schemaverion = $templateContent.'$schema'
if ((($Schemaverion.Split('/')[5]).Split('.')[0]) -eq (($RGdeployment.Split('/')[5]).Split('.')[0])) {
if (($templateContent.resources.type -ccontains 'Microsoft.Resources/deployments' -and $templateContent.resources.condition -like "*[parameters('enableDefaultTelemetry')]*") -or ($templateContent.resources.resources.type -ccontains 'Microsoft.Resources/deployments' -and $templateContent.resources.resources.condition -like "*[parameters('enableDefaultTelemetry')]*")) {
$enableDefaultTelemetryFlag += $true
} else {
$enableDefaultTelemetryFlag += $false
}
}
$enableDefaultTelemetryFlag | Should -Not -Contain $false
}