Files
snapd/tests/lib/tools/tests.env
Sergio Cazzolato 7ba95e3a7a tests: speed up the prepare phase through a new tool to manage initial snapd env (#12707)
* New tool to manage initial env in spread tests

This is used to know in spread tests the initial value for the vars and
be able to repeat not needed steps

* test fixed

* Minor fixes con docs and env var removed

* improve tests.env tool
2023-07-07 17:17:41 +02:00

131 lines
3.0 KiB
Bash
Executable File

#!/bin/bash
show_help() {
echo "usage: tests.env start <ENV_NAME>"
echo " tests.env is-set <ENV_NAME> <VAR>"
echo " tests.env get <ENV_NAME> <VAR>"
echo " tests.env set <ENV_NAME> <VAR> <VAL>"
echo ""
echo "The tool is used to create an environment file"
echo " which can be shared across different tests and suites"
}
start() {
local NAME=$1
if [ -z "$NAME" ]; then
echo "tests.env: name for the env file is required"
exit 1
fi
if [ -f "$RUNTIME_STATE_PATH/$NAME.env" ]; then
echo "tests.env: env file $RUNTIME_STATE_PATH/$NAME.env already exists, deleting..."
rm -f "$RUNTIME_STATE_PATH/$NAME.env"
fi
mkdir -p "$RUNTIME_STATE_PATH"
touch "$RUNTIME_STATE_PATH/$NAME.env"
}
is_set() {
local NAME=$1
local VAR=$2
if [ -z "$NAME" ]; then
echo "tests.env: name for the env file is required"
exit 1
fi
if [ -z "$VAR" ]; then
echo "tests.env: variable to check in env file is required"
exit 1
fi
if [ ! -f "$RUNTIME_STATE_PATH/$NAME.env" ]; then
echo "tests.env: env file $RUNTIME_STATE_PATH/$NAME.env does not exist"
exit 1
fi
grep -Eq "^${VAR}=" "$RUNTIME_STATE_PATH/$NAME.env"
}
get() {
local NAME=$1
local VAR=$2
if [ -z "$NAME" ]; then
echo "tests.env: name for the env file is required"
exit 1
fi
if [ -z "$VAR" ]; then
echo "tests.env: variable to check in env file is required"
exit 1
fi
if [ ! -f "$RUNTIME_STATE_PATH/$NAME.env" ]; then
echo "tests.env: env file $RUNTIME_STATE_PATH/$NAME.env does not exist"
exit 1
fi
if is_set "$NAME" "$VAR"; then
grep -E "^${VAR}=" "$RUNTIME_STATE_PATH/$NAME.env" | cut -d "=" -f2-
fi
}
set() {
local NAME=$1
local VAR=$2
local VAL=$3
if [ -z "$NAME" ]; then
echo "tests.env: name for the env file is required"
exit 1
fi
if [ -z "$VAR" ]; then
echo "tests.env: variable to set in env file is required"
exit 1
fi
if [ ! -f "$RUNTIME_STATE_PATH/$NAME.env" ]; then
echo "tests.env: env file $RUNTIME_STATE_PATH/$NAME.env does not exist"
exit 1
fi
if is_set "$NAME" "$VAR"; then
sed -i -E "s/^${VAR}=.*/${VAR}=${VAL}/" "$RUNTIME_STATE_PATH/$NAME.env"
else
echo "${VAR}=${VAL}" >> "$RUNTIME_STATE_PATH/$NAME.env"
fi
}
main() {
if [ $# -eq 0 ]; then
show_help
exit 0
fi
local subcommand="$1"
local action=
while [ $# -gt 0 ]; do
case "$subcommand" in
-h|--help)
show_help
exit 0
;;
*)
action=$(echo "$subcommand" | tr '-' '_')
shift
break
;;
esac
done
if [ -z "$(declare -f "$action")" ]; then
echo "tests.env: no such command: $subcommand"
show_help
exit 1
fi
"$action" "$@"
}
main "$@"