Wren Linux

wren-linux / tools / test-tty-read.sh

#!/bin/bash
# Checks tty_read (lib/core.sh), which every question of Wren Linux's scripts reads its answer
# with: a pasted answer comes wrapped in the terminal's paste markers (bracketed paste, ESC[200~
# and ESC[201~), which plain read keeps; they must not end up in the answer (a bridge line or a
# web address starting ^[[200~). Answers come from a file, as for the other tests' questions.
# Run by test.sh, or:  bash tools/test-tty-read.sh
HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
T=$(mktemp -d) || { echo "  FAIL  couldn't make a temp folder (is /tmp full?)"; exit 1; }
trap 'rm -rf "$T"' EXIT
fails=0
check() { # DESCRIPTION CONDITION-COMMAND...
    local what=$1
    shift
    if "$@" >/dev/null 2>&1; then printf '  ok    %s\n' "$what"; else printf '  FAIL  %s\n' "$what"; fails=$((fails + 1)); fi
}
# answer LINE: what tty_read makes of LINE, typed or pasted
answer() {
    printf '%s\n' "$1" >"$T/answers"
    WREN_TEST_ANSWERS="$T/answers" bash -c '. "$1/lib.sh" >/dev/null 2>&1; set +e; tty_read a "> " 2>/dev/null; printf "%s" "$a"' _ "$HERE"
}
line='obfs4 192.0.2.1:443 ABCDEF cert=xyz iat-mode=0'
check "a pasted answer comes without the paste markers" test "$(answer $'\e[200~'"$line"$'\e[201~')" = "$line"
check "...a pasted web address too, which is then taken for one" test "$(answer $'\e[200~https://github.com/\e[201~')" = "https://github.com/"
check "a typed answer stays as it is" test "$(answer "$line")" = "$line"
check "...and text that only looks like a marker stays (no ESC: not one)" test "$(answer 'a[200~b')" = 'a[200~b'

[ "$fails" -eq 0 ]