1
0
mirror of https://github.com/sstephenson/bats.git synced 2024-09-29 12:38:26 +02:00
bats/libexec/bats-preprocess
Sam Stephenson bfa4ebcd0f Prefer let x+=1 for incrementing counters
The `((x++))` syntax is shorthand for `let x++`. According to `help let`:

    If the last ARG evaluates to 0, let returns 1; 0 is returned
    otherwise.

Thus the exit status of the expression `x=0; let x++` is 1, since the post-increment `++` operator evaluates to the value of the variable before incrementing.

In Bash 4, this non-zero exit status properly triggers `set -e`'s error trap, but in Bash 3 it does not. That's why the tests were passing on OS X (Bash 3) but not Linux (Bash 4).

We can work around the problem by choosing an incrementation expression that never evaluates to 0, such as `+=` or the pre-increment `++` operator. For consistency and clarity, I've changed to `x+=1` everywhere.

Ref. #25, #27
2013-10-28 21:01:51 -05:00

52 lines
1.0 KiB
Bash
Executable File

#!/usr/bin/env bash
set -e
encode_name() {
local name="$1"
local result="test_"
if [[ ! "$name" =~ [^[:alnum:]\ _-] ]]; then
name="${name//_/-5f}"
name="${name//-/-2d}"
name="${name// /_}"
result+="$name"
else
local length="${#name}"
local char i
for ((i=0; i<length; i++)); do
char="${name:$i:1}"
if [ "$char" = " " ]; then
result+="_"
elif [[ "$char" =~ [[:alnum:]] ]]; then
result+="$char"
else
result+="$(printf -- "-%02x" \'"$char")"
fi
done
fi
echo "$result"
}
tests=()
index=0
while IFS= read -r line; do
let index+=1
quoted_name="$(expr "$line" : ' *@test *\([^ ].*\) *{ *$' || true)"
if [ -n "$quoted_name" ]; then
name="$(eval echo "$quoted_name")"
encoded_name="$(encode_name "$name")"
tests["${#tests[@]}"]="$encoded_name"
echo "${encoded_name}() { bats_test_begin ${quoted_name} ${index}"
else
printf "%s\n" "$line"
fi
done
for test_name in "${tests[@]}"; do
echo "bats_test_function ${test_name}"
done