PageRenderTime 26ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/ResourceManager/KeyVault/Commands.KeyVault.Test/Scripts/PSHCommon/Common.ps1

https://gitlab.com/jslee1/azure-powershell
Powershell | 354 lines | 219 code | 33 blank | 102 comment | 32 complexity | 653113ad7e557416c3fffcaf082830e3 MD5 | raw file
  1. # ----------------------------------------------------------------------------------
  2. #
  3. # Copyright Microsoft Corporation
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. # ----------------------------------------------------------------------------------
  14. $excludedExtensions = @(".dll", ".zip", ".msi", ".exe")
  15. ###################################
  16. #
  17. # Retrievce the contents of a powershrell transcript, stripping headers and footers
  18. #
  19. # param [string] $path: The path to the transript file to read
  20. ###################################
  21. function Get-Transcript
  22. {
  23. param([string] $path)
  24. return Get-Content $path |
  25. Select-String -InputObject {$_} -Pattern "^Start Time\s*:.*" -NotMatch |
  26. Select-String -InputObject {$_} -Pattern "^End Time\s*:.*" -NotMatch |
  27. Select-String -InputObject {$_} -Pattern "^Machine\s*:.*" -NotMatch |
  28. Select-String -InputObject {$_} -Pattern "^Username\s*:.*" -NotMatch |
  29. Select-String -InputObject {$_} -Pattern "^Transcript started, output file is.*" -NotMatch
  30. }
  31. ########################
  32. #
  33. # Get a random file name in the current directory
  34. #
  35. # param [string] $rootPath: The path of the directory to contain the random file (optional)
  36. ########################
  37. function Get-LogFile
  38. {
  39. param([string] $rootPath = ".")
  40. return [System.IO.Path]::Combine($rootPath, ([System.IO.Path]::GetRandomFileName()))
  41. }
  42. #################
  43. #
  44. # Execute a test, no exception thrown means the test passes. Can also be used to compare test
  45. # output to a baseline file, or to generate a baseline file
  46. #
  47. # param [scriptblock] $test: The test code to run
  48. # param [string] $testScript: The path to the baseline file (optional)
  49. # param [switch] $generate: Set if the baseline file should be generated, otherwise
  50. # the baseline file would be used for comparison with test output
  51. ##################
  52. function Run-Test
  53. {
  54. param([scriptblock]$test, [string] $testName = $null, [string] $testScript = $null, [switch] $generate = $false)
  55. Test-Setup
  56. $transFile = $testName + ".log"
  57. if ($testName -eq $null)
  58. {
  59. $transFile = Get-LogFile "."
  60. }
  61. if($testScript)
  62. {
  63. if ($generate)
  64. {
  65. Write-Log "[run-test]: generating script file $testScript"
  66. $transFile = $testScript
  67. }
  68. else
  69. {
  70. Write-Log "[run-test]: writing output to $transFile, using validation script $testScript"
  71. }
  72. }
  73. else
  74. {
  75. Write-Log "[run-test]: Running test without file comparison"
  76. }
  77. $oldPref = $ErrorActionPreference
  78. $ErrorActionPreference = "SilentlyContinue"
  79. #Start-Transcript -Path $transFile
  80. $success = $false;
  81. $ErrorActionPreference = $oldPref
  82. try
  83. {
  84. &$test
  85. $success = $true;
  86. }
  87. finally
  88. {
  89. Test-Cleanup
  90. $oldPref = $ErrorActionPreference
  91. $ErrorActionPreference = "SilentlyContinue"
  92. #Stop-Transcript
  93. $ErrorActionPreference = $oldPref
  94. if ($testScript)
  95. {
  96. if ($success -and -not $generate)
  97. {
  98. $result = Compare-Object (Get-Transcript $testScript) (Get-Transcript $transFile)
  99. if ($result -ne $null)
  100. {
  101. throw "[run-test]: Test Failed " + (Out-String -InputObject $result) + ", Transcript at $transFile"
  102. }
  103. }
  104. }
  105. if ($success)
  106. {
  107. Write-Log "[run-test]: Test Passed"
  108. }
  109. }
  110. }
  111. ##################
  112. #
  113. # Format a string for proper output to host and transcript
  114. #
  115. # param [string] $message: The text to write
  116. ##################
  117. function Write-Log
  118. {
  119. [CmdletBinding()]
  120. param( [Object] [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$false)] $obj = "")
  121. PROCESS
  122. {
  123. $obj | Out-String | Write-Verbose
  124. }
  125. }
  126. function Check-SubscriptionMatch
  127. {
  128. param([string] $baseSubscriptionName, [Microsoft.WindowsAzure.Commands.Utilities.Common.SubscriptionData] $checkedSubscription)
  129. Write-Log ("[CheckSubscriptionMatch]: base subscription: '$baseSubscriptionName', validating '" + ($checkedSubscription.SubscriptionName)+ "'")
  130. Format-Subscription $checkedSubscription | Write-Log
  131. if ($baseSubscriptionName -ne $checkedSubscription.SubscriptionName)
  132. {
  133. throw ("[Check-SubscriptionMatch]: Subscription Match Failed '" + ($baseSubscriptionName) + "' != '" + ($checkedSubscription.SubscriptionName) + "'")
  134. }
  135. Write-Log ("CheckSubscriptionMatch]: subscription check succeeded.")
  136. }
  137. ##########################
  138. #
  139. # Return the fully qualified filename of a given file
  140. #
  141. # param [string] $path: The relative path to the file
  142. #
  143. ##########################
  144. function Get-FullName
  145. {
  146. param([string] $path)
  147. $pathObj = Get-Item $path
  148. return ($pathObj.FullName)
  149. }
  150. #############################
  151. #
  152. # PowerShell environment setup for running a test, save previous snvironment settings and
  153. # enable verbose, debug, and warning streams
  154. #
  155. #############################
  156. function Test-Setup
  157. {
  158. $global:oldConfirmPreference = $global:ConfirmPreference
  159. $global:oldDebugPreference = $global:DebugPreference
  160. $global:oldErrorActionPreference = $global:ErrorActionPreference
  161. $global:oldFormatEnumerationLimit = $global:FormatEnumerationLimit
  162. $global:oldProgressPreference = $global:ProgressPreference
  163. $global:oldVerbosePreference = $global:VerbosePreference
  164. $global:oldWarningPreference = $global:WarningPreference
  165. $global:oldWhatIfPreference = $global:WhatIfPreference
  166. $global:ConfirmPreference = "None"
  167. $global:DebugPreference = "Continue"
  168. $global:ErrorActionPreference = "Stop"
  169. $global:FormatEnumerationLimit = 10000
  170. $global:ProgressPreference = "SilentlyContinue"
  171. $global:VerbosePreference = "Continue"
  172. $global:WarningPreference = "Continue"
  173. $global:WhatIfPreference = 0
  174. }
  175. #############################
  176. #
  177. # PowerShell environment cleanup for running a test, restore previous snvironment settings
  178. #
  179. #############################
  180. function Test-Cleanup
  181. {
  182. $global:ConfirmPreference = $global:oldConfirmPreference
  183. $global:DebugPreference = $global:oldDebugPreference
  184. $global:ErrorActionPreference = $global:oldErrorActionPreference
  185. $global:FormatEnumerationLimit = $global:oldFormatEnumerationLimit
  186. $global:ProgressPreference = $global:oldProgressPreference
  187. $global:VerbosePreference = $global:oldVerbosePreference
  188. $global:WarningPreference = $global:oldWarningPreference
  189. $global:WhatIfPreference = $global:oldWhatIfPreference
  190. }
  191. #######################
  192. #
  193. # Dump the contents of a directory to the output stream
  194. #
  195. # param [string] $rootPath: The path to the directory
  196. # param [switch] $resurse : True if we should recurse directories
  197. ######################
  198. function Dump-Contents
  199. {
  200. param([string] $rootPath = ".", [switch] $recurse = $false)
  201. if (-not ((Test-Path $rootPath) -eq $true))
  202. {
  203. throw "[dump-contents]: $rootPath does not exist"
  204. }
  205. foreach ($item in Get-ChildItem $rootPath)
  206. {
  207. Write-Log
  208. Write-Log "---------------------------"
  209. Write-Log $item.Name
  210. Write-Log "---------------------------"
  211. Write-Log
  212. if (!$item.PSIsContainer)
  213. {
  214. if (Test-BinaryFile $item)
  215. {
  216. Write-Log "---- binary data excluded ----"
  217. }
  218. else
  219. {
  220. Get-Content ($item.PSPath)
  221. }
  222. }
  223. elseif ($recurse)
  224. {
  225. Dump-Contents ($item.PSPath) -recurse
  226. }
  227. }
  228. }
  229. function Test-BinaryFile
  230. {
  231. param ([System.IO.FileInfo] $file)
  232. ($excludedExtensions | Where-Object -FilterScript {$_ -eq $file.Extension}) -ne $null
  233. }
  234. <#
  235. .SYNOPSIS
  236. Waits on the specified job with the given timeout.
  237. .PARAMETER scriptBlock
  238. The script block to execute.
  239. .PARAMETER timeout
  240. The maximum timeout for the script.
  241. #>
  242. function Wait-Function
  243. {
  244. param([ScriptBlock] $scriptBlock, [object] $breakCondition, [int] $timeout)
  245. if ($timeout -eq 0) { $timeout = 60 * 5 }
  246. $start = [DateTime]::Now
  247. $current = [DateTime]::Now
  248. $diff = $current - $start
  249. do
  250. {
  251. Wait-Seconds 5
  252. $current = [DateTime]::Now
  253. $diff = $current - $start
  254. $result = &$scriptBlock
  255. }
  256. while(($result -ne $breakCondition) -and ($diff.TotalSeconds -lt $timeout))
  257. if ($diff.TotalSeconds -ge $timeout)
  258. {
  259. Write-Warning "The script block '$scriptBlock' exceeded the timeout."
  260. # End the processing so the test does not blow up
  261. exit
  262. }
  263. }
  264. <#
  265. .SYNOPSIS
  266. Waits for specified duration if not-mocked, otherwise skips wait.
  267. .PARAMETER timeout
  268. Timeout in seconds
  269. #>
  270. function Wait-Seconds
  271. {
  272. param([int] $timeout)
  273. [Microsoft.WindowsAzure.Testing.TestUtilities]::Wait($timeout * 1000)
  274. }
  275. <#
  276. .SYNOPSIS
  277. Retires the specified job the given numer of times, waiting the given interval between tries
  278. .PARAMETER scriptBlock
  279. The script block to execute. Must be a predicate (return true or false)
  280. .PARAMETER argument
  281. Argument to pass to the script block
  282. .PARAMETER maxTries
  283. The maximum number of times to retry
  284. .PARAMETER interval
  285. The number of seconds to wait before retrying
  286. #>
  287. function Retry-Function
  288. {
  289. param([ScriptBlock] $scriptBlock, [Object] $argument, [int] $maxTries, [int] $interval)
  290. if ($interval -eq 0) { $interval = 60 }
  291. $result = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argument;
  292. $tries = 1;
  293. while(( $result -ne $true) -and ($tries -le $maxTries))
  294. {
  295. Wait-Seconds $interval
  296. $result = Invoke-Command -ScriptBlock $scriptBlock -ArgumentList $argument;
  297. $tries++;
  298. }
  299. return $result;
  300. }
  301. function getAssetName
  302. {
  303. $stack = Get-PSCallStack
  304. $testName = $null;
  305. foreach ($frame in $stack)
  306. {
  307. if ($frame.Command.StartsWith("Test-", "CurrentCultureIgnoreCase"))
  308. {
  309. $testName = $frame.Command
  310. }
  311. }
  312. $assetName = [Microsoft.Azure.Utilities.HttpRecorder.HttpMockServer]::GetAssetName($testName, "onesdk")
  313. return $assetName
  314. }