Two GitHub Actions workflows connect your repository to Validatar through its REST API: one promotes tests and jobs from a source project to a target project, and one runs a Validatar job as a pull request check that fails when any test in the job does not pass. Both call Python scripts you commit to the repository.
Prerequisites
- A Validatar user token with the Authoring and Execution scopes. In Validatar, click the user icon in the top right, choose User Profile, open Tokens and select New Token, with Type set to API. See User Tokens. Authoring needs the full API add-on; without it a token can only have the Execution scope, which is enough for the quality gate alone.
- Project permissions for the token's user: Export on the source project and Import on the target project.
- Project, folder, job and data source ids. CI/CD Pipeline Integrations shows where to find them.
- A runner that can reach Validatar. GitHub-hosted runners reach Validatar Cloud. For Validatar Server behind a firewall, use a self-hosted runner with network access to your server.
Step 1: Store the connection details as secrets
In your repository, open Settings > Secrets and variables > Actions and add:
| Secret | Value |
|---|---|
VALIDATAR_API_TOKEN |
Your Validatar user token |
SOURCE_VALIDATAR_API_URL |
Source instance address, such as https://dev.cloud.validatar.com (no /core, no trailing slash) |
TARGET_VALIDATAR_API_URL |
Target instance address, such as https://prod.cloud.validatar.com |
When the source and target are two projects on the same instance, set both URL secrets to the same address.
Step 2: Add the scripts
scripts/validatar_promote.py
"""Promote Validatar tests and jobs from a source project to a target project.
Exports the chosen test and job folders from the source project through the
Authoring API, then imports the file into the target project with Overwrite.
Source and target can be two projects on one instance or on two instances.
Environment variables:
SOURCE_VALIDATAR_API_URL source instance, e.g. https://dev.cloud.validatar.com
TARGET_VALIDATAR_API_URL target instance (same value for two projects on one instance)
SOURCE_VALIDATAR_API_TOKEN token for the source (or set VALIDATAR_API_TOKEN for both)
TARGET_VALIDATAR_API_TOKEN token for the target (or set VALIDATAR_API_TOKEN for both)
SOURCE_PROJECT_ID, TARGET_PROJECT_ID
EXPORT_TEST_FOLDER_IDS test folder ids to export, comma-separated
EXPORT_JOB_FOLDER_IDS job folder ids to export, comma-separated
DATA_SOURCE_MAPPINGS source_id:target_id pairs, comma-separated, e.g. 42:87,43:88
TARGET_TEST_FOLDER_ID optional: folder that receives the tests
TARGET_JOB_FOLDER_ID optional: folder that receives the jobs
SAVE_EXPORT_FILE optional: "true" writes the export to validatar-export.xml
Requirements: pip install requests
"""
import base64
import os
import sys
import requests
def api_root(url):
"""The v1 REST root for an instance address such as https://acme.cloud.validatar.com."""
return f"{url.rstrip('/')}/core/api/v1"
def token(side):
"""SOURCE_ or TARGET_VALIDATAR_API_TOKEN, falling back to VALIDATAR_API_TOKEN."""
return os.environ.get(f"{side}_VALIDATAR_API_TOKEN") or os.environ["VALIDATAR_API_TOKEN"]
def headers(side):
return {"x-val-api-token": token(side), "Accept": "application/json"}
def id_list(name):
"""Comma-separated ids from an environment variable, as a list of ints."""
return [int(x) for x in os.environ.get(name, "").split(",") if x.strip()]
def data_source_mappings(raw):
"""'42:87,43:88' -> [{"sourceFileKey": "42", "targetId": 87}, ...]"""
mappings = []
for pair in (p.strip() for p in raw.split(",")):
if pair:
source_id, target_id = pair.split(":")
mappings.append({"sourceFileKey": source_id.strip(), "targetId": int(target_id)})
return mappings
source_api = api_root(os.environ["SOURCE_VALIDATAR_API_URL"])
target_api = api_root(os.environ["TARGET_VALIDATAR_API_URL"])
source_project = int(os.environ["SOURCE_PROJECT_ID"])
target_project = int(os.environ["TARGET_PROJECT_ID"])
# ---------------------------------------------------------------------------
# Step 1: export from the source project
# ---------------------------------------------------------------------------
export_body = {
"name": "ci-cd-export",
"description": "Automated export from a CI/CD pipeline",
"testFolderIds": id_list("EXPORT_TEST_FOLDER_IDS"),
"jobFolderIds": id_list("EXPORT_JOB_FOLDER_IDS"),
"includeCustomFields": True,
"includeJobSchedules": False, # schedules belong to each environment
}
print(f"Exporting from project {source_project}: test folders {export_body['testFolderIds']}, "
f"job folders {export_body['jobFolderIds']}")
response = requests.post(f"{source_api}/Authoring/projects/{source_project}/export",
headers=headers("SOURCE"), json=export_body, timeout=300)
if response.status_code != 200:
sys.exit(f"Export failed: HTTP {response.status_code} {response.text[:1000]}")
export = response.json()
print(f"Exported {export['fileName']}")
if os.environ.get("SAVE_EXPORT_FILE", "").lower() == "true":
with open("validatar-export.xml", "wb") as f:
f.write(base64.b64decode(export["contentBase64"]))
print("Saved validatar-export.xml")
# ---------------------------------------------------------------------------
# Step 2: import into the target project
# ---------------------------------------------------------------------------
import_body = {
"mimeType": "application/xml",
"contentBase64": export["contentBase64"],
"dataSourceMappings": data_source_mappings(os.environ.get("DATA_SOURCE_MAPPINGS", "")),
"includeJobSchedules": False, # the import default is true
"conflictResolution": "Overwrite",
}
if os.environ.get("TARGET_TEST_FOLDER_ID"):
import_body["targetTestFolderId"] = int(os.environ["TARGET_TEST_FOLDER_ID"])
if os.environ.get("TARGET_JOB_FOLDER_ID"):
import_body["targetJobFolderId"] = int(os.environ["TARGET_JOB_FOLDER_ID"])
print(f"Importing into project {target_project} with "
f"{len(import_body['dataSourceMappings'])} data source mapping(s)")
response = requests.post(f"{target_api}/Authoring/projects/{target_project}/import",
headers=headers("TARGET"), json=import_body, timeout=300)
if response.status_code == 200:
print("Import succeeded.")
sys.exit(0)
print(f"Import failed: HTTP {response.status_code}")
try:
errors = response.json()
except ValueError:
sys.exit(response.text[:1000])
# Each non-empty list names one kind of problem: validationErrors, invalidDataSources,
# invalidMacros, missingReferences, missingProfileDefs, missingMetaObjects,
# missingCustomFields, commitErrors.
for kind, items in errors.items():
for item in items or []:
print(f" {kind}: {item}")
sys.exit(1)
scripts/validatar_quality_gate.py
"""Run a Validatar job and fail unless every test in it passes.
Starts the job through the Execution API, polls the job's results until the
run finishes, then exits 0 when every test passed and 1 otherwise.
Environment variables:
VALIDATAR_API_URL instance address, e.g. https://acme.cloud.validatar.com
VALIDATAR_API_TOKEN user token with the Execution scope
VALIDATAR_PROJECT_ID
VALIDATAR_JOB_ID
VALIDATAR_TIMEOUT seconds to wait for the run, default 1800
Requirements: pip install requests
"""
import os
import sys
import time
import requests
API = f"{os.environ['VALIDATAR_API_URL'].rstrip('/')}/core/api/v1"
HEADERS = {"x-val-api-token": os.environ["VALIDATAR_API_TOKEN"], "Accept": "application/json"}
PROJECT_ID = int(os.environ["VALIDATAR_PROJECT_ID"])
JOB_ID = int(os.environ["VALIDATAR_JOB_ID"])
TIMEOUT_SECONDS = int(os.environ.get("VALIDATAR_TIMEOUT", "1800"))
POLL_SECONDS = 5
FINISHED = ("Completed", "Aborted", "Abandoned")
# ---------------------------------------------------------------------------
# Step 1: start the job
# ---------------------------------------------------------------------------
response = requests.post(f"{API}/Execution/projects/{PROJECT_ID}/jobs/{JOB_ID}/execute",
headers=HEADERS, timeout=60)
if response.status_code != 200:
sys.exit(f"Execute failed: HTTP {response.status_code} {response.text[:500]}")
run = response.json()
print(f"Started job {JOB_ID} ({run.get('name')}): batch {run.get('batchId')}, "
f"execution key {run['executionKey']}")
# ---------------------------------------------------------------------------
# Step 2: poll until the run finishes
# ---------------------------------------------------------------------------
results_url = f"{API}/Execution/projects/{PROJECT_ID}/jobs/{JOB_ID}/results/{run['executionKey']}"
deadline = time.monotonic() + TIMEOUT_SECONDS
summary = {}
while time.monotonic() < deadline:
time.sleep(POLL_SECONDS)
try:
poll = requests.get(results_url, headers=HEADERS, timeout=60)
except requests.RequestException as error:
print(f" poll error, retrying: {error}")
continue
if poll.status_code != 200: # the run may not be recorded yet
print(f" poll returned HTTP {poll.status_code}, retrying")
continue
summary = poll.json()
print(f" status: {summary.get('status')}")
if summary.get("status") in FINISHED:
break
else:
sys.exit(f"Timed out after {TIMEOUT_SECONDS}s. The job may still be running in Validatar.")
# ---------------------------------------------------------------------------
# Step 3: fail unless every test in the run passed
# ---------------------------------------------------------------------------
if summary["status"] != "Completed":
sys.exit(f"FAILED: the job ended with status {summary['status']}.")
tests = summary.get("tests", [])
for t in tests:
print(f" [{t.get('status')}] {t.get('name')} (test {t.get('id')})")
not_passed = [t for t in tests if t.get("status") != "Passed"]
if not tests:
sys.exit("FAILED: the job ran no tests. Check the job's steps.")
if not_passed:
sys.exit(f"FAILED: {len(not_passed)} of {len(tests)} test(s) did not pass.")
print(f"PASSED: all {len(tests)} test(s) passed.")
Each test in the job summary has a status of Passed, Failed or Error. The gate treats anything other than Passed as a failure.
Step 3: Add the workflows
Promote tests on demand
Create .github/workflows/validatar-promote.yml:
name: Promote Validatar tests
on:
workflow_dispatch:
inputs:
source_project_id:
description: "Source Validatar project ID"
required: true
type: string
target_project_id:
description: "Target Validatar project ID"
required: true
type: string
test_folder_ids:
description: "Test folder IDs to export (comma-separated)"
required: false
type: string
default: ""
job_folder_ids:
description: "Job folder IDs to export (comma-separated)"
required: false
type: string
default: ""
data_source_mappings:
description: "Data source mappings (source_id:target_id, comma-separated)"
required: false
type: string
default: ""
jobs:
promote:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install requests
- name: Export from source and import into target
env:
SOURCE_VALIDATAR_API_URL: ${{ secrets.SOURCE_VALIDATAR_API_URL }}
TARGET_VALIDATAR_API_URL: ${{ secrets.TARGET_VALIDATAR_API_URL }}
VALIDATAR_API_TOKEN: ${{ secrets.VALIDATAR_API_TOKEN }}
SOURCE_PROJECT_ID: ${{ inputs.source_project_id }}
TARGET_PROJECT_ID: ${{ inputs.target_project_id }}
EXPORT_TEST_FOLDER_IDS: ${{ inputs.test_folder_ids }}
EXPORT_JOB_FOLDER_IDS: ${{ inputs.job_folder_ids }}
DATA_SOURCE_MAPPINGS: ${{ inputs.data_source_mappings }}
run: python scripts/validatar_promote.py
To promote automatically on every merge to main, replace the on: block with the one below, and set the project ids, folder ids and mappings as repository variables (vars.*) instead of inputs:
on:
push:
branches: [main]
For PowerShell runners, the export and import script in Run Validatar tests from any CI/CD tool runs in a step with shell: pwsh and the same environment variables.
Run a job as a pull request check
Create .github/workflows/validatar-quality-gate.yml:
name: Validatar quality gate
on:
pull_request:
branches: [main]
workflow_dispatch:
inputs:
project_id:
description: "Validatar project ID"
required: true
type: string
job_id:
description: "Validatar job ID to run"
required: true
type: string
jobs:
quality-gate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install requests
- name: Run the Validatar job
env:
VALIDATAR_API_URL: ${{ secrets.SOURCE_VALIDATAR_API_URL }}
VALIDATAR_API_TOKEN: ${{ secrets.VALIDATAR_API_TOKEN }}
VALIDATAR_PROJECT_ID: ${{ inputs.project_id || vars.VALIDATAR_PROJECT_ID }}
VALIDATAR_JOB_ID: ${{ inputs.job_id || vars.VALIDATAR_JOB_ID }}
run: python scripts/validatar_quality_gate.py
> Tip: Store the default VALIDATAR_PROJECT_ID and VALIDATAR_JOB_ID as repository variables (not secrets) under Settings > Secrets and variables > Actions > Variables, so the pull_request trigger has them without manual input.
Step 4: Run a workflow
- Open Actions in your GitHub repository.
- Select the workflow, for example Promote Validatar tests.
- Click Run workflow.
- Fill in the project ids, folder ids and data source mappings.
- Click Run workflow again to start it.
The quality gate also runs on its own for every pull request into main.
Check that it worked
- Promotion. The step log ends with
Import succeeded.Open the target project in Validatar: the exported folders are there, under the target folder if you set one. - Quality gate. The step log prints
Started job ... batch <id>, one line per test, andPASSED: all N test(s) passed.To see the same run in Validatar, openhttps://<your-instance>.cloud.validatar.com/projects/<project id>/results/<batch id>. When a test fails, the step exits with code 1 and the pull request check turns red.
Troubleshooting
HTTP 404 on every call
- The secret holds the wrong address. Use the address you open Validatar with, such as
https://acme.cloud.validatar.com, without/coreand without a trailing slash. The scripts add/core/api/v1/<scope>/.
HTTP 401 or 403
- Check that the
VALIDATAR_API_TOKENsecret holds the whole token. - Confirm the token has the scopes the call needs: Authoring for export and import, Execution for the quality gate.
- Check that the token's user can open the projects, with the Export permission on the source and Import on the target.
Import fails with invalidDataSources
- Run the data source listing script in Run Validatar tests from any CI/CD tool against both instances.
- Add a mapping for every data source the exported tests use.
sourceFileKeyis the source data source id written as a string.
The quality gate never gets the secrets
- Workflows triggered by pull requests from forks do not receive repository secrets, so the gate cannot call Validatar for them. Run it on branches in the same repository, or start it with Run workflow.
The self-hosted runner cannot reach Validatar
- Confirm the runner has network access to the Validatar address, including firewall and proxy rules.
The quality gate times out
- Raise
VALIDATAR_TIMEOUTin the step'senvif the job runs longer than 30 minutes. - Open the job in Validatar to see whether the run is still going or stuck.