Run Validatar tests from any CI/CD tool

Prev Next

Any CI/CD tool that can run a script can promote Validatar tests and jobs from one project to another and then run them as a gate. This page has the promotion script in Python, PowerShell and Bash, a helper that lists data source ids for the mapping, and notes for running them in Jenkins, GitLab CI, CircleCI, Azure DevOps and other tools. To run a job after the import and fail the build when its tests do not pass, use the scripts in Run Validatar jobs from any orchestrator over REST.

Prerequisites

  • A Validatar user token with the Authoring scope, plus Execution if the pipeline also runs tests. 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.
  • Project permissions for the token's user: Export on the source project and Import on the target project.
  • Network access from your CI/CD runner to the Validatar address.
  • Project, folder and data source ids. CI/CD Pipeline Integrations shows where to find them and documents every field the scripts send.

All three scripts read the same environment variables:

Variable Value
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. Use the same value for two projects on one instance.
SOURCE_VALIDATAR_API_TOKEN, TARGET_VALIDATAR_API_TOKEN Tokens for each side. Set VALIDATAR_API_TOKEN instead when one token covers both.
SOURCE_PROJECT_ID, TARGET_PROJECT_ID Project ids
EXPORT_TEST_FOLDER_IDS, EXPORT_JOB_FOLDER_IDS Folder ids to export, comma-separated
DATA_SOURCE_MAPPINGS source_id:target_id pairs, comma-separated, such as 42:87,43:88
TARGET_TEST_FOLDER_ID, TARGET_JOB_FOLDER_ID Optional: folders that receive the imported tests and jobs
SAVE_EXPORT_FILE Optional: true writes the export to validatar-export.xml (Python and PowerShell)

Export and import (Python)

Save as validatar_promote.py and run it with python validatar_promote.py after pip install requests.

"""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)

Export and import (PowerShell)

Save as validatar-promote.ps1 and run it with pwsh -File validatar-promote.ps1 (or powershell -File on Windows PowerShell 5.1).

<#
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.
Reads the same environment variables as validatar_promote.py.
Works in Windows PowerShell 5.1 and PowerShell 7.
#>
$ErrorActionPreference = "Stop"
if ($PSVersionTable.PSVersion.Major -le 5) {
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}

function Get-ApiRoot([string]$Url) { "$($Url.TrimEnd('/'))/core/api/v1" }

function Get-Token([string]$Side) {
    $Value = [Environment]::GetEnvironmentVariable("$($Side)_VALIDATAR_API_TOKEN")
    if ($Value) { $Value } else { $env:VALIDATAR_API_TOKEN }
}

function Get-IdList([string]$Value) {
    $Value -split "," | Where-Object { $_.Trim() } | ForEach-Object { [int]$_.Trim() }
}

$SourceApi       = Get-ApiRoot $env:SOURCE_VALIDATAR_API_URL
$TargetApi       = Get-ApiRoot $env:TARGET_VALIDATAR_API_URL
$SourceProjectId = [int]$env:SOURCE_PROJECT_ID
$TargetProjectId = [int]$env:TARGET_PROJECT_ID

# @() keeps a single id or mapping as an array, so the JSON body gets [5] and not 5
$Mappings = @(
    $env:DATA_SOURCE_MAPPINGS -split "," | Where-Object { $_.Trim() } | ForEach-Object {
        $Pair = $_.Trim() -split ":"
        @{ sourceFileKey = $Pair[0].Trim(); targetId = [int]$Pair[1] }
    }
)

# ---------------------------------------------------------------------------
# Step 1: export from the source project
# ---------------------------------------------------------------------------
$ExportBody = @{
    name                = "ci-cd-export"
    description         = "Automated export from a CI/CD pipeline"
    testFolderIds       = @(Get-IdList $env:EXPORT_TEST_FOLDER_IDS)
    jobFolderIds        = @(Get-IdList $env:EXPORT_JOB_FOLDER_IDS)
    includeCustomFields = $true
    includeJobSchedules = $false   # schedules belong to each environment
} | ConvertTo-Json -Depth 5

Write-Host "Exporting from project $SourceProjectId..."
try {
    $Export = Invoke-RestMethod -Method Post -Uri "$SourceApi/Authoring/projects/$SourceProjectId/export" `
        -Headers @{ "x-val-api-token" = (Get-Token "SOURCE") } -ContentType "application/json" -Body $ExportBody
}
catch {
    Write-Host "Export failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
    exit 1
}
Write-Host "Exported $($Export.fileName)"

if ($env:SAVE_EXPORT_FILE -eq "true") {
    $Path = Join-Path (Get-Location) "validatar-export.xml"
    [System.IO.File]::WriteAllBytes($Path, [Convert]::FromBase64String($Export.contentBase64))
    Write-Host "Saved $Path"
}

# ---------------------------------------------------------------------------
# Step 2: import into the target project
# ---------------------------------------------------------------------------
$ImportBody = @{
    mimeType            = "application/xml"
    contentBase64       = $Export.contentBase64
    dataSourceMappings  = $Mappings
    includeJobSchedules = $false   # the import default is true
    conflictResolution  = "Overwrite"
}
if ($env:TARGET_TEST_FOLDER_ID) { $ImportBody.targetTestFolderId = [int]$env:TARGET_TEST_FOLDER_ID }
if ($env:TARGET_JOB_FOLDER_ID)  { $ImportBody.targetJobFolderId  = [int]$env:TARGET_JOB_FOLDER_ID }

Write-Host "Importing into project $TargetProjectId with $($Mappings.Count) data source mapping(s)..."
try {
    Invoke-RestMethod -Method Post -Uri "$TargetApi/Authoring/projects/$TargetProjectId/import" `
        -Headers @{ "x-val-api-token" = (Get-Token "TARGET") } -ContentType "application/json" `
        -Body ($ImportBody | ConvertTo-Json -Depth 5) | Out-Null
    Write-Host "Import succeeded."
    exit 0
}
catch {
    Write-Host "Import failed: $($_.Exception.Message)"
    # The HTTP 400 body lists the problems: validationErrors, invalidDataSources,
    # invalidMacros, missingReferences, missingCustomFields, commitErrors and others.
    if ($_.ErrorDetails.Message) { Write-Host $_.ErrorDetails.Message }
    exit 1
}

Export and import (Bash)

Save as validatar-promote.sh. It needs curl and python3, which it uses to read and build JSON.

#!/usr/bin/env bash
# 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.
# Reads the same environment variables as validatar_promote.py.
# Needs curl and python3.
set -euo pipefail

SOURCE_URL="${SOURCE_VALIDATAR_API_URL:?Set SOURCE_VALIDATAR_API_URL}"
TARGET_URL="${TARGET_VALIDATAR_API_URL:?Set TARGET_VALIDATAR_API_URL}"
SOURCE_API="${SOURCE_URL%/}/core/api/v1"
TARGET_API="${TARGET_URL%/}/core/api/v1"
SOURCE_TOKEN="${SOURCE_VALIDATAR_API_TOKEN:-${VALIDATAR_API_TOKEN:?Set VALIDATAR_API_TOKEN}}"
TARGET_TOKEN="${TARGET_VALIDATAR_API_TOKEN:-${VALIDATAR_API_TOKEN:?Set VALIDATAR_API_TOKEN}}"
SOURCE_PROJECT_ID="${SOURCE_PROJECT_ID:?Set SOURCE_PROJECT_ID}"
TARGET_PROJECT_ID="${TARGET_PROJECT_ID:?Set TARGET_PROJECT_ID}"

WORK_DIR=$(mktemp -d)
trap 'rm -rf "$WORK_DIR"' EXIT

# ---------------------------------------------------------------------------
# Step 1: export from the source project
# ---------------------------------------------------------------------------
# Comma-separated ids are valid JSON array contents: "101,102" -> [101,102]
EXPORT_BODY=$(cat <<JSON
{
  "name": "ci-cd-export",
  "description": "Automated export from a CI/CD pipeline",
  "testFolderIds": [${EXPORT_TEST_FOLDER_IDS:-}],
  "jobFolderIds": [${EXPORT_JOB_FOLDER_IDS:-}],
  "includeCustomFields": true,
  "includeJobSchedules": false
}
JSON
)

echo "Exporting from project ${SOURCE_PROJECT_ID}..."
HTTP_CODE=$(curl -s -o "$WORK_DIR/export.json" -w "%{http_code}" -X POST \
  "${SOURCE_API}/Authoring/projects/${SOURCE_PROJECT_ID}/export" \
  -H "x-val-api-token: ${SOURCE_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${EXPORT_BODY}")
if [ "$HTTP_CODE" != "200" ]; then
  echo "Export failed: HTTP ${HTTP_CODE}"
  cat "$WORK_DIR/export.json"; echo
  exit 1
fi

# ---------------------------------------------------------------------------
# Step 2: build the import body in a file (an export can be larger than a
# single command-line argument allows), then import into the target project
# ---------------------------------------------------------------------------
python3 - "$WORK_DIR/export.json" "$WORK_DIR/import.json" <<'PY'
import json, os, sys
export = json.load(open(sys.argv[1]))
pairs = [p.strip() for p in os.environ.get("DATA_SOURCE_MAPPINGS", "").split(",") if p.strip()]
body = {
    "mimeType": "application/xml",
    "contentBase64": export["contentBase64"],
    "dataSourceMappings": [
        {"sourceFileKey": p.split(":")[0].strip(), "targetId": int(p.split(":")[1])} for p in pairs
    ],
    "includeJobSchedules": False,  # the import default is true
    "conflictResolution": "Overwrite",
}
for var, field in (("TARGET_TEST_FOLDER_ID", "targetTestFolderId"), ("TARGET_JOB_FOLDER_ID", "targetJobFolderId")):
    if os.environ.get(var):
        body[field] = int(os.environ[var])
json.dump(body, open(sys.argv[2], "w"))
print(f"Exported {export['fileName']}; {len(pairs)} data source mapping(s)")
PY

echo "Importing into project ${TARGET_PROJECT_ID}..."
HTTP_CODE=$(curl -s -o "$WORK_DIR/import-response.json" -w "%{http_code}" -X POST \
  "${TARGET_API}/Authoring/projects/${TARGET_PROJECT_ID}/import" \
  -H "x-val-api-token: ${TARGET_TOKEN}" \
  -H "Content-Type: application/json" \
  --data-binary "@$WORK_DIR/import.json")
if [ "$HTTP_CODE" = "200" ]; then
  echo "Import succeeded."
else
  echo "Import failed: HTTP ${HTTP_CODE}"
  cat "$WORK_DIR/import-response.json"; echo
  exit 1
fi

List data source ids for the mapping

Each data source has its own id on each instance, and the import needs a source_id:target_id pair for every data source the exported tests use. This script prints the data sources a token can see on both sides, so you can match them by name:

"""List the Validatar data sources visible to a token on the source and target instances.

Use the output to build DATA_SOURCE_MAPPINGS: find each source data source's
counterpart in the target by name, then write the pair as source_id:target_id.

Environment variables: SOURCE_VALIDATAR_API_URL, TARGET_VALIDATAR_API_URL, and
SOURCE_/TARGET_VALIDATAR_API_TOKEN (or VALIDATAR_API_TOKEN for both).
Requirements: pip install requests
"""
import os

import requests


def list_data_sources(url, token):
    response = requests.get(f"{url.rstrip('/')}/core/api/v1/Authoring/data-sources",
                            headers={"x-val-api-token": token, "Accept": "application/json"}, timeout=60)
    response.raise_for_status()
    print(f"Data sources at {url}:")
    for ds in response.json().get("dataSources", []):
        print(f"  {ds['id']:>5}  {ds['name']}")


for side in ("SOURCE", "TARGET"):
    token = os.environ.get(f"{side}_VALIDATAR_API_TOKEN") or os.environ["VALIDATAR_API_TOKEN"]
    list_data_sources(os.environ[f"{side}_VALIDATAR_API_URL"], token)
    print()

The list holds only the data sources the token's user has access to. If a data source is missing, check that user's data source permissions.

Run it in your CI/CD tool

Each tool needs the same three things: the token kept as a secret, the variables above in the step's environment, and Python 3 (or PowerShell, or Bash with curl and python3) on the runner. The scripts exit with code 1 on any failure, which fails the step.

Jenkins

Store the token as a Secret text credential, expose it with a withCredentials block, and run the script from an sh or pwsh step.

GitLab CI

Add the token as a masked CI/CD variable and run the script in a job's script: section on a python:3.12 image.

CircleCI

Keep the token in a context or project environment variable and run the script in a run step on a cimg/python image.

Azure DevOps

Store the token as a secret pipeline variable or in a variable group, map it into the step's env: (secret variables are not passed to scripts automatically), and run the script from a script or pwsh step.

TeamCity

Store the token as a password parameter named env.VALIDATAR_API_TOKEN and run the script from a Command Line build step.

AWS CodePipeline

Run the script in a CodeBuild buildspec.yml and pull the token from AWS Secrets Manager through the buildspec's env: secrets-manager: section.

Check that it worked

  1. The script's output ends with Import succeeded. and the step exits with code 0.
  2. Open the target project in Validatar. The exported folders are there, under the target folder if you set one.
  3. To confirm the promoted tests work against the target's data sources, run a job in the target project with the quality gate script in Run Validatar jobs from any orchestrator over REST.

Troubleshooting

HTTP 404 on every call

  • The URL variable holds the wrong address. Use the address you open Validatar with, such as https://acme.cloud.validatar.com, without /core and without a trailing slash. The scripts add /core/api/v1/<scope>/, for example /core/api/v1/Authoring/projects/12/export.

HTTP 403 on export or import

  • The token lacks the Authoring scope, or its user lacks the Export permission on the source project or the Import permission on the target project.

Export returns HTTP 400 or an empty file

  • Check that the folder ids, test ids and job ids belong to the source project.
  • Check that the requested folders hold at least one test or job.

Import fails with invalidDataSources

  • Run the data source listing script above against both instances.
  • Add a mapping for every data source the exported tests use. sourceFileKey is the source data source id written as a string.

Import fails with validationErrors or missingReferences

  • Check that the target project exists and the token's user can open it.
  • If you set TARGET_TEST_FOLDER_ID or TARGET_JOB_FOLDER_ID, check that those folders exist in the target project.
  • missingReferences means a job step points at something the file does not include. Export the folders that hold every test and job the exported jobs use.

Importing into an older version

  • Export and import generally work across Validatar versions. A file from a newer version can contain settings an older version does not support; the error response names them.