0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Tosca Cloud APIを使ってCI/CDパイプラインからテストを実行

Posted at

Tosca Cloud APIを使ってCI/CDパイプラインからテストを実行してみた

背景

Tricentis Toscaは、GUIテストやAPIテストを中心にしたエンタープライズ向けテスト自動化ツールです。
Tosca Cloudでは、テストの実行や結果取得を「Public API」経由で自動化できます。

このAPIを利用すれば、GitHub ActionsやAzure DevOps, JenkinsなどのCI/CDパイプラインから
テスト自動実行結果収集成果判定(JUnit形式) を一連で行うことが可能になります。

本記事では、Tricentisの公式ドキュメントに掲載されている
Tosca Cloud Public API
を利用し、PythonでPlaylist実行を自動化するサンプルを紹介します。


🧩 構成概要

今回紹介するサンプルでは、以下の流れでTosca Cloud上のテストをトリガーします。

① Okta経由でAccess Token取得
② Tosca Cloud APIでPlaylist実行をトリガー
③ 実行ステータスをポーリングで監視
④ 実行完了後、JUnitレポートを取得
⑤ CI/CD側で成否を判定

⚙️ 必要な準備

1. Tosca Cloud側の設定

Tosca Cloud環境のTenant URLを確認
Workspace IDとPlaylist IDを取得
Oktaに登録されたClient ID/Client Secretを発行(Service Account用)

Workspace ID は管理者にてログインしてSetting 画面からWorkspacesを選択すれば確認可能です。
image.png

PlaylistはAPIから確認も可能ですがPlaylist編集画面のURLからも簡単に確認可能です。
image.png

2. .env ファイルの準備

ローカルに以下のような .env ファイルを作成します。

OKTA_DOMAIN=https://<your-okta-domain>
OKTA_CLIENT_ID=<client_id>
OKTA_CLIENT_SECRET=<client_secret>
TOSCA_CLOUD_TENANT=https://<your-tenant>.tricentiscloud.com
WORKSPACE_ID=<workspace_id>

Pythonサンプルコード

以下のサンプルを Tosca_cloud_JapanDemo.py として保存し、実行します。
(※公式APIドキュメントのエンドポイント仕様を踏まえた再現コード)

#!/usr/bin/env python3
import os
import sys
import requests
import time
import json
from requests.auth import HTTPBasicAuth
from dotenv import load_dotenv

# ── Load .env configuration ──────────────────────────────────────────────
load_dotenv()

OKTA_DOMAIN        = os.getenv("OKTA_DOMAIN")
CLIENT_ID          = os.getenv("OKTA_CLIENT_ID")
CLIENT_SECRET      = os.getenv("OKTA_CLIENT_SECRET")
SCOPE              = os.getenv("OKTA_SCOPE", "tta")
TOSCA_CLOUD_TENANT = os.getenv("TOSCA_CLOUD_TENANT")
WORKSPACE_ID       = os.getenv("WORKSPACE_ID")
# ── Load .env configuration ──────────────────────────────────────────────

# ── PlaylistID指定 ──────────────────────────────────────────────
PLAYLIST_ID_DEMO   = "XXXXX"

TOKEN_URL = f"{OKTA_DOMAIN.rstrip('/')}/oauth2/default/v1/token"
PLAYLIST_RUNS_URL = f"{TOSCA_CLOUD_TENANT.rstrip('/')}/{WORKSPACE_ID}/_playlists/api/v2/playlistRuns"

def get_service_token() -> str:
    resp = requests.post(
        TOKEN_URL,
        auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET),
        data={"grant_type": "client_credentials", "scope": SCOPE},
        headers={"Accept": "application/json"}
    )
    if not resp.ok:
        print(f"❌ Token request failed: {resp.status_code}")
        print(resp.text)
        sys.exit(1)
    return resp.json()["access_token"]

def trigger_playlist_run(token: str, playlist_id: str, private=False) -> dict:
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    payload = {"playlistId": playlist_id, "private": private}
    resp = requests.post(PLAYLIST_RUNS_URL, json=payload, headers=headers)
    if not resp.ok:
        print(f"❌ Run trigger failed: {resp.text}")
        sys.exit(1)
    return resp.json()

def get_run_info(token: str, run_id: str) -> dict:
    url = f"{PLAYLIST_RUNS_URL}/{run_id}"
    headers = {"Authorization": f"Bearer {token}"}
    resp = requests.get(url, headers=headers)
    return resp.json()

def get_run_junit(token: str, run_id: str) -> str:
    url = f"{PLAYLIST_RUNS_URL}/{run_id}/junit"
    headers = {"Authorization": f"Bearer {token}"}
    resp = requests.get(url, headers=headers)
    return resp.text

if __name__ == "__main__":
    token = get_service_token()
    print("Token acquired")

    run = trigger_playlist_run(token, PLAYLIST_ID_DEMO)
    run_id = run["id"]
    print(f"Triggered run ID: {run_id}")

    print("Waiting for run to complete ...")
    while True:
        info = get_run_info(token, run_id)
        if info["state"] != "running":
            break
        time.sleep(15)

    print(f"Run completed with state: {info['state']}")
    junit = get_run_junit(token, run_id)
    print(junit)

🔄 CI/CDとの統合イメージ

このPythonスクリプトは、以下のように簡単にCI/CDジョブへ組み込めます。

✅ GitHub Actions例

name: Run Tosca Cloud Playlist
on:
  workflow_dispatch:

jobs:
  run-tosca:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: 3.11

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Run Tosca Cloud playlist
        env:
          OKTA_DOMAIN: ${{ secrets.OKTA_DOMAIN }}
          OKTA_CLIENT_ID: ${{ secrets.OKTA_CLIENT_ID }}
          OKTA_CLIENT_SECRET: ${{ secrets.OKTA_CLIENT_SECRET }}
          TOSCA_CLOUD_TENANT: ${{ secrets.TOSCA_CLOUD_TENANT }}
          WORKSPACE_ID: ${{ secrets.WORKSPACE_ID }}
        run: python Tosca_cloud_JapanDemo.py

これにより、CI/CD上でPlaylistが実行され、JUnit結果がテストレポートとして取り込めます。

🧩 APIの参考リンク

💡 まとめ

項目 内容
利用API Tosca Cloud Playlist API
トークン管理 OktaのClient Credentials Flow
実行結果取得 /playlistRuns/{id} & /playlistRuns/{id}/junit
CI/CD統合 Python + GitHub Actions等で容易に実現可能

Tosca Cloud APIを活用することで、GUIに依存せずにテストを自動実行できるようになります。
CI/CDと品質保証の自動化を進めたいチームには特におすすめです。


📘 参考

本記事はマニュアルの内容を基に作成しました。内容は検証済みですが、環境により挙動が異なる場合があります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?