| 1 | #!/bin/sh |
| 2 | TEST_PREFIX="[flow-control]" |
| 3 | . "$(cd "$(dirname "$0")/.." && pwd)/test_harness.sh" |
| 4 | |
| 5 | section "1. exit" |
| 6 | compare_exit "exit 0" 'exit 0' |
| 7 | compare_exit "exit 1" 'exit 1' |
| 8 | compare_exit "exit 42" 'exit 42' |
| 9 | compare_exit "exit no arg uses last status" 'false; exit' |
| 10 | compare_exit "exit 255 wraps" 'exit 255' |
| 11 | |
| 12 | section "2. return" |
| 13 | compare_output "return from function" 'f() { echo before; return; echo after; }; f' |
| 14 | compare_exit "return with code" 'f() { return 5; }; f' |
| 15 | compare_output "return preserves code" 'f() { return 3; }; f; echo $?' |
| 16 | compare_output "return only affects function" 'f() { return 0; }; f; echo after' |
| 17 | compare_exit "return outside function fails" 'return 0 2>/dev/null' |
| 18 | |
| 19 | section "3. break" |
| 20 | compare_output "break exits loop" 'for i in 1 2 3 4 5; do if [ $i -eq 3 ]; then break; fi; echo $i; done' |
| 21 | compare_output "break in while loop" 'i=0; while true; do i=$((i+1)); if [ $i -eq 3 ]; then break; fi; echo $i; done' |
| 22 | compare_output "break N exits nested loops" 'for i in 1 2; do for j in a b; do if [ "$j" = "b" ]; then break 2; fi; echo "$i$j"; done; done' |
| 23 | compare_output "break 1 same as break" 'for i in 1 2 3; do if [ $i -eq 2 ]; then break 1; fi; echo $i; done' |
| 24 | compare_output "break from inner loop only" 'for i in 1 2; do for j in a b c; do if [ "$j" = "b" ]; then break; fi; echo "$i$j"; done; echo "outer$i"; done' |
| 25 | |
| 26 | section "4. continue" |
| 27 | compare_output "continue skips iteration" 'for i in 1 2 3 4 5; do if [ $i -eq 3 ]; then continue; fi; echo $i; done' |
| 28 | compare_output "continue in while loop" 'i=0; while [ $i -lt 5 ]; do i=$((i+1)); if [ $i -eq 3 ]; then continue; fi; echo $i; done' |
| 29 | compare_output "continue N in nested loops" 'for i in 1 2; do for j in a b c; do if [ "$j" = "b" ]; then continue 2; fi; echo "$i$j"; done; done' |
| 30 | compare_output "continue 1 same as continue" 'for i in 1 2 3; do if [ $i -eq 2 ]; then continue 1; fi; echo $i; done' |
| 31 | |
| 32 | section "5. colon and true/false" |
| 33 | compare_exit ": is no-op with exit 0" ':' |
| 34 | compare_exit "true exits 0" 'true' |
| 35 | compare_exit "false exits 1" 'false' |
| 36 | compare_exit ": with arguments still exits 0" ': some args here' |
| 37 | compare_output ": does not produce output" ': hello; echo $?' |
| 38 | |
| 39 | print_summary |