ploughshares/test_api_curl.sh

80 lines
2.4 KiB
Bash
Executable File

#!/bin/bash
set -Eeuo pipefail
# Colors for better readability
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
FAILURES=0
fail() { echo -e "${RED}$1${NC}"; FAILURES=$((FAILURES+1)); }
pass() { echo -e "${GREEN}$1${NC}"; }
# Base URLs to test
DEV_URL="http://localhost:5005"
PROD_URL="https://ploughshares.nixc.us"
# Default to development URL unless specified
URL=${1:-$DEV_URL}
echo -e "${BLUE}Testing API endpoints with curl for ${URL}${NC}"
echo "=================================================="
assert_status_and_json_field() {
local method=$1; shift
local url=$1; shift
local data=${1:-}; shift || true
local headers=${1:-}; shift || true
local expected_status=${1:-200}; shift || true
local json_field=${1:-}; shift || true
local tmp
tmp=$(mktemp)
local cmd="curl -s -o $tmp -w \"%{http_code}\" -X $method"
if [ -n "$headers" ]; then
cmd="$cmd $headers"
fi
if [ -n "$data" ]; then
cmd="$cmd -d '$data'"
fi
cmd="$cmd \"$url\""
echo -e "${BLUE}Command:${NC} $cmd"
# shellcheck disable=SC2086
status=$(eval $cmd)
echo -e "${BLUE}Status:${NC} $status"
echo -e "${BLUE}Body:${NC}"; cat "$tmp" | jq 2>/dev/null || cat "$tmp"
if [ "$status" != "$expected_status" ]; then
fail "$method $url expected $expected_status, got $status"
rm -f "$tmp"
return
fi
if [ -n "$json_field" ] && ! jq -e ".${json_field} // empty" >/dev/null 2>&1 <"$tmp"; then
fail "$method $url response missing field: $json_field"
rm -f "$tmp"
return
fi
pass "$method $url returned $expected_status${json_field:+ and contains $json_field}"
rm -f "$tmp"
}
# Tests that do not mutate state
assert_status_and_json_field GET "${URL}/api/test" "" "-H \"Accept: application/json\"" 200 status
assert_status_and_json_field OPTIONS "${URL}/api/test" "" "-H \"Origin: http://example.com\"" 200
# Mutating tests guarded by env var
if [[ "${ALLOW_MUTATING_TESTS:-0}" == "1" ]]; then
assert_status_and_json_field POST "${URL}/api/transaction" '{"transaction_type":"test","company_division":"div","recipient":"Test Corp"}' "-H \"Content-Type: application/json\" -H \"Accept: application/json\"" 201 transaction_id
else
echo -e "${YELLOW}Skipping POST/PUT/DELETE tests (set ALLOW_MUTATING_TESTS=1 to enable).${NC}"
fi
if [ "$FAILURES" -gt 0 ]; then
echo -e "${RED}API curl tests failed: $FAILURES issue(s).${NC}"; exit 1
else
echo -e "${GREEN}All API curl tests passed.${NC}"
fi