Repository navigation
Expand file tree
/
Copy pathrun-dotnet-tests.ps1
More file actions
512 lines (458 loc) · 22.2 KB
/
Copy pathrun-dotnet-tests.ps1
File metadata and controls
512 lines (458 loc) · 22.2 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
<#
.SYNOPSIS
Builds and runs a batch of test projects for one CI profile.
.DESCRIPTION
Shared by .github/workflows/buildandtest.yml and .github/workflows/nightly.yml
through the .github/actions/run-dotnet-tests composite action. One matrix
entry carries several projects, so this script keeps per-project results: it
decides applicability, builds, tests, evaluates the emitted TRX and reports a
row per project.
Applicability is decided by evaluating the project rather than by guessing
from its path. Directory.Build.targets turns a project that opts into
RestrictForLegacyTfm into an empty no-op shell on the legacy profiles, and
marks the shell 'IsTestProject=false'. A shell is recorded as not applicable
with its reason - it is explicitly not counted as a passing test run.
A project that is applicable must produce a TRX recording at least one
executed test. A run that emits nothing, or emits a TRX with no results, is a
broken discovery rather than a pass, and fails here.
The recorded results decide the verdict, not the 'dotnet test' exit code. A
non-zero exit is tolerated when - and only when - the TRX records at least
one test and no failure, error, timeout, abort or passedButRunAborted: that
combination means the host died during process exit, after the last test and
every teardown had already run. It was originally assumed to be a macOS-only
quirk, but Windows hosts do it too (observed on run 35714133848, job
'test-windows-net48 (5/30)', where Opc.Ua.Client.Tests reported 256 passed
and 0 failed and the host still exited 1). A host that dies mid-run is not
tolerated - that leaves a non-zero counter, which fails above.
.PARAMETER Projects
Semicolon-separated, repository-relative project paths to run in order.
.PARAMETER CustomTestTarget
The value passed as /p:CustomTestTarget for build and test. This, not
'--framework', is what pins the whole stack to a single target framework
(see targets.props).
.PARAMETER Framework
The target framework the tests actually execute on.
.PARAMETER Configuration
Debug or Release.
.PARAMETER Filter
NUnit category filter. Empty runs every category, which is what the
long-running and durable tiers do.
.PARAMETER HangTimeout
--blame-hang-timeout for a single test.
.PARAMETER PerProjectTimeoutMinutes
Wall-clock ceiling for one project's test invocation. The blame collector
only reacts to inactivity inside the test host and can itself fail to
unwind, so this is the backstop that turns a stuck run into a named
per-project failure instead of an unexplained job timeout.
Builds are bounded by the enclosing GitHub job timeout, which includes a
fixed setup/build allowance in addition to one test ceiling per project.
.PARAMETER ResultsDirectory
Directory that receives one subdirectory of results per project, plus the
machine-readable batch summary.
.PARAMETER Coverage
Collect Cobertura coverage. Never set for a .NET Framework test host:
coverlet.collector ships build assets for net8.0 and newer only, so the
collector cannot load there and VSTest would only warn.
.PARAMETER QuietOutput
Write each project's build and test output to a log file under the results
directory instead of the console. Use it for inputs that must not reach a
world-readable job log: a failing fuzz test prints a base64 reproducer, so
a replay of unpublished crash inputs has to keep its output in the results
tree.
#>
Param(
[Parameter(Mandatory = $true)]
[string] $Projects,
[Parameter(Mandatory = $true)]
[string] $CustomTestTarget,
[Parameter(Mandatory = $true)]
[string] $Framework,
[Parameter(Mandatory = $true)]
[string] $Configuration,
[string] $Filter = '',
[string] $HangTimeout = '10m',
[int] $PerProjectTimeoutMinutes = 30,
[Parameter(Mandatory = $true)]
[string] $ResultsDirectory,
[switch] $Coverage,
[switch] $QuietOutput
)
$ErrorActionPreference = 'Stop'
# The verdict rule and the TRX parsing it consumes live in their own file so they
# can be tested without building or running anything - see
# tests/Opc.Ua.Tools.Tests/CiTestVerdictTests.cs.
. (Join-Path $PSScriptRoot 'get-test-verdict.ps1')
$projectList = @($Projects -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
if ($projectList.Count -eq 0) {
throw 'No projects were supplied. An entry that runs nothing would report success without testing anything.'
}
$null = New-Item -ItemType Directory -Path $ResultsDirectory -Force
$resultsRoot = (Resolve-Path -LiteralPath $ResultsDirectory).Path
function New-DotnetStartInfo(
[string[]] $arguments,
[bool] $linux,
[string] $nativeLibraryDirectory = '')
{
$startInfo = [System.Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = 'dotnet'
if ($linux -and $arguments.Count -ge 2 -and $arguments[0] -eq 'test' -and
[System.IO.Path]::GetFileName($arguments[1]) -in @(
'Opc.Ua.Lens.Workflow.Tests.csproj', 'Opc.Ua.Lens.Desktop.Tests.csproj')) {
$xvfb = Get-Command xvfb-run -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($null -eq $xvfb) {
throw 'UaLens desktop tests require xvfb-run on the Linux agent.'
}
$startInfo.FileName = $xvfb.Source
$startInfo.ArgumentList.Add('-a')
$startInfo.ArgumentList.Add('dotnet')
}
if ($linux -and $arguments[0] -eq 'test' -and
-not [string]::IsNullOrWhiteSpace($nativeLibraryDirectory)) {
$directories = @(
$nativeLibraryDirectory,
[System.IO.Path]::Combine($nativeLibraryDirectory, 'runtimes', 'linux-x64', 'native'))
if ($startInfo.Environment['LD_LIBRARY_PATH']) {
$directories += $startInfo.Environment['LD_LIBRARY_PATH']
}
$startInfo.Environment['LD_LIBRARY_PATH'] = $directories -join ':'
}
foreach ($argument in $arguments) {
$startInfo.ArgumentList.Add($argument)
}
$startInfo.UseShellExecute = $false
return $startInfo
}
<#
.SYNOPSIS
Runs 'dotnet' with the supplied arguments, streaming its output to the log
and killing the process tree if the project's remaining budget runs out.
.DESCRIPTION
System.Diagnostics.Process is used instead of the call operator so the child
can be killed on timeout, and instead of Start-Process so the arguments -
which include filter expressions containing '&' and '!' - are passed through
verbatim rather than re-parsed by a shell.
A stopwatch is supplied for test invocations so build time does not consume
the test execution budget. Builds rely on the enclosing GitHub job timeout,
which budgets fixed setup/build overhead plus each project's test ceiling.
#>
function Invoke-Dotnet(
[string[]] $arguments,
[System.Diagnostics.Stopwatch] $budget,
[int] $budgetMinutes,
[string] $logPath,
[string] $nativeLibraryDirectory = '')
{
Write-Host "dotnet $($arguments -join ' ')"
$remainingMs = [long]::MaxValue
if ($null -ne $budget) {
$remainingMs = ([long]$budgetMinutes * 60 * 1000) - $budget.ElapsedMilliseconds
if ($remainingMs -le 0) {
Write-Host ("::error title=CI test runner::The $budgetMinutes-minute per-project ceiling was " +
"already spent before 'dotnet $($arguments[0])' could start.")
return [pscustomobject]@{ ExitCode = -1; TimedOut = $true }
}
}
$startInfo = New-DotnetStartInfo $arguments $IsLinux $nativeLibraryDirectory
$writer = $null
$subscriptions = @()
if ($QuietOutput) {
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$writer = [System.IO.StreamWriter]::new($logPath, $true)
$writer.AutoFlush = $true
}
$process = [System.Diagnostics.Process]::new()
$process.StartInfo = $startInfo
try {
if ($QuietOutput) {
# Event-driven rather than ReadToEnd on both streams in turn, which
# deadlocks as soon as one pipe buffer fills.
$handler = {
if ($null -ne $EventArgs.Data) {
$Event.MessageData.WriteLine($EventArgs.Data)
}
}
$subscriptions += Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -Action $handler -MessageData $writer
$subscriptions += Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -Action $handler -MessageData $writer
}
$null = $process.Start()
if ($QuietOutput) {
$process.BeginOutputReadLine()
$process.BeginErrorReadLine()
}
if ($null -eq $budget) {
$process.WaitForExit()
}
elseif (-not $process.WaitForExit([int][System.Math]::Min([long][int]::MaxValue, $remainingMs))) {
Write-Host ("::error title=CI test runner::'dotnet $($arguments[0])' exhausted the " +
"$budgetMinutes-minute per-project ceiling and was killed.")
$process.Kill($true)
$null = $process.WaitForExit(60 * 1000)
return [pscustomobject]@{ ExitCode = -1; TimedOut = $true }
}
if ($QuietOutput) {
# The timed overload returns as soon as the process exits; only the
# parameterless one waits for the asynchronous readers to drain, and
# without it the tail of the log is lost.
$process.WaitForExit()
}
return [pscustomobject]@{ ExitCode = $process.ExitCode; TimedOut = $false }
}
finally {
foreach ($subscription in $subscriptions) {
Unregister-Event -SourceIdentifier $subscription.Name -ErrorAction SilentlyContinue
}
if ($null -ne $writer) {
$writer.Dispose()
}
$process.Dispose()
}
}
<#
.SYNOPSIS
Evaluates the properties that decide whether a project takes part in this
profile, without restoring or building it.
.DESCRIPTION
Without a framework the project is evaluated as the build sees it, so a
project that pins a single TargetFramework keeps it and
Directory.Build.targets can restrict it. Passing the profile's framework as a
global property would override that pin and hide the restriction, leaving
'dotnet build --framework' to fail with NETSDK1005. The framework is only
passed to resolve the TargetDir of a project already known to apply.
#>
function Get-ProjectProperties([string] $project, [string] $framework = '')
{
$arguments = @(
'msbuild', $project,
'-getProperty:IsTestProject;TargetFrameworks;TargetFramework;TargetDir',
"-p:CustomTestTarget=$CustomTestTarget",
"-p:Configuration=$Configuration",
'-nologo')
if ($framework) {
$arguments += "-p:TargetFramework=$framework"
}
$output = & dotnet @arguments | Out-String
if ($LASTEXITCODE -ne 0) {
throw "Could not evaluate '$project' for CustomTestTarget=$CustomTestTarget (exit code $LASTEXITCODE)."
}
# MSBuild prints the requested properties as a JSON document, but an
# evaluation-time warning would be printed alongside it, so take the document
# rather than the whole stream.
$start = $output.IndexOf('{')
$end = $output.LastIndexOf('}')
if ($start -lt 0 -or $end -le $start) {
throw "Evaluating '$project' produced no property document.`n$output"
}
return ($output.Substring($start, $end - $start + 1) | ConvertFrom-Json).Properties
}
$records = @()
foreach ($project in $projectList) {
$stem = [System.IO.Path]::GetFileNameWithoutExtension($project)
Write-Host "::group::$stem ($CustomTestTarget / $Framework / $Configuration)"
$record = [ordered]@{
project = $project
customTarget = $CustomTestTarget
framework = $Framework
configuration = $Configuration
outcome = 'failed'
reason = ''
total = 0
passed = 0
failed = 0
# Wall-clock seconds, read by update-test-durations.ps1 to refresh
# the weights get-ci-matrix.ps1 packs batches with.
buildSeconds = 0
testSeconds = 0
}
try {
if (-not (Test-Path -LiteralPath $project)) {
throw "The project file does not exist."
}
$properties = Get-ProjectProperties $project
$declared = @()
if (-not [string]::IsNullOrWhiteSpace($properties.TargetFrameworks)) {
$declared = @($properties.TargetFrameworks -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
elseif (-not [string]::IsNullOrWhiteSpace($properties.TargetFramework)) {
$declared = @($properties.TargetFramework)
}
if ($properties.IsTestProject -eq 'false') {
# Directory.Build.targets emptied the project for this profile. The
# reason is recorded so a profile that skips everything is visible
# rather than looking like a clean run.
$record.outcome = 'not-applicable'
$record.reason = "RestrictForLegacyTfm makes this an empty shell for CustomTestTarget=$CustomTestTarget."
Write-Host "Not applicable: $($record.reason)"
continue
}
if ($declared -notcontains $Framework) {
throw ("The project builds [$($declared -join ', ')] for CustomTestTarget=$CustomTestTarget " +
"but this profile hosts its tests on $Framework. Either follow CustomTestTarget in the " +
"project's TargetFrameworks or set RestrictForLegacyTfm so the profile skips it explicitly.")
}
$targetDir = (Get-ProjectProperties $project $Framework).TargetDir
$projectResults = Join-Path $resultsRoot $stem
$null = New-Item -ItemType Directory -Path $projectResults -Force
$logPath = Join-Path $projectResults 'build-and-test.log'
$buildArguments = @(
'build', $project,
'--configuration', $Configuration,
'--framework', $Framework,
"/p:CustomTestTarget=$CustomTestTarget")
if ($Coverage) {
# Not what switches coverlet on - the XPlat data collector does the
# instrumentation. It turns ContinuousIntegrationBuild off in
# common.props so SourceLink does not rewrite the source paths
# embedded in the pdb to deterministic '/_/...' paths, which the
# changed-lines gate needs in order to map coverage back onto the
# working tree. It has to be set for the build, not just the test.
$buildArguments += '/p:CollectCoverage=true'
}
$buildBudget = [System.Diagnostics.Stopwatch]::StartNew()
$build = Invoke-Dotnet $buildArguments $null 0 $logPath
$record.buildSeconds = [int]$buildBudget.Elapsed.TotalSeconds
if ($build.ExitCode -ne 0) {
throw "The build failed with exit code $($build.ExitCode)."
}
$testArguments = @(
'test', $project,
'--no-build',
'--configuration', $Configuration,
'--framework', $Framework,
"/p:CustomTestTarget=$CustomTestTarget",
'--logger', 'trx',
'--results-directory', $projectResults,
# Kill (and name) any single test that outlives the profile's hang
# budget so a silent hang surfaces as "Test <Name> exceeded the
# configured timeout" rather than burning the job timeout with
# nothing to go on. The mini dump carries every thread's stack, which
# is what a teardown or shutdown hang needs, without serialising the
# managed heap of a server-hosting test process.
'--blame-hang-timeout', $HangTimeout,
'--blame-hang-dump-type', 'mini',
# Crash detection: the sequence file records which test was running
# when the host exited, and the mini dump captures the native state.
# Only written on an actual crash, so healthy runs pay no cost.
'--blame-crash',
'--blame-crash-dump-type', 'mini')
if ($Coverage) {
$testArguments += @(
'/p:CollectCoverage=true',
'--collect:XPlat Code Coverage',
'--settings', './tests/coverlet.runsettings.xml')
}
$projectFilter = $Filter
if ($stem -eq 'Opc.Ua.Types.Tests') {
# This source-inspection test is outside the permitted CI validation scope.
$excluded = 'FullyQualifiedName!~TheComparerSourceNamesNoProfile'
$projectFilter = if ([string]::IsNullOrWhiteSpace($Filter)) { $excluded } else { "($Filter)&$excluded" }
}
if (-not [string]::IsNullOrWhiteSpace($projectFilter)) {
$testArguments += @('--filter', $projectFilter)
}
# Keep per-test progress visible while diagnosing the WotCon shard timeout.
if ($stem -eq 'Opc.Ua.WotCon.Tests' -and
$projectFilter -like '*FullyQualifiedName!~Opc.Ua.WotCon.Tests.Materialization.*') {
$testArguments += @('--logger', 'console;verbosity=detailed')
}
# Above the adapter's default 2,000-case limit, a non-category
# selection becomes an empty engine filter and runs the whole assembly.
# Apply this after coverage options and share one runsettings delimiter.
$testArguments += @('--', 'NUnit.AssemblySelectLimit=2147483647')
if ($IsMacOS -and $env:OPCUA_CAPTURE_MACOS_NATIVE_LOADER_DIAGNOSTICS -eq 'true' -and
$stem -eq 'Opc.Ua.Security.Pkcs11.Tests') {
# VSTest does not forward the test host's stderr, where dyld writes
# by default, so variables set on 'dotnet test' only traced the
# muxer and MSBuild. RunConfiguration.EnvironmentVariables reaches
# the test host alone, and DYLD_PRINT_TO_FILE keeps its trace.
$dyldTrace = Join-Path $projectResults 'dyld-testhost.log'
$testArguments += @(
"RunConfiguration.EnvironmentVariables.DYLD_PRINT_TO_FILE=$dyldTrace",
'RunConfiguration.EnvironmentVariables.DYLD_PRINT_LIBRARIES=1',
'RunConfiguration.EnvironmentVariables.DYLD_PRINT_SEGMENTS=1',
'RunConfiguration.EnvironmentVariables.DYLD_PRINT_APIS=1')
}
$testBudget = [System.Diagnostics.Stopwatch]::StartNew()
$test = Invoke-Dotnet $testArguments $testBudget $PerProjectTimeoutMinutes $logPath $targetDir
$record.testSeconds = [int]$testBudget.Elapsed.TotalSeconds
if ($test.TimedOut) {
throw "The test exhausted the $PerProjectTimeoutMinutes-minute per-project ceiling."
}
$results = Measure-TestResults $projectResults
$record.total = $results.Total
$record.passed = $results.Passed
$record.failed = $results.Failed
if ($results.Files -eq 0) {
throw ('No TRX was produced. Every mainline test project runs on VSTest and must emit one; ' +
'a Microsoft.Testing.Platform project belongs in a dedicated job instead of this matrix.')
}
$verdict = Get-TestRunVerdict `
-TrxFileCount $results.Files `
-Total $results.Total `
-Passed $results.Passed `
-Failed $results.Failed `
-FixtureFailures $results.FixtureFailures `
-RunFailures $results.RunFailures `
-ExitCode $test.ExitCode `
-TimedOut $test.TimedOut `
-TimeoutMinutes $PerProjectTimeoutMinutes
if (-not $verdict.Passed) {
throw $verdict.Reason
}
if ($verdict.Tolerated) {
# Surfaced as a warning annotation so a host that keeps dying at exit
# stays visible instead of being silently swallowed.
$record.reason = $verdict.Reason
Write-Host "::warning title=$stem ($CustomTestTarget/$Configuration)::$($verdict.Reason)"
}
$record.outcome = 'passed'
Write-Host "Passed: $($results.Passed)/$($results.Total)."
}
catch {
$record.outcome = 'failed'
$record.reason = $_.Exception.Message
Write-Host "::error title=$stem ($CustomTestTarget/$Configuration)::$($record.reason)"
}
finally {
$records += [pscustomobject]$record
Write-Host '::endgroup::'
}
}
$summaryPath = Join-Path $resultsRoot 'batch-summary.json'
[ordered]@{
customTestTarget = $CustomTestTarget
framework = $Framework
configuration = $Configuration
filter = $Filter
coverage = [bool]$Coverage
projects = $records
} | ConvertTo-Json -Depth 5 | Out-File -LiteralPath $summaryPath -Encoding utf8
$lines = @(
"### $CustomTestTarget / $Framework / $Configuration",
'',
'| Project | Outcome | Passed | Total | Build (s) | Test (s) | Detail |',
'| --- | --- | ---: | ---: | ---: | ---: | --- |')
foreach ($record in $records) {
$detail = $record.reason -replace '\r?\n', ' '
$lines += "| $([System.IO.Path]::GetFileNameWithoutExtension($record.project)) | $($record.outcome) | $($record.passed) | $($record.total) | $($record.buildSeconds) | $($record.testSeconds) | $detail |"
}
$lines += ''
if (-not [string]::IsNullOrWhiteSpace($env:GITHUB_STEP_SUMMARY)) {
$lines | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append
}
$lines | Write-Host
$failedRecords = @($records | Where-Object { $_.outcome -eq 'failed' })
if ($failedRecords.Count -gt 0) {
throw "$($failedRecords.Count) of $($records.Count) project(s) failed: $(($failedRecords.project | ForEach-Object { [System.IO.Path]::GetFileNameWithoutExtension($_) }) -join ', ')."
}
$executed = @($records | Where-Object { $_.outcome -eq 'passed' })
if ($executed.Count -eq 0) {
# Not a failure: batches are arbitrary slices of the profile's project list,
# so one can legitimately contain only projects this profile restricts. It is
# still worth surfacing, because a batch that tests nothing is otherwise
# indistinguishable from a healthy one.
Write-Host ("::warning title=CI test runner::Every project in this batch is restricted for " +
"CustomTestTarget=$CustomTestTarget, so no tests ran.")
}
Write-Host "$($executed.Count) project(s) passed, $($records.Count - $executed.Count) not applicable."