[v2,03/18] tests/lib.sh: Add check if variable exists to test_value_in_array

Message ID 20240616160245.18865-4-jonatan.schlag@ipfire.org
State New
Headers
Series [v2,01/18] tests: Add bash lib |

Commit Message

Jonatan Schlag June 16, 2024, 4:02 p.m. UTC
  We cannot use [ -v ] here as this does not work. We need to check if the
array is correctly declared.

Signed-off-by: Jonatan Schlag <jonatan.schlag@ipfire.org>
---
 tests/lib.sh | 9 +++++++++
 1 file changed, 9 insertions(+)
  

Patch

diff --git a/tests/lib.sh b/tests/lib.sh
index 716922024..4fce151f8 100644
--- a/tests/lib.sh
+++ b/tests/lib.sh
@@ -28,9 +28,18 @@  var_has_value() {
 
 test_value_in_array() {
 	local -n array="${1}"
+	local arrayname="${1}"
 	local key="${2}"
 	local value="${3}"
 
+	# `declare -p` print out how the variable with the name $arrayname was declared
+	# If the array was not declared as indexed or associative array we fail. We cannot check for a value in an array if 
+	# we were not given array.
+	if [[ ! "$(declare  -p "${arrayname}")" =~ "declare -a" && ! "$(declare  -p "${arrayname}")" =~ "declare -A" ]]; then
+		echo -e "${CLR_RED_BG}Test failed: The array '${1}' does not exists. The variable is not set.${CLR_RESET}'"
+		return 1
+	fi
+
 	if [[ "${array[${key}]}" == "${value}" ]] ; then
 		echo -e "${CLR_GREEN_BG}Test succeded: The array '${1}' contains the value '${value}' under the key '${key}' ${CLR_RESET}"
 		return 0