Run a test and wait for the result
Starts a run, reads it every 10 seconds until its status is final and exits with a non-zero code unless it passed, which is what a CI step needs. If the test already has a run in progress (409 run_in_progress), the program follows that run instead.
#!/usr/bin/env bash
# Start a run, poll it every 10 seconds and exit 1 unless it passed. Needs curl 7.76+ and jq.
set -euo pipefail
api="https://optisway.com/api/v1"
auth="Authorization: Bearer $OPTISWAY_API_KEY"
fail() { echo "$1" | jq -r '"\(.error): \(.message)"' >&2; exit 1; }
if run=$(curl --fail-with-body -sS -X POST "$api/tests/tst_7k2m9q4xh3vd/runs" -H "$auth"); then
echo "Started run $(echo "$run" | jq -r .id)"
else
# 409 run_in_progress: a run of this test is already active, so poll the newest one instead.
[ "$(echo "$run" | jq -r .error)" = run_in_progress ] || fail "$run"
runs=$(curl --fail-with-body -sS "$api/tests/tst_7k2m9q4xh3vd/runs?limit=1" -H "$auth") || fail "$runs"
run=$(echo "$runs" | jq '.items[0]')
echo "Following run $(echo "$run" | jq -r .id), already in progress"
fi
run_id=$(echo "$run" | jq -r .id)
status=$(echo "$run" | jq -r .status)
while [ "$status" != passed ] && [ "$status" != failed ] && [ "$status" != error ]; do
sleep 10
run=$(curl --fail-with-body -sS "$api/runs/$run_id" -H "$auth") || fail "$run"
status=$(echo "$run" | jq -r .status)
echo "Run $run_id: $status"
done
echo "$run" | jq -r '.summary // ""'
echo "$run" | jq -r '.findings[] | select(.severity == "fail") | "- \(.message) (\(.target // "-"))"'
[ "$status" = passed ] || exit 1// Node.js 18+: save as run-and-wait.mjs and run `node run-and-wait.mjs`
import { setTimeout as sleep } from "node:timers/promises";
const api = "https://optisway.com/api/v1";
const authorization = `Bearer ${process.env.OPTISWAY_API_KEY}`;
// Returns the JSON body; exits on an error response unless its code is `allowed`.
async function call(path, init = {}, allowed = "") {
const response = await fetch(api + path, {
...init,
headers: { Authorization: authorization, ...init.headers },
});
const body = await response.json();
if (!response.ok && body.error !== allowed) {
console.error(`${response.status} ${body.error}: ${body.message}`);
process.exit(1);
}
return body;
}
let run = await call("/tests/tst_7k2m9q4xh3vd/runs", { method: "POST" }, "run_in_progress");
if (run.error === "run_in_progress") {
// 409: a run of this test is already active, so poll the newest one instead of starting another.
[run] = (await call("/tests/tst_7k2m9q4xh3vd/runs?limit=1")).items;
console.log(`Following run ${run.id}, already in progress`);
} else {
console.log(`Started run ${run.id}`);
}
while (!["passed", "failed", "error"].includes(run.status)) {
await sleep(10_000);
run = await call(`/runs/${run.id}`);
console.log(`Run ${run.id}: ${run.status}`);
}
console.log(run.summary);
for (const finding of run.findings.filter((f) => f.severity === "fail")) {
console.log(`- ${finding.message} (${finding.target ?? "-"})`);
}
process.exit(run.status === "passed" ? 0 : 1);# pip install requests
import os
import sys
import time
import requests
API = "https://optisway.com/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['OPTISWAY_API_KEY']}"
def call(method, path, allowed=""):
"""Returns the JSON body; exits on an error response unless its code is `allowed`."""
response = session.request(method, API + path, timeout=30)
body = response.json()
if not response.ok and body.get("error") != allowed:
print(f"{response.status_code} {body['error']}: {body['message']}", file=sys.stderr)
sys.exit(1)
return body
run = call("POST", "/tests/tst_7k2m9q4xh3vd/runs", allowed="run_in_progress")
if run.get("error") == "run_in_progress":
# 409: a run of this test is already active, so poll the newest one instead of starting another.
run = call("GET", "/tests/tst_7k2m9q4xh3vd/runs?limit=1")["items"][0]
print(f"Following run {run['id']}, already in progress")
else:
print(f"Started run {run['id']}")
while run["status"] not in ("passed", "failed", "error"):
time.sleep(10)
run = call("GET", f"/runs/{run['id']}")
print(f"Run {run['id']}: {run['status']}")
print(run["summary"])
for finding in run["findings"]:
if finding["severity"] == "fail":
print(f"- {finding['message']} ({finding['target'] or '-'})")
sys.exit(0 if run["status"] == "passed" else 1)require "json"
require "net/http"
require "uri"
API = "https://optisway.com/api/v1"
KEY = ENV.fetch("OPTISWAY_API_KEY")
# Returns the JSON body; exits on an error response unless its code is `allowed`.
def call(request, allowed = "")
request["Authorization"] = "Bearer #{KEY}"
uri = request.uri
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
body = JSON.parse(response.body)
return body if response.is_a?(Net::HTTPSuccess) || body["error"] == allowed
warn "#{response.code} #{body["error"]}: #{body["message"]}"
exit 1
end
run = call(Net::HTTP::Post.new(URI("#{API}/tests/tst_7k2m9q4xh3vd/runs")), "run_in_progress")
if run["error"] == "run_in_progress"
# 409: a run of this test is already active, so poll the newest one instead of starting another.
run = call(Net::HTTP::Get.new(URI("#{API}/tests/tst_7k2m9q4xh3vd/runs?limit=1")))["items"].first
puts "Following run #{run["id"]}, already in progress"
else
puts "Started run #{run["id"]}"
end
until %w[passed failed error].include?(run["status"])
sleep 10
run = call(Net::HTTP::Get.new(URI("#{API}/runs/#{run["id"]}")))
puts "Run #{run["id"]}: #{run["status"]}"
end
puts run["summary"]
run["findings"].select { |finding| finding["severity"] == "fail" }.each do |finding|
puts "- #{finding["message"]} (#{finding["target"] || "-"})"
end
exit(run["status"] == "passed" ? 0 : 1)<?php
const API = "https://optisway.com/api/v1";
// Returns the JSON body; exits on an error response unless its code is $allowed.
function call(string $method, string $path, string $allowed = ""): array
{
$curl = curl_init(API . $path);
$headers = ["Authorization: Bearer " . getenv("OPTISWAY_API_KEY")];
if ($method === "POST") {
// No body: an empty POSTFIELDS makes libcurl send Content-Length: 0.
curl_setopt_array($curl, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => ""]);
}
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $headers]);
$body = json_decode((string) curl_exec($curl), true);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if (($status < 200 || $status >= 300) && ($body["error"] ?? null) !== $allowed) {
$message = $body["message"] ?? curl_error($curl);
fwrite(STDERR, "$status " . ($body["error"] ?? "request_failed") . ": $message\n");
exit(1);
}
return $body;
}
$run = call("POST", "/tests/tst_7k2m9q4xh3vd/runs", "run_in_progress");
if (($run["error"] ?? null) === "run_in_progress") {
// 409: a run of this test is already active, so poll the newest one instead of starting another.
$run = call("GET", "/tests/tst_7k2m9q4xh3vd/runs?limit=1")["items"][0];
echo "Following run {$run['id']}, already in progress\n";
} else {
echo "Started run {$run['id']}\n";
}
while (!in_array($run["status"], ["passed", "failed", "error"], true)) {
sleep(10);
$run = call("GET", "/runs/{$run['id']}");
echo "Run {$run['id']}: {$run['status']}\n";
}
echo $run["summary"], "\n";
foreach ($run["findings"] as $finding) {
if ($finding["severity"] === "fail") {
echo "- {$finding['message']} (", $finding["target"] ?? "-", ")\n";
}
}
exit($run["status"] === "passed" ? 0 : 1);// Java 11+: save as Main.java and run `java Main.java`
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
static final String API = "https://optisway.com/api/v1";
static final HttpClient CLIENT = HttpClient.newHttpClient();
public static void main(String[] args) throws Exception {
String run = call(HttpRequest.newBuilder(URI.create(API + "/tests/tst_7k2m9q4xh3vd/runs"))
.POST(HttpRequest.BodyPublishers.noBody()), "run_in_progress");
boolean following = "run_in_progress".equals(field(run, "error"));
if (following) {
// 409: a run of this test is already active, so poll the newest one instead of starting another.
run = call(HttpRequest.newBuilder(URI.create(API + "/tests/tst_7k2m9q4xh3vd/runs?limit=1")).GET(), "");
}
String id = field(run, "id");
String status = field(run, "status");
System.out.println(following ? "Following run " + id + ", already in progress" : "Started run " + id);
while (!status.equals("passed") && !status.equals("failed") && !status.equals("error")) {
Thread.sleep(10_000);
run = call(HttpRequest.newBuilder(URI.create(API + "/runs/" + id)).GET(), "");
status = field(run, "status");
System.out.println("Run " + id + ": " + status);
}
System.out.println(field(run, "summary"));
// Findings are { severity, code, message, target, value, unit }: print the failing ones.
Matcher failing = Pattern.compile("\"severity\"\\s*:\\s*\"fail\"").matcher(run);
while (failing.find()) {
String finding = run.substring(failing.end());
System.out.println("- " + field(finding, "message") + " (" + field(finding, "target") + ")");
}
System.exit(status.equals("passed") ? 0 : 1);
}
/** Returns the body; exits on an error response unless its code is {@code allowed}. */
static String call(HttpRequest.Builder builder, String allowed) throws Exception {
HttpRequest request = builder
.header("Authorization", "Bearer " + System.getenv("OPTISWAY_API_KEY"))
.build();
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
String error = field(response.body(), "error");
if (response.statusCode() >= 300 && !allowed.equals(error)) {
System.err.println(response.statusCode() + " " + error + ": " + field(response.body(), "message"));
System.exit(1);
}
return response.body();
}
/** The first string value of a JSON key (dependency-free; Jackson or Gson parse JSON properly). */
static String field(String json, String key) {
Matcher match = Pattern.compile("\"" + key + "\"\\s*:\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|null)")
.matcher(json);
return match.find() ? match.group(1) : null;
}
}package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
const api = "https://optisway.com/api/v1"
type run struct { // encoding/json matches the keys (id, status, …) case-insensitively
ID, Status, Summary string
Findings []struct{ Severity, Message, Target string }
}
// call decodes a 2xx body into out; an error response returns its code when allowed, else exits.
func call(method, path string, out any, allowed string) string {
req, err := http.NewRequest(method, api+path, nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("OPTISWAY_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
var envelope struct{ Error, Message string }
_ = json.NewDecoder(resp.Body).Decode(&envelope)
if allowed != "" && envelope.Error == allowed {
return allowed
}
fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, envelope.Error, envelope.Message)
os.Exit(1)
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
panic(err)
}
return ""
}
func main() {
var r run
if call(http.MethodPost, "/tests/tst_7k2m9q4xh3vd/runs", &r, "run_in_progress") != "" {
// 409: a run of this test is already active, so poll the newest one instead of starting another.
var page struct{ Items []run }
call(http.MethodGet, "/tests/tst_7k2m9q4xh3vd/runs?limit=1", &page, "")
r = page.Items[0]
fmt.Printf("Following run %s, already in progress\n", r.ID)
} else {
fmt.Println("Started run", r.ID)
}
for r.Status != "passed" && r.Status != "failed" && r.Status != "error" {
time.Sleep(10 * time.Second)
call(http.MethodGet, "/runs/"+r.ID, &r, "")
fmt.Printf("Run %s: %s\n", r.ID, r.Status)
}
fmt.Println(r.Summary)
for _, f := range r.Findings {
if f.Severity == "fail" {
fmt.Printf("- %s (%s)\n", f.Message, f.Target)
}
}
if r.Status != "passed" {
os.Exit(1)
}
}// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
const string Api = "https://optisway.com/api/v1";
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var run = await Read(await client.PostAsync($"{Api}/tests/tst_7k2m9q4xh3vd/runs", null), "run_in_progress");
var following = run.TryGetProperty("error", out _);
if (following)
{
// 409: a run of this test is already active, so poll the newest one instead of starting another.
var newest = await Read(await client.GetAsync($"{Api}/tests/tst_7k2m9q4xh3vd/runs?limit=1"));
run = newest.GetProperty("items")[0];
}
var id = run.GetProperty("id").GetString();
var status = run.GetProperty("status").GetString();
Console.WriteLine(following ? $"Following run {id}, already in progress" : $"Started run {id}");
while (status is not ("passed" or "failed" or "error"))
{
await Task.Delay(TimeSpan.FromSeconds(10));
run = await Read(await client.GetAsync($"{Api}/runs/{id}"));
status = run.GetProperty("status").GetString();
Console.WriteLine($"Run {id}: {status}");
}
Console.WriteLine(run.GetProperty("summary"));
foreach (var finding in run.GetProperty("findings").EnumerateArray())
{
if (finding.GetProperty("severity").GetString() != "fail") continue;
Console.WriteLine($"- {finding.GetProperty("message")} ({finding.GetProperty("target")})");
}
return status == "passed" ? 0 : 1;
// Returns the JSON body; exits on an error response unless its code is `allowed`.
static async Task<JsonElement> Read(HttpResponseMessage response, string allowed = "")
{
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
if (response.IsSuccessStatusCode) return body;
var error = body.GetProperty("error");
if (error.GetString() == allowed) return body;
var message = body.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode} {error}: {message}");
Environment.Exit(1);
return body;
}