Run Validatar tests in Bitbucket Pipelines

Prev Next

Bitbucket Pipelines can call the Validatar REST API to promote tests and jobs from a source project to a target project, and to run a Validatar job as a build step that fails when any test in the job does not pass. This page gives the bitbucket-pipelines.yml entries and the two Python scripts they run.

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. Bitbucket Cloud runners reach Validatar Cloud. For Validatar Server behind a firewall, use a self-hosted runner with network access to your server.

Step 1: Configure repository variables

Add these under Repository settings > Pipelines > Repository variables:

Variable Secured Value
VALIDATAR_API_TOKEN Yes Your Validatar user token
SOURCE_VALIDATAR_API_URL No Source instance address, such as https://dev.cloud.validatar.com (no /core, no trailing slash)
TARGET_VALIDATAR_API_URL No Target instance address, such as https://prod.cloud.validatar.com
SOURCE_PROJECT_ID No Source Validatar project id
TARGET_PROJECT_ID No Target Validatar project id
EXPORT_TEST_FOLDER_IDS No Test folder ids to export, comma-separated
EXPORT_JOB_FOLDER_IDS No Job folder ids to export, comma-separated
DATA_SOURCE_MAPPINGS No Data source mappings, such as 42:87,43:88
VALIDATAR_API_URL No Instance that runs the quality gate job
VALIDATAR_PROJECT_ID No Project that holds the quality gate job
VALIDATAR_JOB_ID No The job to run
VALIDATAR_TIMEOUT No Optional: seconds to wait for the job, default 1800

Tip: Mark the token as Secured so Bitbucket masks it in build logs. Ids and addresses can stay unsecured, which makes the logs easier to read.

When the source and target are two projects on the same instance, set both URL variables 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"])
build = os.environ.get("BITBUCKET_BUILD_NUMBER", "manual")

# ---------------------------------------------------------------------------
# Step 1: export from the source project
# ---------------------------------------------------------------------------
export_body = {
    "name": "bitbucket-pipelines-export",
    "description": f"Automated export from Bitbucket build {build}",
    "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
# ---------------------------------------------------------------------------
print(f"Quality gate, Bitbucket build {os.environ.get('BITBUCKET_BUILD_NUMBER', 'manual')}")
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
# ---------------------------------------------------------------------------
print(f"Started {summary.get('dateStarted')}, completed {summary.get('dateCompleted')}")
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 pipelines

Create or update bitbucket-pipelines.yml in the repository root. This version promotes tests on every merge to main, offers the same promotion as a manual pipeline, and offers the quality gate as a manual pipeline:

image: python:3.12-slim

pipelines:
  branches:
    main:
      - step:
          name: Promote Validatar tests
          script:
            - pip install requests
            - export SAVE_EXPORT_FILE=true
            - python scripts/validatar_promote.py
          artifacts:
            - validatar-export.xml

  custom:
    promote-tests:
      - variables:
          - name: SOURCE_PROJECT_ID
          - name: TARGET_PROJECT_ID
          - name: EXPORT_TEST_FOLDER_IDS
          - name: EXPORT_JOB_FOLDER_IDS
          - name: DATA_SOURCE_MAPPINGS
      - step:
          name: Promote Validatar tests (manual)
          script:
            - pip install requests
            - python scripts/validatar_promote.py

    quality-gate:
      - variables:
          - name: VALIDATAR_PROJECT_ID
          - name: VALIDATAR_JOB_ID
      - step:
          name: Run Validatar quality gate (manual)
          script:
            - pip install requests
            - python scripts/validatar_quality_gate.py

The artifacts entry keeps the exported XML with the build, so you can download it and see exactly what was promoted.

Promote, then test the target

To run the quality gate against the target right after the import, chain the two steps in one pipeline. The second step points the gate at the target instance:

pipelines:
  custom:
    promote-and-validate:
      - step:
          name: Promote Validatar tests
          script:
            - pip install requests
            - export SAVE_EXPORT_FILE=true
            - python scripts/validatar_promote.py
          artifacts:
            - validatar-export.xml
      - step:
          name: Run the quality gate on the target
          script:
            - pip install requests
            - export VALIDATAR_API_URL="$TARGET_VALIDATAR_API_URL"
            - python scripts/validatar_quality_gate.py

VALIDATAR_PROJECT_ID and VALIDATAR_JOB_ID must then name a job in the target project.

Step 4: Run a pipeline by hand

  1. Open Pipelines in your Bitbucket repository.
  2. Click Run pipeline.
  3. Select the branch.
  4. Choose the custom pipeline, for example promote-tests.
  5. Fill in any variable overrides.
  6. Click Run.

Check that it worked

  • Promotion. The step log ends with Import succeeded., and validatar-export.xml appears under the step's Artifacts. Open the target project in Validatar: the exported folders are there.
  • Quality gate. The step log prints Started job ... batch <id>, one line per test, and PASSED: all N test(s) passed. To see the same run in Validatar, open https://<your-instance>.cloud.validatar.com/projects/<project id>/results/<batch id>. When a test fails, the step exits with code 1 and the build fails.

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>/.

HTTP 401 or 403

  • Check that VALIDATAR_API_TOKEN is set and 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. sourceFileKey is the source data source id written as a string.

"pip: command not found"

  • Use an image that includes Python 3. python:3.12-slim works.
  • On a custom image, install Python first, for example apt-get install -y python3 python3-pip.

The self-hosted runner cannot reach Validatar

  • Confirm the runner has network access to the Validatar address, including firewall and proxy rules. Atlassian's runner documentation covers the setup.

The quality gate times out

  • Raise the VALIDATAR_TIMEOUT repository variable if the job runs longer than 30 minutes.
  • Open the job in Validatar to see whether the run is still going or stuck.

The export XML artifact is missing

  • The artifacts list must sit under the same step that runs the promote script, and that step must set SAVE_EXPORT_FILE=true.