secrets/test/common.sh (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
# Common test utilities for szecret tests
# Source this file from individual test files
set -euo pipefail
SECRETS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
pass() { echo -e "${GREEN}PASS${NC}: $1"; }
fail() { echo -e "${RED}FAIL${NC}: $1"; exit 1; }
skip() { echo -e "${YELLOW}SKIP${NC}: $1"; }
# Create temporary test environment
setup() {
export TEST_DIR="$(mktemp -d)"
export SZECRET_STORE="${TEST_DIR}/store"
export SZECRET_PUBLIC_KEY="${TEST_DIR}/.id.pub"
export SZECRET_PRIVATE_KEY="${TEST_DIR}/.id"
mkdir -p "${SZECRET_STORE}"
# Generate test keypair
age-keygen -o "${SZECRET_PRIVATE_KEY}" 2>/dev/null
age-keygen -y "${SZECRET_PRIVATE_KEY}" > "${SZECRET_PUBLIC_KEY}"
}
teardown() {
if [[ -n "${TEST_DIR:-}" && -d "${TEST_DIR}" ]]; then
rm -rf "${TEST_DIR}"
fi
}
# Run a command from the secrets directory
szecret() {
"${SECRETS_DIR}/main.sh" "$@"
}
# Direct access to individual scripts (useful for testing specific scripts)
szecret_script() {
local script="$1"
shift
"${SECRETS_DIR}/${script}.sh" "$@"
}
# Assert that a command succeeds
assert_success() {
if "$@"; then
return 0
else
fail "Command failed: $*"
fi
}
# Assert that a command fails
assert_failure() {
if "$@" 2>/dev/null; then
fail "Command should have failed: $*"
else
return 0
fi
}
# Assert string equality
assert_equals() {
local expected="$1"
local actual="$2"
local msg="${3:-values}"
if [[ "${expected}" == "${actual}" ]]; then
return 0
else
fail "${msg}: expected '${expected}', got '${actual}'"
fi
}
# Assert string contains substring
assert_contains() {
local haystack="$1"
local needle="$2"
local msg="${3:-string}"
if [[ "${haystack}" == *"${needle}"* ]]; then
return 0
else
fail "${msg}: '${haystack}' does not contain '${needle}'"
fi
}
# Assert file exists
assert_file_exists() {
local file="$1"
local msg="${2:-file}"
if [[ -f "${file}" ]]; then
return 0
else
fail "${msg}: file '${file}' does not exist"
fi
}
# Auto-setup: only run once per process
if [[ -z "${_SZECRET_TEST_INITIALIZED:-}" ]]; then
export _SZECRET_TEST_INITIALIZED=1
trap teardown EXIT
setup
fi
|