forked from MethodsAndPractices/vsteam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRun-ContainerTests.ps1
355 lines (289 loc) · 10.6 KB
/
Run-ContainerTests.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
347
348
349
350
351
352
353
354
355
[CmdletBinding()]
param (
# if you want to make sure that only Linux based containers are used, since Windows based containers are not supported on your OS
[Parameter(Mandatory = $false)]
[switch]
$UseLinux,
# Open another PowerShell session to show the logs from the container
[Switch]
$ShowLogs
)
function Find-Numbers {
[CmdletBinding()]
param (
[string] $fileToRead
)
process {
$passed = 0
$failed = 0
$skipped = 0
$not_run = 0
if (Test-Path $fileToRead) {
$a = Get-Content $fileToRead
$myMatches = $a | Select-string "total=""([0-9]+)"""
$passed = $myMatches.Matches[0].Groups[1].Value -as [int]
$myMatches = $a | Select-string 'failures="([0-9]+)"'
$failed = $myMatches.Matches[0].Groups[1].Value -as [int]
$myMatches = $a | Select-string 'skipped="([0-9]+)"'
$skipped = $myMatches.Matches[0].Groups[1].Value -as [int]
$myMatches = $a | Select-string 'not-run="([0-9]+)"'
$not_run = $myMatches.Matches[0].Groups[1].Value -as [int]
}
Write-Output @{
Passed = $passed
Failed = $failed
Skipped = $skipped
NotRun = $not_run
}
}
}
function Set-DockerHost {
<#
.SYNOPSIS
Switch between Windows and Linux containers. IMPORTANT: Works only for Windows based systems
#>
[CmdletBinding()]
param (
#sets the container OS
[Parameter(Mandatory = $true)]
[ValidateSet("Windows", "Linux")]
[string]
$Os
)
process {
$dockerVersion = docker version --format '{{json .}}' | ConvertFrom-Json
if ($dockerVersion.Server.Os -ne $Os ) {
& "$env:ProgramFiles\Docker\Docker\DockerCli.exe" -SwitchDaemon
}
else {
Write-Verbose "docker host is already set to $Os... ignoring command"
}
}
}
function Add-DockerBuild {
<#
.SYNOPSIS
Create a docker build with a tag. Optionally force to rebuild the container.
#>
[CmdletBinding()]
param (
# Path to the dockerfile
[Parameter(Mandatory = $true)]
[string]
$DockerFile,
# give it a named tag. Best with repository and image name
[Parameter(Mandatory = $true)]
[string]
$Tag,
# Force the rebuild of the container
[Switch]
$Force
)
process {
$dockerImageId = docker images -q $Tag
# only build if image does not exist or it's forced
# when not using force: It can't be checked if a docker file has is different from the existing image
if ($null -eq $dockerImageId -or $Force) {
docker build --file $DockerFile --tag $Tag .
}
else {
Write-Verbose "image $Tag already exists with id $dockerImageId"
}
}
}
function Start-DockerVSTeamTests {
[CmdletBinding()]
param (
# Name of the container to run
[Parameter(Mandatory = $true)]
[string]
$Container,
# volume mapping string
# see: https://docs.docker.com/storage/volumes/#start-a-container-with-a-volume
[Parameter(Mandatory = $true)]
[string]
$Volume,
# default directoy when the container is started
[Parameter(Mandatory = $true)]
[string]
$DefaultWorkDir,
# Image to start
[Parameter(Mandatory = $true)]
[string]
$Image,
# choose which shell to start
[Parameter(Mandatory = $false)]
[ValidateSet("pwsh", "powershell")]
[string]
$Shell = "pwsh",
# Use if powershell should wait for the container to exit
[Parameter(Mandatory = $false)]
[Switch]
$Wait,
# Open another powershell session to show the logs from the container
[Parameter(Mandatory = $false)]
[Switch]
$FollowLogs
)
begin {
# using a script block here to have syntax checking and highlightning.
# Later it is converted to a string to start the container with it
$pesterBuild = {
Write-Verbose 'Deleting old results'
# I delete from the container so that all the correct permissions
# are granted to delete. When I tried this from outside the container
# I did not have permissions to delete it.
if (Test-Path './Tests/TestResults/#Container#_result.xml') {
Write-Verbose 'Deleting old results file ./Tests/TestResults/#Container#_result.xml'
Remove-Item './Tests/TestResults/#Container#_result.xml'
}
.\Build-Module.ps1 -installDep -skipLibBuild
$null = Import-Module Pester
$pesterArgs = [PesterConfiguration]::Default
$pesterArgs.Run.Exit = $true
$pesterArgs.Run.Path = './Tests/function'
$pesterArgs.Run.PassThru = $false
$pesterArgs.TestResult.Enabled = $true
$pesterArgs.TestResult.OutputPath = './Tests/TestResults/#Container#_result.xml'
Invoke-Pester -Configuration $pesterArgs
# exist with PowerShells last exist code for docker.
# without deliverate exit code the -Wait switch could cause to wait indefinetely
Exit $LASTEXITCODE
}
}
process {
$containerId = docker ps --all --filter name=$Container -q
$containerIsRunning = $null -ne (docker ps --filter name=$Container -q)
if ($containerIsRunning) {
docker stop $containerId
}
if ($containerId) {
docker rm $Container
}
$psCommandString = ($pesterBuild.ToString()) -replace '#Container#', $Container
docker run `
-dit `
--name $Container `
--volume $Volume `
-w $DefaultWorkDir `
$Image `
$Shell -Command $psCommandString
if ($FollowLogs) {
$output = (docker exec -it $Container $Shell -c '$PSVersionTable | ConvertTo-Json -Compress') -join ''
$outputFirst = $output.IndexOf('{')
$ouputLast = $output.LastIndexOf('}')
$versiontable = $output.Substring($outputFirst, $ouputLast + 1 - $outputFirst) | ConvertFrom-Json
$psVersion = "$($versiontable.PSVersion.Major).$($versiontable.PSVersion.Minor).$($versiontable.PSVersion.Patch)"
# On Linux the logs show up in the same PowerShell window so we need it to exit
# On Windows new windows are opened and you want -NoExit so they stay open for you to
# review the logs.
$os = Get-OperatingSystem
if ($os -ne 'Windows') {
$argList = "-Command `"`$Host.UI.RawUI.WindowTitle = 'VSTeam Unit Tests | PowerShell $($versiontable.PSEdition) $psVersion | $($versiontable.Os)'; docker logs $Container -f`""
}
else {
$argList = "-NoExit -Command `"`$Host.UI.RawUI.WindowTitle = 'VSTeam Unit Tests | PowerShell $($versiontable.PSEdition) $psVersion | $($versiontable.Os)'; docker logs $Container -f`""
}
Start-Process $Shell -argumentlist $argList
}
if ($Wait) {
docker wait $Container
}
}
}
function Wait-DockerContainer {
<#
.SYNOPSIS
Wait for the given containers to finish. If they don't run, then error is thrown
#>
[CmdletBinding()]
param (
# Containers to wait for
[Parameter(Mandatory = $true)]
[string[]]
$Container
)
process {
$exitCodes = @()
$runningContainers = docker ps --format '{{json .}}' | ConvertFrom-Json
$notRunningContainers = @()
$notAllContainersRunning = $Container.Count -ne ($Container | Where-Object {
$contains = $runningContainers.Names.Contains($_)
if ($contains) {
return $true
}
else {
$notRunningContainers += $_
return $false
}
}).Count
if ($notAllContainersRunning) {
Write-Error "Contains with the following names are not running: $($notRunningContainers -join ', ')"
}
else {
$Container | ForEach-Object {
$exitCode = docker wait $_
$exitCodes += @{
containerName = $_
exitCode = $exitCode
}
}
}
return $exitCodes
}
}
$platform = Get-OperatingSystem
$scriptPath = $PSScriptRoot
$rootDir = (Resolve-Path -Path "$scriptPath\..\..\").ToString().trim('\')
$containerFolder = "c:/vsteam"
$containerFilePath = "$rootDir/tools/docker"
Write-Verbose "Root Dir: $rootDir"
$dockerRepository = "vsteam"
$WindowsImage = "$dockerRepository/wcore1903"
$WindowsContainerPS7 = "$($dockerRepository)_wcore1903_ps7_tests"
$WindowsContainerPS5 = "$($dockerRepository)_wcore1903_ps5_tests"
# Build / run Windows based container
if ($platform -eq "Windows" -and !$UseLinux) {
Set-DockerHost -Os Windows
Add-DockerBuild -DockerFile "$containerFilePath/wcore1903/Dockerfile" -Tag $WindowsImage
Write-Output 'Starting PowerShell 7 tests on Windows'
$null = Start-DockerVSTeamTests `
-Container $WindowsContainerPS7 `
-Volume "$rootDir`:$containerFolder" `
-DefaultWorkDir $containerFolder `
-Image $WindowsImage `
-FollowLogs:$ShowLogs
Write-Output 'Starting PowerShell 5 tests on Windows'
$null = Start-DockerVSTeamTests `
-Container $WindowsContainerPS5 `
-Volume "$rootDir`:$containerFolder" `
-DefaultWorkDir $containerFolder `
-Image $WindowsImage `
-Shell powershell `
-FollowLogs:$ShowLogs
$null = Wait-DockerContainer -Container @($WindowsContainerPS5, $WindowsContainerPS7)
}
$LinuxImage = "$dockerRepository/linux"
$LinuxContainer = "$($dockerRepository)_Linux_ps7_tests"
$LinuxContainerFolder = $containerFolder.Replace('c:/', '/c/')
# Build / run Linux based container
if ($platform -eq "Windows") {
Set-DockerHost -Os Linux
}
Add-DockerBuild -DockerFile "$containerFilePath/linux/Dockerfile" -Tag $LinuxImage
Write-Output 'Starting PowerShell 7 tests on Linux'
$null = Start-DockerVSTeamTests `
-Container $LinuxContainer `
-Volume "$rootDir`:$LinuxContainerFolder" `
-DefaultWorkDir $LinuxContainerFolder `
-Image $LinuxImage `
-Wait `
-FollowLogs:$ShowLogs
$linux = Find-Numbers -fileToRead "$rootDir/Tests/TestResults/vsteam_Linux_ps7_tests_result.xml"
$winP5 = Find-Numbers -fileToRead "$rootDir/Tests/TestResults/vsteam_wcore1903_ps5_tests_result.xml"
$winP7 = Find-Numbers -fileToRead "$rootDir/Tests/TestResults/vsteam_wcore1903_ps7_tests_result.xml"
$totalPassed = $winP5.Passed + $linux.Passed + $winP7.Passed
$totalFailed = $winP5.Failed + $linux.Failed + $winP7.Failed
$totalNotRun = $winP5.NotRun + $linux.NotRun + $winP7.NotRun
$totalSkipped = $winP5.Skipped + $linux.Skipped + $winP7.Skipped
Write-Host "Tests Passed: $totalPassed, Failed: $totalFailed, Skipped: $totalSkipped, NotRun: $totalNotRun"