Jenkinsでプレイリストを実行する
このトピックでは、Jenkinsパイプラインを設定して、Tosca Cloudプレイリストを実行する方法を示します。Tosca Cloud プレイリストを使用して、CI/CD統合を利用することで、テストランプロセスを完全に自動化することができます。
Tosca Cloud をJenkins CIパイプラインに統合するための手順は以下の通りです。
詳細なセットアップ手順を省略したい場合は、すべてを一度に設定できる完全なコード例に進むことができます。
すべて設定が完了すると、パイプラインは自動的にプロセスを管理します。
始める前に
始めるために必要なものは以下の通りです。
-
Jenkinsとともに、パイプラインプラグインも一緒にインストールされている。
-
Swaggerから収集された認証値。
パイプラインを認証する
Jenkinsで新しいパイプラインジョブを作成し、環境ブロックで必要な認証値を定義してください。これらの値により、ご利用のパイプラインをTosca Cloudで認証できるようにします。
この例は、認証値を含む環境ブロックを示しています。
pipeline{
agent any
environment {
CLIENT_ID = '0Bx5q308ttNLhiXbf413'
CLIENT_SECRET = 'X438PC4VVXccvIm2HdQrZL4zffuWZciKrx5tRw4'
E2G_SCOPE = 'tta'
E2G_AUTH_URL = 'https://vehicle_insurance_company.com/oauth2/default/v3/token'
TOSCA_CLOUD_URL = 'https://vehicle_insurance_company.com/785fb70b-1621-4a71-a68f-05de9e1b40a3'
PLAYLIST_ID = '0aa88a1c-0bd1-4ee5-8ada-e89e7cecc2d2'
}
アクセストークンをリクエストする
Tosca CloudをCI/CDパイプラインに統合する場合は、アクセストークンを使用してAPIリクエストを認証する必要があります。
アクセストークンを取得するには、Tosca Cloudからclient_id、client_secret、scope、grant_type を含むトークンURLにリクエストを送信します。
リクエストの例:
stages {
stage('Get Token') {
steps {
powershell '''
$headers = @{
"Content-Type" = "application/x-www-form-urlencoded"
}
$Body = "client_id=$env:CLIENT_ID&client_secret=$env:CLIENT_SECRET&scope=$env:E2G_SCOPE&grant_type=client_credentials"
$maxRetries = 3
$retryCount = 0
$success = $false
do {
try {
Write-Host "=== TOKEN ACQUISITION API CALL ==="
$response = Invoke-RestMethod -Uri "$env:E2G_AUTH_URL" -Method "Post" -Headers $headers -Body $Body
$accessToken = $response.access_token
$success = $true
Write-Host "Token acquired successfully."
}
catch {
$retryCount++
Write-Host "Token acquisition failed (attempt $retryCount of $maxRetries): $($_.Exception.Message)"
if ($retryCount -lt $maxRetries) {
Start-Sleep -Seconds 5
}
}
} while (-not $success -and $retryCount -lt $maxRetries)
if (-not $success) {
throw "Failed to acquire token after $maxRetries attempts"
}
# Save token to file for use in subsequent stages
$accessToken | Out-File -FilePath "access_token.txt" -Encoding UTF8
'''
}
}
If the authentication succeeds, Jenkins saves the access token to the access_token.txt file specified in the request.By default, it stores this file in C:\ProgramData\Jenkins\.jenkins\workspace\<YourProjectName>.テストランをトリガーするために、後でこのトークンが必要になります。
テストランをトリガーする
Jenkinsパイプラインを通じてリクエストを送信し、テストランをトリガーするには、以下の手順に従ってください。
-
ヘッダーでリクエストを認証してください。
Bearer <access_token>のAuthorizationヘッダーを設定します。
application/jsonのContent-Typeヘッダーを設定します。
-
リクエスト本文において:
-
実行するプレイリストを指定するには、playlistId 本文にプレイリストIDを入力します。
-
Tosca CloudAgentまたはTosca CloudチームのAgentでテストを実行するには、プライベート本文にfalseを入力します。
-
-
エンドポイントTOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/にPOSTリクエストを送信します。
リクエストの例:
stage('Run Tests') {
steps {
powershell '''
$accessToken = Get-Content -Path "access_token.txt" -Raw
$accessToken = $accessToken.Trim()
function StartPlaylistExecution {
param(
[string]$AccessToken,
[string]$TtaUrl,
[string]$PlaylistId
)
try {
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
"Accept" = "application/json"
}
$body = @{
"playlistId" = $PlaylistId
"private" = $false
} | ConvertTo-Json
Write-Host "=== RUN PLAYLIST API CALL ==="
$fullUrl = "$env:TOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/"
Write-Host "Calling: $fullUrl"
$response = Invoke-RestMethod -Uri $fullUrl -Method Post -Headers $headers -Body $body
if ($response.executionId) {
return $response.executionId
} elseif ($response.id) {
return $response.id
} else {
throw "No execution ID returned."
}
}
catch {
Write-Error "Execution failed: $($_.Exception.Message)"
throw
}
}
$executionId = StartPlaylistExecution $accessToken $env:TOSCA_CLOUD_URL $env:PLAYLIST_ID
Write-Host "Execution triggered. ID: $executionId"
# Save execution ID to file for use in subsequent stages
$executionId | Out-File -FilePath "execution_id.txt" -Encoding UTF8
'''
}
}
If the request succeeds, Jenkins saves the execution ID to the execution_id.txt file specified in the request.By default, it stores this file in C:\ProgramData\Jenkins\.jenkins\workspace\<YourProjectName>.テストランのステータスを確認するために、後でこのIDが必要になります。
テストランのステータスを確認する
リクエストを送信し、Jenkinsパイプラインにテストランの現在のステータスを確認させるためには、以下の手順に従ってください。
-
ヘッダーでリクエストを認証します。
Bearer <access_token>のAuthorizationヘッダーを設定します。
application/jsonのContent-Typeヘッダーを設定します。
-
エンドポイントTOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/<executionId>にGETリクエストを送信します。
-
テストランのステータスをポーリングします。最終的なテストランのステータスは、以下のいずれかになります。
-
成功
-
失敗
-
取消
-
リクエストの例:
stage('Wait for Results') {
steps {
powershell '''
# Read token and execution ID from files
$accessToken = Get-Content -Path "access_token.txt" -Raw
$accessToken = $accessToken.Trim()
$executionId = Get-Content -Path "execution_id.txt" -Raw
$executionId = $executionId.Trim()
function WaitForExecution {
param(
[Parameter(Mandatory=$true)][string]$AccessToken,
[Parameter(Mandatory=$true)][string]$TtaUrl,
[Parameter(Mandatory=$true)][string]$ExecutionId,
[int]$TimeoutMinutes = 120,
[int]$PollingIntervalSeconds = 30
)
try {
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
$startTime = Get-Date
$timeoutTime = $startTime.AddMinutes($TimeoutMinutes)
do {
$fullUrl = "$env:TOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/$ExecutionId"
Write-Host "=== PLAYLIST RUN STATUS CHECK API CALL ==="
Write-Host "Calling: $fullUrl"
$response = Invoke-RestMethod -Uri $fullUrl -Method Get -Headers $headers
$status = $response.state
if ($status -eq "Completed" -or $status -eq "Succeeded") {
Write-Host "Execution finished with status: Succeeded"
return "succeeded"
}
if ($status -eq "Failed") {
Write-Host "Execution finished with status: Failed"
return "failed"
}
if ($status -eq "Cancelled" -or $status -eq "Canceled" -or $status -eq "Canceling") {
Write-Host "Execution was cancelled"
return "canceled"
}
if ((Get-Date) -gt $timeoutTime) {
Write-Host "Execution timed out after $TimeoutMinutes minutes"
return $null
}
Write-Host "Execution still running. Waiting $PollingIntervalSeconds seconds before next check..."
Start-Sleep -Seconds $PollingIntervalSeconds
} while ($status -eq "Running" -or $status -eq "Queued" -or $status -eq "Pending" -or $status -eq "Starting")
return $status
}
catch {
Write-Error "Failed to wait for execution: $($_.Exception.Message)"
throw
}
}
$currentState = WaitForExecution $accessToken $env:TOSCA_CLOUD_URL $executionId
if ($currentState -eq $null) {
throw "Execution timed out"
}
if ($currentState -eq 'Canceling' -or $currentState -eq 'Canceled') {
throw "Execution Canceled"
}
Write-Host "Test execution completed with state: $currentState"
# Save test state to file for use in subsequent stages
$currentState | Out-File -FilePath "test_state.txt" -Encoding UTF8
'''
}
}
リクエストが上記の必要なテストランのいずれのステータスも返さない場合、ポーリングは自動的に停止します。
If the request succeeds, Jenkins saves the status to the test_state.txt file specified in the request.By default, it stores this file in C:\ProgramData\Jenkins\.jenkins\workspace\<YourProjectName>.JUnitの結果を取得するために、後で最終ステータスが必要となります。
結果を取得する
Tosca CloudからJenkinsパイプラインがJUnit XML形式でテスト結果を取得するには、次の手順に従います。
-
ヘッダーでリクエストを承認します:
-
Bearer <access_token>のAuthorizationヘッダーを設定します。
-
application/xmlのContent-Type ヘッダーを設定します。
-
-
エンドポイントTOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/<executionId>/junitにGETリクエストを送信します。
リクエストの例:
stage('Get JUnit Results') {
steps {
powershell '''
# Read token and execution ID from files
$accessToken = Get-Content -Path "access_token.txt" -Raw
$accessToken = $accessToken.Trim()
$executionId = Get-Content -Path "execution_id.txt" -Raw
$executionId = $executionId.Trim()
function GetJUnitResults {
param(
[Parameter(Mandatory=$true)][string]$AccessToken,
[Parameter(Mandatory=$true)][string]$TtaUrl,
[Parameter(Mandatory=$true)][string]$ExecutionId
)
try {
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Accept" = "application/xml"
}
$fullUrl = "$env:TOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/$ExecutionId/junit"
Write-Host "=== JUNIT RESULTS API CALL ==="
Write-Host "Calling: $fullUrl"
Write-Host "---------------------------------"
$response = Invoke-RestMethod -Uri $fullUrl -Method Get -Headers $headers
# Save JUnit XML to file
$junitXml = $response.OuterXml
$junitXml | Out-File -FilePath "junit-results.xml" -Encoding UTF8
Write-Host "JUnit results saved to junit-results.xml"
# Parse and display summary
$xmlDoc = [xml]$junitXml
$testsuites = $xmlDoc.testsuites
Write-Host "=== JUNIT RESULTS SUMMARY ==="
Write-Host "Playlist: $($testsuites.name)"
Write-Host "Total Tests: $($testsuites.tests)"
Write-Host "Failures: $($testsuites.failures)"
Write-Host "Errors: $($testsuites.errors)"
Write-Host "Disabled: $($testsuites.disabled)"
Write-Host "---------------------------------"
# Display individual test cases
$testcases = $xmlDoc.SelectNodes("//testcase")
Write-Host "=== INDIVIDUAL TEST CASES RESULT==="
foreach ($testcase in $testcases) {
$status = "Succeeded"
# Check if the testcase has a failure child element
$failureElements = $testcase.SelectNodes("failure")
if ($failureElements.Count -gt 0) {
$status = "Failed"
}
Write-Host "$($testcase.name): $status"
}
return $junitXml
}
catch {
Write-Error "Failed to get JUnit results: $($_.Exception.Message)"
throw
}
}
$junitResults = GetJUnitResults $accessToken $env:TOSCA_CLOUD_URL $executionId
Write-Host "---------------------------------"
Write-Host "JUnit results retrieved successfully"
'''
}
}
}
}
If the request succeeds, Jenkins saves the response to the junit-results.xml file specified in the request.By default, it stores this file in C:\ProgramData\Jenkins\.jenkins\workspace\<YourProjectName>.
成功した応答はテストの実施結果を明確に要約し、Jenkinsパイプラインが結果を視覚的に表示できるようにします。XMLファイルで以下のテスト結果を確認してください。
テストの総数
失敗したテストの数
エラーの数
個別のテストケースの結果
完全なコード例
こちらが、Tosca Cloud プレイリストを実行するためのJenkinsパイプラインを設定するのに役立つ完全なコードの例です。
pipeline{
agent any
environment {
CLIENT_ID = 'Tricentis_Cloud_API'
CLIENT_SECRET = '<client secret for Tricentis_Cloud_API>'
E2G_SCOPE = 'tta'
E2G_AUTH_URL = '<Token_url>'
TOSCA_CLOUD_URL = '<Your tenant url including the workspace>'
PLAYLIST_ID = '<Your playlist id>'
}
stages {
stage('Get Token') {
steps {
powershell '''
$headers = @{
"Content-Type" = "application/x-www-form-urlencoded"
}
$Body = "client_id=$env:CLIENT_ID&client_secret=$env:CLIENT_SECRET&scope=$env:E2G_SCOPE&grant_type=client_credentials"
$maxRetries = 3
$retryCount = 0
$success = $false
do {
try {
Write-Host "=== TOKEN ACQUISITION API CALL ==="
$response = Invoke-RestMethod -Uri "$env:E2G_AUTH_URL" -Method "Post" -Headers $headers -Body $Body
$accessToken = $response.access_token
$success = $true
Write-Host "Token acquired successfully."
}
catch {
$retryCount++
Write-Host "Token acquisition failed (attempt $retryCount of $maxRetries): $($_.Exception.Message)"
if ($retryCount -lt $maxRetries) {
Start-Sleep -Seconds 5
}
}
} while (-not $success -and $retryCount -lt $maxRetries)
if (-not $success) {
throw "Failed to acquire token after $maxRetries attempts"
}
# Save token to file for use in subsequent stages
$accessToken | Out-File -FilePath "access_token.txt" -Encoding UTF8
'''
}
}
stage('Run Tests') {
steps {
powershell '''
$accessToken = Get-Content -Path "access_token.txt" -Raw
$accessToken = $accessToken.Trim()
function StartPlaylistExecution {
param(
[string]$AccessToken,
[string]$TtaUrl,
[string]$PlaylistId
)
try {
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
"Accept" = "application/json"
}
$body = @{
"playlistId" = $PlaylistId
"private" = $false
} | ConvertTo-Json
Write-Host "=== RUN PLAYLIST API CALL ==="
$fullUrl = "$env:TOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/"
Write-Host "Calling: $fullUrl"
$response = Invoke-RestMethod -Uri $fullUrl -Method Post -Headers $headers -Body $body
if ($response.executionId) {
return $response.executionId
} elseif ($response.id) {
return $response.id
} else {
throw "No execution ID returned."
}
}
catch {
Write-Error "Execution failed: $($_.Exception.Message)"
throw
}
}
$executionId = StartPlaylistExecution $accessToken $env:TOSCA_CLOUD_URL $env:PLAYLIST_ID
Write-Host "Execution triggered. ID: $executionId"
# Save execution ID to file for use in subsequent stages
$executionId | Out-File -FilePath "execution_id.txt" -Encoding UTF8
'''
}
}
stage('Wait for Results') {
steps {
powershell '''
# Read token and execution ID from files
$accessToken = Get-Content -Path "access_token.txt" -Raw
$accessToken = $accessToken.Trim()
$executionId = Get-Content -Path "execution_id.txt" -Raw
$executionId = $executionId.Trim()
function WaitForExecution {
param(
[Parameter(Mandatory=$true)][string]$AccessToken,
[Parameter(Mandatory=$true)][string]$TtaUrl,
[Parameter(Mandatory=$true)][string]$ExecutionId,
[int]$TimeoutMinutes = 120,
[int]$PollingIntervalSeconds = 30
)
try {
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
$startTime = Get-Date
$timeoutTime = $startTime.AddMinutes($TimeoutMinutes)
do {
$fullUrl = "$env:TOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/$ExecutionId"
Write-Host "=== PLAYLIST RUN STATUS CHECK API CALL ==="
Write-Host "Calling: $fullUrl"
$response = Invoke-RestMethod -Uri $fullUrl -Method Get -Headers $headers
$status = $response.state
if ($status -eq "Completed" -or $status -eq "Succeeded") {
Write-Host "Execution finished with status: Succeeded"
return "succeeded"
}
if ($status -eq "Failed") {
Write-Host "Execution finished with status: Failed"
return "failed"
}
if ($status -eq "Cancelled" -or $status -eq "Canceled" -or $status -eq "Canceling") {
Write-Host "Execution was cancelled"
return "canceled"
}
if ((Get-Date) -gt $timeoutTime) {
Write-Host "Execution timed out after $TimeoutMinutes minutes"
return $null
}
Write-Host "Execution still running. Waiting $PollingIntervalSeconds seconds before next check..."
Start-Sleep -Seconds $PollingIntervalSeconds
} while ($status -eq "Running" -or $status -eq "Queued" -or $status -eq "Pending" -or $status -eq "Starting")
return $status
}
catch {
Write-Error "Failed to wait for execution: $($_.Exception.Message)"
throw
}
}
$currentState = WaitForExecution $accessToken $env:TOSCA_CLOUD_URL $executionId
if ($currentState -eq $null) {
throw "Execution timed out"
}
if ($currentState -eq 'Canceling' -or $currentState -eq 'Canceled') {
throw "Execution Canceled"
}
Write-Host "Test execution completed with state: $currentState"
# Save test state to file for use in subsequent stages
$currentState | Out-File -FilePath "test_state.txt" -Encoding UTF8
'''
}
}
stage('Get JUnit Results') {
steps {
powershell '''
# Read token and execution ID from files
$accessToken = Get-Content -Path "access_token.txt" -Raw
$accessToken = $accessToken.Trim()
$executionId = Get-Content -Path "execution_id.txt" -Raw
$executionId = $executionId.Trim()
function GetJUnitResults {
param(
[Parameter(Mandatory=$true)][string]$AccessToken,
[Parameter(Mandatory=$true)][string]$TtaUrl,
[Parameter(Mandatory=$true)][string]$ExecutionId
)
try {
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Accept" = "application/xml"
}
$fullUrl = "$env:TOSCA_CLOUD_URL/_playlists/api/v2/playlistRuns/$ExecutionId/junit"
Write-Host "=== JUNIT RESULTS API CALL ==="
Write-Host "Calling: $fullUrl"
Write-Host "---------------------------------"
$response = Invoke-RestMethod -Uri $fullUrl -Method Get -Headers $headers
# Save JUnit XML to file
$junitXml = $response.OuterXml
$junitXml | Out-File -FilePath "junit-results.xml" -Encoding UTF8
Write-Host "JUnit results saved to junit-results.xml"
# Parse and display summary
$xmlDoc = [xml]$junitXml
$testsuites = $xmlDoc.testsuites
Write-Host "=== JUNIT RESULTS SUMMARY ==="
Write-Host "Playlist: $($testsuites.name)"
Write-Host "Total Tests: $($testsuites.tests)"
Write-Host "Failures: $($testsuites.failures)"
Write-Host "Errors: $($testsuites.errors)"
Write-Host "Disabled: $($testsuites.disabled)"
Write-Host "---------------------------------"
# Display individual test cases
$testcases = $xmlDoc.SelectNodes("//testcase")
Write-Host "=== INDIVIDUAL TEST CASES RESULT==="
foreach ($testcase in $testcases) {
$status = "Succeeded"
# Check if the testcase has a failure child element
$failureElements = $testcase.SelectNodes("failure")
if ($failureElements.Count -gt 0) {
$status = "Failed"
}
Write-Host "$($testcase.name): $status"
}
return $junitXml
}
catch {
Write-Error "Failed to get JUnit results: $($_.Exception.Message)"
throw
}
}
$junitResults = GetJUnitResults $accessToken $env:TOSCA_CLOUD_URL $executionId
Write-Host "---------------------------------"
Write-Host "JUnit results retrieved successfully"
'''
}
}
}
}