-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-Test.ps1
More file actions
392 lines (331 loc) · 12.7 KB
/
Invoke-Test.ps1
File metadata and controls
392 lines (331 loc) · 12.7 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
#Requires -Modules Posh-SSH
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$HostName,
[Parameter(Mandatory = $false)]
[string]$UserName = "testrunner",
[Parameter(Mandatory = $false)]
[int]$Port = 22
)
<#
.SYNOPSIS
Initiates an SSH connection to an AMX device and runs control commands.
.DESCRIPTION
This script connects to an AMX device via SSH and executes two specific commands:
- msg on all
- pulse[33201:1:0,1]
Password must be provided via the AMX_TESTRUNNER_SSH_PASSWORD environment variable or will be prompted securely.
.PARAMETER HostName
The hostname or IP address of the AMX device.
.PARAMETER UserName
The username to authenticate with (default: testrunner).
.PARAMETER Port
The SSH port (default: 22).
.EXAMPLE
$env:AMX_SSH_PASSWORD = "mypassword"; .\ssh-runner.ps1 -HostName "192.168.1.100"
.EXAMPLE
.\ssh-runner.ps1 -HostName "10.0.0.5" -UserName "admin"
#>
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch ($Level) {
"INFO" { "Cyan" }
"SUCCESS" { "Green" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
default { "White" }
}
Write-Host "[$timestamp] [$Level] $Message" -ForegroundColor $color
}
# Define the commands to execute
$commands = @(
"msg on debug",
"pulse[33201:1:0,1]"
)
try {
# Load .env file if it exists
$envFile = Join-Path $PSScriptRoot ".env"
if (Test-Path $envFile) {
Write-Log "Loading environment variables from .env file"
Get-Content $envFile | ForEach-Object {
$line = $_.Trim()
# Skip empty lines and comments
if ($line -and -not $line.StartsWith("#")) {
# Parse KEY=VALUE format
if ($line -match '^([^=]+)=(.*)$') {
$key = $matches[1].Trim()
$value = $matches[2].Trim()
# Remove quotes if present
$value = $value -replace '^["'']|["'']$', ''
# Set environment variable for this session
[Environment]::SetEnvironmentVariable($key, $value, "Process")
}
}
}
Write-Log ".env file loaded successfully" "SUCCESS"
}
# Check if Posh-SSH module is available
if (-not (Get-Module -ListAvailable -Name Posh-SSH)) {
Write-Log "Posh-SSH module is not installed. Installing..." "WARNING"
Install-Module -Name Posh-SSH -Force -Scope CurrentUser
Write-Log "Posh-SSH module installed successfully" "SUCCESS"
}
Import-Module Posh-SSH -ErrorAction Stop
# Resolve HostName: command line > env var > prompt
if ([string]::IsNullOrEmpty($HostName)) {
if (Test-Path env:AMX_TESTRUNNER_SSH_HOST) {
$HostName = $env:AMX_TESTRUNNER_SSH_HOST
Write-Log "Using hostname from environment variable: $HostName"
}
else {
$HostName = Read-Host "Enter hostname or IP address"
if ([string]::IsNullOrEmpty($HostName)) {
Write-Log "Hostname cannot be empty" "ERROR"
exit 1
}
}
}
# Resolve UserName: command line > env var > default
# Check if UserName was explicitly provided via command line (not just the default)
if ($PSBoundParameters.ContainsKey('UserName')) {
Write-Log "Using username from command line: $UserName"
}
elseif (Test-Path env:AMX_TESTRUNNER_SSH_USER) {
$UserName = $env:AMX_TESTRUNNER_SSH_USER
Write-Log "Using username from environment variable: $UserName"
}
else {
Write-Log "Using default username: $UserName"
}
Write-Log "Starting SSH connection to ${UserName}@${HostName}:${Port}"
# Get password from environment variable or prompt
$securePassword = $null
if (Test-Path env:AMX_TESTRUNNER_SSH_PASSWORD) {
$password = $env:AMX_TESTRUNNER_SSH_PASSWORD
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
Write-Log "Using password from environment variable: AMX_TESTRUNNER_SSH_PASSWORD"
}
else {
Write-Log "Environment variable 'AMX_TESTRUNNER_SSH_PASSWORD' not found. Prompting for password..." "WARNING"
$securePassword = Read-Host "Enter password for ${UserName}@${HostName}" -AsSecureString
}
if ($null -eq $securePassword) {
Write-Log "Password cannot be empty" "ERROR"
exit 1
}
# Create credential object
$credential = New-Object System.Management.Automation.PSCredential($UserName, $securePassword)
# Establish SSH session
Write-Log "Establishing SSH session..."
$session = New-SSHSession -ComputerName $HostName -Port $Port -Credential $credential -AcceptKey -ErrorAction Stop
if ($null -eq $session) {
Write-Log "Failed to establish SSH session" "ERROR"
exit 1
}
Write-Log "SSH session established (Session ID: $($session.SessionId))" "SUCCESS"
Write-Host ""
# Create SSH shell stream for interactive commands
Write-Log "Creating SSH shell stream..."
$stream = New-SSHShellStream -SSHSession $session -ErrorAction Stop
# Collect all output for analysis
$allOutput = ""
# Wait for initial prompt
Start-Sleep -Milliseconds 500
$initialOutput = $stream.Read()
if ($initialOutput) {
Write-Host $initialOutput
$allOutput += $initialOutput
}
# Execute each command with streaming output
$commandIndex = 1
foreach ($command in $commands) {
Write-Log "Executing command $commandIndex/$($commands.Count): $command"
# Send command
$stream.WriteLine($command)
# For the test trigger command, wait intelligently for completion
if ($command -match "pulse") {
Write-Log "Waiting for test execution (max 600s)..."
$maxWaitSeconds = 600
$idleTimeoutSeconds = 3
$pollIntervalMs = 500
$startTime = Get-Date
$lastOutputTime = Get-Date
$hasReceivedOutput = $false
$testsStarted = $false
$testsFinished = $false
while ($true) {
$elapsed = (Get-Date) - $startTime
# Check max timeout
if ($elapsed.TotalSeconds -ge $maxWaitSeconds) {
Write-Log "Maximum wait time of ${maxWaitSeconds}s reached" "WARNING"
break
}
# Try to read output
Start-Sleep -Milliseconds $pollIntervalMs
$output = $stream.Read()
if ($output) {
# We got output - stream it and update timestamps
Write-Host $output
$allOutput += $output
$lastOutputTime = Get-Date
$hasReceivedOutput = $true
# Check for test start marker
if ($output -match "Starting Tests") {
$testsStarted = $true
Write-Log "Tests started" "INFO"
}
# Check for test end marker
if ($output -match "Finished Tests") {
$testsFinished = $true
Write-Log "Tests completed" "SUCCESS"
break
}
}
else {
# No output - check if we've been idle long enough
$idleTime = (Get-Date) - $lastOutputTime
# Only exit on idle if we've received at least some output
if ($hasReceivedOutput -and $idleTime.TotalSeconds -ge $idleTimeoutSeconds) {
if (-not $testsStarted) {
Write-Log "No test start detected after ${idleTimeoutSeconds}s idle" "WARNING"
}
elseif (-not $testsFinished) {
Write-Log "Tests started but did not complete normally (${idleTimeoutSeconds}s idle)" "WARNING"
}
else {
Write-Log "No output for ${idleTimeoutSeconds}s - tests appear complete"
}
break
}
}
}
}
else {
# For non-test commands, use simple wait
Start-Sleep -Milliseconds 1000
$output = $stream.Read()
if ($output) {
Write-Host $output
$allOutput += $output
}
}
Write-Log "Command sent successfully" "SUCCESS"
Write-Host ""
$commandIndex++
}
# Give a final moment for any stragglers
Start-Sleep -Milliseconds 250
$finalOutput = $stream.Read()
if ($finalOutput) {
Write-Host $finalOutput
$allOutput += $finalOutput
}
# Close stream and session
Write-Log "Closing SSH connection..."
$stream.Dispose()
Remove-SSHSession -SSHSession $session | Out-Null
Write-Log "SSH session closed successfully" "SUCCESS"
# Analyze test results
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Test Results Analysis" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
# Build a map of test suites and their tests
$testSuiteMap = @{}
$currentSuite = $null
$lines = $allOutput -split "`n"
foreach ($line in $lines) {
# Check for test suite start
if ($line -match "Starting Test Suite:\s+(.+?)\s+=====") {
$currentSuite = $matches[1].Trim()
if (-not $testSuiteMap.ContainsKey($currentSuite)) {
$testSuiteMap[$currentSuite] = @{
Passed = @()
Failed = @()
}
}
}
# Check for test suite end
if ($line -match "Finished Test Suite:") {
$currentSuite = $null
}
# Parse test results within the current suite
if ($null -ne $currentSuite) {
if ($line -match "Test (\d+) passed") {
$testNum = $matches[1]
$testSuiteMap[$currentSuite].Passed += $testNum
}
elseif ($line -match "Test (\d+) failed") {
$testNum = $matches[1]
$testSuiteMap[$currentSuite].Failed += $testNum
}
}
}
# Calculate totals
$totalPassed = 0
$totalFailed = 0
foreach ($suite in $testSuiteMap.Keys) {
$totalPassed += $testSuiteMap[$suite].Passed.Count
$totalFailed += $testSuiteMap[$suite].Failed.Count
}
$totalTests = $totalPassed + $totalFailed
Write-Host ""
Write-Host "Total Tests: $totalTests" -ForegroundColor White
Write-Host "Passed: $totalPassed" -ForegroundColor Green
Write-Host "Failed: $totalFailed" -ForegroundColor $(if ($totalFailed -gt 0) { "Red" } else { "Green" })
Write-Host ""
# Show results by test suite
if ($testSuiteMap.Count -gt 0) {
Write-Host "Results by Test Suite:" -ForegroundColor Cyan
foreach ($suite in $testSuiteMap.Keys | Sort-Object) {
$suiteData = $testSuiteMap[$suite]
$suitePassed = $suiteData.Passed.Count
$suiteFailed = $suiteData.Failed.Count
$suiteTotal = $suitePassed + $suiteFailed
$suiteColor = if ($suiteFailed -gt 0) { "Red" } else { "Green" }
Write-Host " [$suite]" -ForegroundColor White -NoNewline
Write-Host " $suiteTotal tests: " -NoNewline
Write-Host "$suitePassed passed" -ForegroundColor Green -NoNewline
Write-Host ", " -NoNewline
Write-Host "$suiteFailed failed" -ForegroundColor $suiteColor
# Show failed tests for this suite
if ($suiteFailed -gt 0) {
foreach ($testNum in $suiteData.Failed) {
Write-Host " - $suite Test $testNum" -ForegroundColor Red
}
}
}
Write-Host ""
}
if ($totalFailed -gt 0) {
Write-Log "Test run completed with failures" "ERROR"
exit 1
}
else {
Write-Log "All tests passed successfully!" "SUCCESS"
exit 0
}
}
catch {
Write-Log "An error occurred: $($_.Exception.Message)" "ERROR"
# Clean up stream and session if they exist
if ($null -ne $stream) {
try {
$stream.Dispose()
}
catch {
# Ignore cleanup errors
}
}
if ($null -ne $session) {
try {
Remove-SSHSession -SSHSession $session | Out-Null
}
catch {
# Ignore cleanup errors
}
}
exit 1
}