[Tests] add try/try_err helpers; convert tests to use them

Add `try` and `try_err` helper functions to `test/common.sh` that capture stdout/stderr and exit code from a single invocation, eliminating duplicate command executions in tests.
Convert all existing tests that used the `OUTPUT`/`EXIT_CODE` double-invocation pattern to use the new helpers.
Also fixes a pre-existing bug in the `nvm_die_on_prefix` test where ASCII apostrophes were used instead of U+2019 to match nvm.sh output.
This commit is contained in:
Jordan Harband
2026-03-13 15:26:07 -04:00
parent 4c556a19b0
commit 14d01c6877
28 changed files with 329 additions and 365 deletions

View File

@@ -12,24 +12,23 @@ cleanup() {
\. ../../common.sh
for f in ../../../test/fixtures/nvmrc/test/fixtures/valid/*; do
STDOUT="$(nvm_process_nvmrc $f/.nvmrc 2>/dev/null)"
EXIT_CODE="$(nvm_process_nvmrc $f/.nvmrc >/dev/null 2>/dev/null; echo $?)"
try nvm_process_nvmrc $f/.nvmrc
EXPECTED="$(nvm_json_extract node < "${f}/expected.json" | tr -d '"')"
[ "${EXIT_CODE}" = "0" ] || die "$(basename "${f}"): expected exit code of 0 but got ${EXIT_CODE}"
[ "${CAPTURED_EXIT_CODE}" = "0" ] || die "$(basename "${f}"): expected exit code of 0 but got ${CAPTURED_EXIT_CODE}"
[ "${STDOUT}" = "${EXPECTED}" ] || die "$(basename "${f}"): expected STDOUT of \`${EXPECTED}\` but got \`${STDOUT}\`"
[ "${CAPTURED_STDOUT}" = "${EXPECTED}" ] || die "$(basename "${f}"): expected STDOUT of \`${EXPECTED}\` but got \`${CAPTURED_STDOUT}\`"
done
for f in ../../../test/fixtures/nvmrc/test/fixtures/invalid/*; do
STDOUT="$(nvm_process_nvmrc $f/.nvmrc 2>/dev/null)"
STDERR="$(nvm_process_nvmrc $f/.nvmrc 2>&1 >/dev/null | awk '{if(NR > 8) print $0}' | strip_colors)"
EXIT_CODE="$(nvm_process_nvmrc $f/.nvmrc >/dev/null 2>/dev/null; echo $?)"
try nvm_process_nvmrc $f/.nvmrc
try_err nvm_process_nvmrc $f/.nvmrc
STDERR="$(echo "$CAPTURED_STDERR" | awk '{if(NR > 8) print $0}' | strip_colors)"
EXPECTED="$(nvm_json_extract < "${f}/expected.json" | tr -d '"')"
[ "${EXIT_CODE}" != "0" ] || die "$(basename "${f}"): expected exit code of 'not 0' but got ${EXIT_CODE}"
[ "${CAPTURED_EXIT_CODE}" != "0" ] || die "$(basename "${f}"): expected exit code of 'not 0' but got ${CAPTURED_EXIT_CODE}"
[ "${STDERR}" = "${EXPECTED}" ] || die "$(basename "${f}"): expected STDERR of \`${EXPECTED}\` but got \`${STDERR}\`"
done