Optisway ana sayfa
Dokümantasyon menüsü

REST API referansı: Hazır programlar

En sık yapılan üç iş için sekiz dilin hepsinde eksiksiz programlar: bir testi çalıştırıp sonucunu beklemek, bir çalıştırmanın PDF raporunu indirmek ve bir projenin başarısız çalıştırmalarını listelemek.

Programları çalıştırma

Her program anahtarı OPTISWAY_API_KEY değişkeninden okur, her yanıtın durumunu kontrol eder ve bir istek başarısız olursa bir hata mesajıyla durur. Bir programı çalıştırmadan önce değişkeni dışa aktarın.

Önce örnek kimlikleri değiştirin: test kimliği tst_7k2m9q4xh3vd ve proje kimliği 42. İlk program yalnızca çalıştırma başarılı olduğunda 0 çıkış koduyla biter; böylece bir betik veya CI adımı çıkış koduna güvenebilir.

Testi çalıştır ve sonucu bekle

Bir çalıştırma başlatır, durumu kesinleşene kadar 10 saniyede bir okur ve başarılı olmadıkça sıfırdan farklı bir çıkış koduyla sonlanır; bir CI adımının ihtiyacı tam olarak budur. Test için zaten süren bir çalıştırma varsa (409 run_in_progress), program bunun yerine o çalıştırmayı izler.

#!/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;
}

Bir çalıştırmanın PDF raporunu indir

Bir testin en yeni çalıştırmasını bulur ve report.pdf dosyasını geçerli dizine kaydeder.

#!/usr/bin/env bash
# Save the PDF report of the latest run of a test as report.pdf. 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; }

runs=$(curl --fail-with-body -sS "$api/tests/tst_7k2m9q4xh3vd/runs?limit=1" -H "$auth") || fail "$runs"
run_id=$(echo "$runs" | jq -r '.items[0].id // empty')
[ -n "$run_id" ] || { echo "The test has no runs yet." >&2; exit 1; }
if ! curl --fail-with-body -sS -o report.pdf "$api/runs/$run_id/files?path=report.pdf" -H "$auth"; then
  envelope=$(cat report.pdf); rm -f report.pdf; fail "$envelope"
fi
echo "Saved report.pdf of run $run_id ($(wc -c < report.pdf | tr -d ' ') bytes)"
// Node.js 18+: save as download-report.mjs and run `node download-report.mjs`
import { writeFile } from "node:fs/promises";

const api = "https://optisway.com/api/v1";
const headers = { Authorization: `Bearer ${process.env.OPTISWAY_API_KEY}` };

async function get(path) {
  const response = await fetch(api + path, { headers });
  if (!response.ok) {
    const { error, message } = await response.json();
    console.error(`${response.status} ${error}: ${message}`);
    process.exit(1);
  }
  return response;
}

const { items } = await (await get("/tests/tst_7k2m9q4xh3vd/runs?limit=1")).json();
if (items.length === 0) {
  console.error("The test has no runs yet.");
  process.exit(1);
}
const runId = items[0].id;
const report = await get(`/runs/${runId}/files?path=report.pdf`);
const bytes = Buffer.from(await report.arrayBuffer());
await writeFile("report.pdf", bytes);
console.log(`Saved report.pdf of run ${runId} (${bytes.length} bytes)`);
# pip install requests
import os
import sys

import requests

API = "https://optisway.com/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['OPTISWAY_API_KEY']}"


def get(path):
    response = session.get(API + path, timeout=60)
    if not response.ok:
        envelope = response.json()
        print(f"{response.status_code} {envelope['error']}: {envelope['message']}", file=sys.stderr)
        sys.exit(1)
    return response


runs = get("/tests/tst_7k2m9q4xh3vd/runs?limit=1").json()["items"]
if not runs:
    sys.exit("The test has no runs yet.")
run_id = runs[0]["id"]
report = get(f"/runs/{run_id}/files?path=report.pdf").content
with open("report.pdf", "wb") as file:
    file.write(report)
print(f"Saved report.pdf of run {run_id} ({len(report)} bytes)")
require "json"
require "net/http"
require "uri"

API = "https://optisway.com/api/v1"
KEY = ENV.fetch("OPTISWAY_API_KEY")

def get(path)
  uri = URI(API + path)
  request = Net::HTTP::Get.new(uri)
  request["Authorization"] = "Bearer #{KEY}"
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
  return response if response.is_a?(Net::HTTPSuccess)

  envelope = JSON.parse(response.body)
  warn "#{response.code} #{envelope["error"]}: #{envelope["message"]}"
  exit 1
end

runs = JSON.parse(get("/tests/tst_7k2m9q4xh3vd/runs?limit=1").body)["items"]
abort "The test has no runs yet." if runs.empty?
run_id = runs.first["id"]
report = get("/runs/#{run_id}/files?path=report.pdf").body
File.binwrite("report.pdf", report)
puts "Saved report.pdf of run #{run_id} (#{report.bytesize} bytes)"
<?php
const API = "https://optisway.com/api/v1";

function get(string $path): string
{
  $curl = curl_init(API . $path);
  curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("OPTISWAY_API_KEY")],
  ]);
  $body = (string) curl_exec($curl);
  $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
  if ($status < 200 || $status >= 300) {
    $envelope = json_decode($body, true) ?? ["error" => "request_failed", "message" => curl_error($curl)];
    fwrite(STDERR, "$status {$envelope['error']}: {$envelope['message']}\n");
    exit(1);
  }
  return $body;
}

$runs = json_decode(get("/tests/tst_7k2m9q4xh3vd/runs?limit=1"), true)["items"];
if (count($runs) === 0) {
  fwrite(STDERR, "The test has no runs yet.\n");
  exit(1);
}
$runId = $runs[0]["id"];
$report = get("/runs/$runId/files?path=report.pdf");
file_put_contents("report.pdf", $report);
echo "Saved report.pdf of run $runId (" . strlen($report) . " bytes)\n";
// 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.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
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 runs = new String(get("/tests/tst_7k2m9q4xh3vd/runs?limit=1"), StandardCharsets.UTF_8);
    // The first "id" of { "items": [ { "id": ... } ] } is the latest run's id.
    String runId = field(runs, "id");
    if (runId == null) {
      System.err.println("The test has no runs yet.");
      System.exit(1);
    }
    byte[] report = get("/runs/" + runId + "/files?path=report.pdf");
    Files.write(Path.of("report.pdf"), report);
    System.out.println("Saved report.pdf of run " + runId + " (" + report.length + " bytes)");
  }

  static byte[] get(String path) throws Exception {
    HttpRequest request = HttpRequest.newBuilder(URI.create(API + path))
        .header("Authorization", "Bearer " + System.getenv("OPTISWAY_API_KEY"))
        .build();
    HttpResponse<byte[]> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofByteArray());
    if (response.statusCode() >= 300) {
      String error = new String(response.body(), StandardCharsets.UTF_8);
      System.err.println(response.statusCode() + " " + field(error, "error") + ": "
          + field(error, "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"
	"io"
	"net/http"
	"os"
)

const api = "https://optisway.com/api/v1"

// get answers the response of a successful GET; on an error it prints the envelope and exits.
func get(path string) *http.Response {
	req, err := http.NewRequest(http.MethodGet, 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)
	}
	if resp.StatusCode >= 300 {
		var envelope struct {
			Error   string `json:"error"`
			Message string `json:"message"`
		}
		_ = json.NewDecoder(resp.Body).Decode(&envelope)
		fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, envelope.Error, envelope.Message)
		os.Exit(1)
	}
	return resp
}

func main() {
	resp := get("/tests/tst_7k2m9q4xh3vd/runs?limit=1")
	var runs struct {
		Items []struct {
			ID string `json:"id"`
		} `json:"items"`
	}
	err := json.NewDecoder(resp.Body).Decode(&runs)
	resp.Body.Close()
	if err != nil {
		panic(err)
	}
	if len(runs.Items) == 0 {
		fmt.Fprintln(os.Stderr, "The test has no runs yet.")
		os.Exit(1)
	}
	runID := runs.Items[0].ID
	report := get("/runs/" + runID + "/files?path=report.pdf")
	defer report.Body.Close()
	file, err := os.Create("report.pdf")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	size, err := io.Copy(file, report.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Saved report.pdf of run %s (%d bytes)\n", runID, size)
}
// .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 runs = await (await Get("/tests/tst_7k2m9q4xh3vd/runs?limit=1")).Content.ReadFromJsonAsync<JsonElement>();
var items = runs.GetProperty("items");
if (items.GetArrayLength() == 0)
{
  Console.Error.WriteLine("The test has no runs yet.");
  return 1;
}
var runId = items[0].GetProperty("id").GetString();
var report = await (await Get($"/runs/{runId}/files?path=report.pdf")).Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("report.pdf", report);
Console.WriteLine($"Saved report.pdf of run {runId} ({report.Length} bytes)");
return 0;

async Task<HttpResponseMessage> Get(string path)
{
  var response = await client.GetAsync(Api + path);
  if (response.IsSuccessStatusCode) return response;
  var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
  var error = envelope.GetProperty("error");
  var message = envelope.GetProperty("message");
  Console.Error.WriteLine($"{(int)response.StatusCode} {error}: {message}");
  Environment.Exit(1);
  return response;
}

Bir projenin başarısız çalıştırmalarını listele

Bir projenin başarısız çalıştırmalarını listeler ve her biri için test adını, bitiş zamanını ve özetini yazdırır.

#!/usr/bin/env bash
# Print the failed runs of project 42, newest first, following next until null. Needs curl 7.76+ and jq.
set -euo pipefail
origin="https://optisway.com"
auth="Authorization: Bearer $OPTISWAY_API_KEY"
fail() { echo "$1" | jq -r '"\(.error): \(.message)"' >&2; exit 1; }

path="/api/v1/runs?project=42&status=failed&limit=50"
while [ -n "$path" ]; do
  page=$(curl --fail-with-body -sS "$origin$path" -H "$auth") || fail "$page"
  echo "$page" | jq -r '.items[] | "\(.testName)  \(.finishedAt)  \(.summary // "")"'
  path=$(echo "$page" | jq -r '.next // empty')
done
// Node.js 18+: save as list-failures.mjs and run `node list-failures.mjs`
const origin = "https://optisway.com";
const headers = { Authorization: `Bearer ${process.env.OPTISWAY_API_KEY}` };

// `next` is the same path with before=<last id>, or null on the last page.
let path = "/api/v1/runs?project=42&status=failed&limit=50";
while (path) {
  const response = await fetch(origin + path, { headers });
  const page = await response.json();
  if (!response.ok) {
    console.error(`${response.status} ${page.error}: ${page.message}`);
    process.exit(1);
  }
  for (const run of page.items) console.log(run.testName, run.finishedAt, run.summary);
  path = page.next;
}
# pip install requests
import os
import sys

import requests

ORIGIN = "https://optisway.com"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['OPTISWAY_API_KEY']}"

# "next" is the same path with before=<last id>, or None on the last page.
path = "/api/v1/runs?project=42&status=failed&limit=50"
while path:
    response = session.get(ORIGIN + path, timeout=30)
    page = response.json()
    if not response.ok:
        print(f"{response.status_code} {page['error']}: {page['message']}", file=sys.stderr)
        sys.exit(1)
    for run in page["items"]:
        print(run["testName"], run["finishedAt"], run["summary"], sep="  ")
    path = page["next"]
require "json"
require "net/http"
require "uri"

ORIGIN = "https://optisway.com"
KEY = ENV.fetch("OPTISWAY_API_KEY")

# "next" is the same path with before=<last id>, or nil on the last page.
path = "/api/v1/runs?project=42&status=failed&limit=50"
while path
  uri = URI(ORIGIN + path)
  request = Net::HTTP::Get.new(uri)
  request["Authorization"] = "Bearer #{KEY}"
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
  page = JSON.parse(response.body)
  unless response.is_a?(Net::HTTPSuccess)
    warn "#{response.code} #{page["error"]}: #{page["message"]}"
    exit 1
  end
  page["items"].each do |run|
    puts [run["testName"], run["finishedAt"], run["summary"]].join("  ")
  end
  path = page["next"]
end
<?php
const ORIGIN = "https://optisway.com";

// "next" is the same path with before=<last id>, or null on the last page.
$path = "/api/v1/runs?project=42&status=failed&limit=50";
while ($path !== null) {
  $curl = curl_init(ORIGIN . $path);
  curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("OPTISWAY_API_KEY")],
  ]);
  $page = json_decode((string) curl_exec($curl), true);
  $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
  if ($status < 200 || $status >= 300) {
    fwrite(STDERR, "$status " . ($page["error"] ?? "request_failed") . ": "
      . ($page["message"] ?? curl_error($curl)) . "\n");
    exit(1);
  }
  foreach ($page["items"] as $run) {
    echo $run["testName"], "  ", $run["finishedAt"], "  ", $run["summary"], "\n";
  }
  $path = $page["next"];
}
// 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 ORIGIN = "https://optisway.com";

  public static void main(String[] args) throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    // "next" is the same path with before=<last id>, or null on the last page.
    String path = "/api/v1/runs?project=42&status=failed&limit=50";
    while (path != null) {
      HttpRequest request = HttpRequest.newBuilder(URI.create(ORIGIN + path))
          .header("Authorization", "Bearer " + System.getenv("OPTISWAY_API_KEY"))
          .build();
      HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
      String page = response.body();
      if (response.statusCode() >= 300) {
        System.err.println(response.statusCode() + " " + field(page, "error") + ": "
            + field(page, "message"));
        System.exit(1);
      }
      // Run fields come in a fixed order (testName before finishedAt and summary); a JSON library such as
      // Jackson or Gson reads them properly.
      Matcher names = Pattern.compile("\"testName\"\\s*:").matcher(page);
      while (names.find()) {
        String run = page.substring(names.start());
        System.out.println(field(run, "testName") + "  " + field(run, "finishedAt") + "  "
            + field(run, "summary"));
      }
      path = field(page.substring(page.lastIndexOf("\"next\"")), "next");
    }
  }

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

const origin = "https://optisway.com"

type page struct {
	Items []struct {
		TestName   string `json:"testName"`
		FinishedAt string `json:"finishedAt"`
		Summary    string `json:"summary"`
	} `json:"items"`
	Next    *string `json:"next"`
	Error   string  `json:"error"`
	Message string  `json:"message"`
}

func main() {
	// next is the same path with before=<last id>, or null on the last page.
	path := "/api/v1/runs?project=42&status=failed&limit=50"
	for path != "" {
		req, err := http.NewRequest(http.MethodGet, origin+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)
		}
		var p page
		err = json.NewDecoder(resp.Body).Decode(&p)
		resp.Body.Close()
		if err != nil {
			panic(err)
		}
		if resp.StatusCode >= 300 {
			fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, p.Error, p.Message)
			os.Exit(1)
		}
		for _, run := range p.Items {
			fmt.Println(run.TestName, run.FinishedAt, run.Summary)
		}
		path = ""
		if p.Next != nil {
			path = *p.Next
		}
	}
}
// .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 Origin = "https://optisway.com";
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
  new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));

// "next" is the same path with before=<last id>, or null on the last page.
string? path = "/api/v1/runs?project=42&status=failed&limit=50";
while (path is not null)
{
  using var response = await client.GetAsync(Origin + path);
  var page = await response.Content.ReadFromJsonAsync<JsonElement>();
  if (!response.IsSuccessStatusCode)
  {
    var error = page.GetProperty("error");
    var message = page.GetProperty("message");
    Console.Error.WriteLine($"{(int)response.StatusCode} {error}: {message}");
    return 1;
  }
  foreach (var run in page.GetProperty("items").EnumerateArray())
  {
    Console.WriteLine(string.Join("  ",
      run.GetProperty("testName"), run.GetProperty("finishedAt"), run.GetProperty("summary")));
  }
  path = page.GetProperty("next").GetString();
}
return 0;