forked from Azure/azure-powershell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon.ps1
371 lines (327 loc) · 10.7 KB
/
Common.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
$excludedExtensions = @(".dll", ".zip", ".msi", ".exe")
###################################
#
# Retrievce the contents of a powershrell transcript, stripping headers and footers
#
# param [string] $path: The path to the transript file to read
###################################
function Get-Transcript
{
param([string] $path)
return Get-Content $path |
Select-String -InputObject {$_} -Pattern "^Start Time\s*:.*" -NotMatch |
Select-String -InputObject {$_} -Pattern "^End Time\s*:.*" -NotMatch |
Select-String -InputObject {$_} -Pattern "^Machine\s*:.*" -NotMatch |
Select-String -InputObject {$_} -Pattern "^Username\s*:.*" -NotMatch |
Select-String -InputObject {$_} -Pattern "^Transcript started, output file is.*" -NotMatch
}
########################
#
# Get a random file name in the current directory
#
# param [string] $rootPath: The path of the directory to contain the random file (optional)
########################
function Get-LogFile
{
param([string] $rootPath = ".")
return [System.IO.Path]::Combine($rootPath, ([System.IO.Path]::GetRandomFileName()))
}
#################
#
# Execute a test, no exception thrown means the test passes. Can also be used to compare test
# output to a baseline file, or to generate a baseline file
#
# param [scriptblock] $test: The test code to run
# param [string] $testScript: The path to the baseline file (optional)
# param [switch] $generate: Set if the baseline file should be generated, otherwise
# the baseline file would be used for comparison with test output
##################
function Run-Test
{
param([scriptblock]$test, [string] $testName = $null, [string] $testScript = $null, [switch] $generate = $false)
Test-Setup
$transFile = $testName + ".log"
if ($testName -eq $null)
{
$transFile = Get-LogFile "."
}
if($testScript)
{
if ($generate)
{
Write-Log "[run-test]: generating script file $testScript"
$transFile = $testScript
}
else
{
Write-Log "[run-test]: writing output to $transFile, using validation script $testScript"
}
}
else
{
Write-Log "[run-test]: Running test without file comparison"
}
$oldPref = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
#Start-Transcript -Path $transFile
$success = $false;
$ErrorActionPreference = $oldPref
try
{
&$test
$success = $true;
}
finally
{
Test-Cleanup
$oldPref = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
#Stop-Transcript
$ErrorActionPreference = $oldPref
if ($testScript)
{
if ($success -and -not $generate)
{
$result = Compare-Object (Get-Transcript $testScript) (Get-Transcript $transFile)
if ($result -ne $null)
{
throw "[run-test]: Test Failed " + (Out-String -InputObject $result) + ", Transcript at $transFile"
}
}
}
if ($success)
{
Write-Log "[run-test]: Test Passed"
}
}
}
##################
#
# Format a string for proper output to host and transcript
#
# param [string] $message: The text to write
##################
function Write-Log
{
[CmdletBinding()]
param( [Object] [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$false)] $obj = "")
PROCESS
{
$obj | Out-String | Write-Verbose
}
}
function Check-SubscriptionMatch
{
param([string] $baseSubscriptionName, [Microsoft.WindowsAzure.Commands.Utilities.Common.SubscriptionData] $checkedSubscription)
Write-Log ("[CheckSubscriptionMatch]: base subscription: '$baseSubscriptionName', validating '" + ($checkedSubscription.SubscriptionName)+ "'")
Format-Subscription $checkedSubscription | Write-Log
if ($baseSubscriptionName -ne $checkedSubscription.SubscriptionName)
{
throw ("[Check-SubscriptionMatch]: Subscription Match Failed '" + ($baseSubscriptionName) + "' != '" + ($checkedSubscription.SubscriptionName) + "'")
}
Write-Log ("CheckSubscriptionMatch]: subscription check succeeded.")
}
##########################
#
# Return the fully qualified filename of a given file
#
# param [string] $path: The relative path to the file
#
##########################
function Get-FullName
{
param([string] $path)
$pathObj = Get-Item $path
return ($pathObj.FullName)
}
#############################
#
# PowerShell environment setup for running a test, save previous snvironment settings and
# enable verbose, debug, and warning streams
#
#############################
function Test-Setup([bool]$runOnCIMachine=$false)
{
$global:oldConfirmPreference = $global:ConfirmPreference
$global:oldDebugPreference = $global:DebugPreference
$global:oldErrorActionPreference = $global:ErrorActionPreference
$global:oldFormatEnumerationLimit = $global:FormatEnumerationLimit
$global:oldProgressPreference = $global:ProgressPreference
$global:oldVerbosePreference = $global:VerbosePreference
$global:oldWarningPreference = $global:WarningPreference
$global:oldWhatIfPreference = $global:WhatIfPreference
$global:ConfirmPreference = "None"
$global:DebugPreference = "SilentlyContinue"
if($runOnCIMachine -eq $true)
{
$global:DebugPreference = "Continue"
}
$global:ErrorActionPreference = "Stop"
$global:FormatEnumerationLimit = 10000
$global:ProgressPreference = "SilentlyContinue"
$global:VerbosePreference = "Continue"
$global:WarningPreference = "Continue"
$global:WhatIfPreference = 0
}
#############################
#
# PowerShell environment cleanup for running a test, restore previous snvironment settings
#
#############################
function Test-Cleanup
{
$global:ConfirmPreference = $global:oldConfirmPreference
$global:DebugPreference = $global:oldDebugPreference
$global:ErrorActionPreference = $global:oldErrorActionPreference
$global:FormatEnumerationLimit = $global:oldFormatEnumerationLimit
$global:ProgressPreference = $global:oldProgressPreference
$global:VerbosePreference = $global:oldVerbosePreference
$global:WarningPreference = $global:oldWarningPreference
$global:WhatIfPreference = $global:oldWhatIfPreference
Remove-AllSubscriptions
}
#######################
#
# Dump the contents of a directory to the output stream
#
# param [string] $rootPath: The path to the directory
# param [switch] $resurse : True if we should recurse directories
######################
function Dump-Contents
{
param([string] $rootPath = ".", [switch] $recurse = $false)
if (-not ((Test-Path $rootPath) -eq $true))
{
throw "[dump-contents]: $rootPath does not exist"
}
foreach ($item in Get-ChildItem $rootPath)
{
Write-Log
Write-Log "---------------------------"
Write-Log $item.Name
Write-Log "---------------------------"
Write-Log
if (!$item.PSIsContainer)
{
if (Test-BinaryFile $item)
{
Write-Log "---- binary data excluded ----"
}
else
{
Get-Content ($item.PSPath)
}
}
elseif ($recurse)
{
Dump-Contents ($item.PSPath) -recurse
}
}
}
function Test-BinaryFile
{
param ([System.IO.FileInfo] $file)
($excludedExtensions | Where-Object -FilterScript {$_ -eq $file.Extension}) -ne $null
}
<#
.SYNOPSIS
Removes all current subscriptions.
#>
function Remove-AllSubscriptions
{
Get-AzureSubscription | Remove-AzureSubscription -Force
}
<#
.SYNOPSIS
Waits on the specified job with the given timeout.
.PARAMETER scriptBlock
The script block to execute.
.PARAMETER timeout
The maximum timeout for the script.
#>
function Wait-Function
{
param([ScriptBlock] $scriptBlock, [object] $breakCondition, [int] $timeout)
if ($timeout -eq 0) { $timeout = 60 * 5 }
$start = [DateTime]::Now
$current = [DateTime]::Now
$diff = $current - $start
do
{
Start-Sleep -s 5
$current = [DateTime]::Now
$diff = $current - $start
$result = &$scriptBlock
}
while(($result -ne $breakCondition) -and ($diff.TotalSeconds -lt $timeout))
if ($diff.TotalSeconds -ge $timeout)
{
Write-Warning "The script block '$scriptBlock' exceeded the timeout."
# End the processing so the test does not blow up
exit
}
}
<#
.SYNOPSIS
Waits for specified duration if not-mocked, otherwise skips wait.
.PARAMETER timeout
Timeout in seconds
#>
function Wait-Seconds
{
param([int] $timeout)
[Microsoft.WindowsAzure.Testing.TestUtilities]::Wait($timeout * 1000)
}
<#
.SYNOPSIS
Retires the specified job the given numer of times, waiting the given interval between tries
.PARAMETER scriptBlock
The script block to execute. Must be a predicate (return true or false)
.PARAMETER argument
Argument to pass to the script block
.PARAMETER maxTries
The maximum number of times to retry
.PARAMETER interval
The number of seconds to wait before retrying
#>
function Retry-Function
{
param([ScriptBlock] $scriptBlock, [Object] $argument, [int] $maxTries, [int] $interval)
if ($interval -eq 0) { $interval = 60 }
$result = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argument;
$tries = 1;
while(( $result -ne $true) -and ($tries -le $maxTries))
{
Start-Sleep -s $interval
$result = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argument;
$tries++;
}
return $result;
}
function getAssetName
{
$stack = Get-PSCallStack
$testName = $null;
foreach ($frame in $stack)
{
if ($frame.Command.StartsWith("Test-", "CurrentCultureIgnoreCase"))
{
$testName = $frame.Command
}
}
$assetName = [Microsoft.Azure.Utilities.HttpRecorder.HttpMockServer]::GetAssetName($testName, "onesdk")
return $assetName
}