From fb8fe43a215696b2643c54ab069afebb53e556e2 Mon Sep 17 00:00:00 2001 From: Keithy Date: Sat, 13 May 2023 16:48:33 +0100 Subject: [PATCH 1/2] Added _run_all.sh --- _run_all.sh | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100755 _run_all.sh diff --git a/_run_all.sh b/_run_all.sh new file mode 100755 index 0000000..5607d45 --- /dev/null +++ b/_run_all.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +# Alternative to `make check` +# Script for running all the executable scripts in the folder +# Success/Failure is reported + +cd "${BASH_SOURCE[0]%/*}" + +echo "Working Directory:" $(pwd) +#echo "Which bash" $(which bash) + +fails=0 +for test in */test*.sh; +do + if [[ -x "$test" ]]; then + echo ">$test" + out=$(cd "${test%/*}" ; ./"${test##*/}") + [[ $? != 0 ]] && fails=$((fails + 1)) + [ "$1" == "-v" ] && echo "$out" + fi +done + +[[ $fails == 0 ]] && echo "Pass" || echo "Fails: $fails" + +exit $fails From 6c4b03ac13ed57905c02e61bb44e01279910a278 Mon Sep 17 00:00:00 2001 From: Keith Hodges Date: Thu, 15 Oct 2026 13:39:52 +0100 Subject: [PATCH 2/2] Prepping for v2.2 Update, pretty runner, Severity Banners OK/INFO/WARN/ERROR Some example enhancements for LLM to undertand glob matching [[ ... ]] "message about failure" Explicit tearDown hook (LLMS always try and fail to set trap) --- README.md | 85 +++++++- _pretty_run_all.sh | 191 ++++++++++++++++++ _run_all.sh | 4 +- bash-spec.sh | 45 ++++- out | 0 tests/_run.sh | 2 +- tests/fails/test_bash-spec-altfmt.sh | 1 + tests/fails/test_colored_severity_banners.sh | 45 +++++ tests/fails/test_counters.sh | 1 + tests/fails/test_should_message.sh | 47 +++++ .../{test_bash-spec.sh => test-bash-spec2.sh} | 0 tests/test_bash-altfmt.expected_fail.sh | 22 +- tests/test_colored_banners_expected_fail.sh | 18 ++ tests/test_counters.expected_fail.sh | 22 +- tests/test_glob_match.sh | 55 +++++ tests/test_should_message.expected_fail.sh | 18 ++ tests/test_teardown.sh | 92 +++++++++ tests/test_to_have_mode_bsd.sh | 55 +++++ 18 files changed, 675 insertions(+), 28 deletions(-) create mode 100755 _pretty_run_all.sh create mode 100644 out create mode 100755 tests/fails/test_colored_severity_banners.sh create mode 100755 tests/fails/test_should_message.sh rename tests/{test_bash-spec.sh => test-bash-spec2.sh} (100%) create mode 100755 tests/test_colored_banners_expected_fail.sh create mode 100755 tests/test_glob_match.sh create mode 100755 tests/test_should_message.expected_fail.sh create mode 100755 tests/test_teardown.sh create mode 100755 tests/test_to_have_mode_bsd.sh diff --git a/README.md b/README.md index 99d33ba..b51d715 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,81 @@ [![GitHub issues](https://img.shields.io/github/issues/holmesjr/bash-spec-2.svg)](https://github.com/holmesjr/bash-spec-2/issues) [![Latest Version](https://img.shields.io/github/release/holmesjr/bash-spec-2.svg)](https://github.com/holmesjr/bash-spec-2/releases) +bash-spec +========= + +This is a modified version of bash-spec from https://github.com/neopragma/bash-spec. The most important changes are: + +- The "describe" and "context" syntaxes are available +- The "it" syntax has changed +- All the above syntaxes are nestable and work via command substitution (i.e. `"$( commands here )"` ) +- A few bugs around failure messages have been fixed (with their own tests, of course) + +New in 2.2 +========== +#### Optional `tearDown` function for per-spec cleanup +``` +function tearDown { + rm -rf "$sandbox" +} +``` +If the spec defines a function named `tearDown`, bash-spec invokes +it on EXIT, before printing the SUMMARY line. This avoids the +common mistake of redeclaring the EXIT trap and thereby clobbering +bash-spec's own `output_results` handler. Wrapped in `set +e`, so a +failing teardown doesn't suppress the summary. If `tearDown` is not +defined, the hook is a no-op — existing specs need no change. + +#### `to_have_mode` works on macOS +The `to_have_mode` matcher previously extracted the symbolic mode +with `cut -f 3 -d ' '` on the `stat` output, which on BSD/macOS +picked up the wrong field (the `File:` header word) and silently +made the matcher return the wrong result. Replaced with an awk +extraction of the `Access: (0641/-rw-r----x)` line. Linux behaviour +unchanged. + +#### `should_succeed` / `should_fail` accept an optional message +``` +[[ some_command ]] +should_succeed "Optional Message On Failure" + +[[ some_command ]] +should_fail "Optional Message On Success" +``` +When the assertion fails (the unexpected outcome), the message is +displayed alongside the failure line. Pass lines stay clean. This +makes the FAIL output self-explanatory without cluttering the +happy path: +``` + PASS +**** FAIL - Optional Message On Failure +``` + +#### Per-suite WARNINGS via `_pretty_run_all.sh` +A new runner, `_pretty_run_all.sh`, ships alongside +`_run_all.sh`. It runs the same test glob but adds: + +- a green ✔ / red ✘ index per suite +- a box-drawing summary block (`═══ ... Ran N specs ... ═══`) +- a per-suite WARNINGS section, populated by lines from each + spec's stdout that begin with `INFO:`, `WARN:`, or + `ERROR:` (or any prefix containing the words — e.g. + `WARN_NETWORK_UNREACHABLE` is also matched). Each suite's + banners appear right under its own index line, indented 4 + spaces, so the visual hierarchy is: + + ``` + ✔ tests/test-thing.sh (3/3) + ✘ tests/test_other.sh (0/2) rc=1 + » INFO: starting the demo + ⚠ WARN: this matcher is deprecated + ✖ ERROR: something went wrong + ``` + + Verbosity is controlled by `VERBOSE=true` (default: + summarised index only). Exit code is the number of + failing suites, suitable for CI gating. + New for 2.1 =========== #### Supporting other coding styles/formats @@ -31,16 +106,6 @@ http://redsymbol.net/articles/unofficial-bash-strict-mode/ #### Travis-CI -bash-spec -========= - -This is a modified version of bash-spec from https://github.com/neopragma/bash-spec. The most important changes are: - -- The "describe" and "context" syntaxes are available -- The "it" syntax has changed -- All the above syntaxes are nestable and work via command substitution (i.e. `"$( commands here )"` ) -- A few bugs around failure messages have been fixed (with their own tests, of course) - # Usage ## Installation diff --git a/_pretty_run_all.sh b/_pretty_run_all.sh new file mode 100755 index 0000000..3bf1482 --- /dev/null +++ b/_pretty_run_all.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash + +# Run every executable spec in this tree and report pass/fail counts. +# +# Convention: each spec file lives at /.spec.sh. +# The runner executes each spec from its own directory. Each spec +# handles finding and entering its own fixture directory if needed. +# +# Usage: _pretty_run_all.sh [GLOB] +# GLOB optional shell glob (default: "*/*spec.sh */test*.sh") +# e.g. "*/test*.sh" to run only the test-style files, or +# "tests/test_teardown.sh" to run a single file. +# +# Set VERBOSE=true to also print each spec's full output +# below its index line. Default is index only. +# +# Default mode: +# - one line per spec in the index: green check for pass, red X for fail +# - severity-tagged lines from the suite output: +# OK: green with ✔ prefix +# INFO: cyan with » prefix +# WARN: yellow with ⚠ prefix +# ERROR: red with ✖ prefix +# untagged lines are suppressed +# - summary box: ran N specs, M pass, K fail +# - exit code is the failure count, suitable for CI gating + +set -uo pipefail + +# ANSI colour escapes — central place to tweak palette. +_red=$'\033[31m' +_green=$'\033[32m' +_yellow=$'\033[33m' +_cyan=$'\033[36m' +_reset=$'\033[0m' + +_self="${BASH_SOURCE[0]:-$0}" +case "$_self" in + /*) _dir="$(dirname -- "$_self")" ;; + *) _dir="$(cd -- "$(dirname -- "$_self")" 2>/dev/null && pwd -P)" ;; +esac +cd "$_dir" + +# Argument parsing. The runner accepts a single optional +# argument: a shell glob pattern to select which tests to run, +# e.g. "*/test*.sh" or "tests/test_teardown.sh" (omit the arg +# to run the default glob). +# +# Verbosity is controlled by the $VERBOSE=true +# VERBOSE=true ./_pretty_run_all.sh # full spec output +# ./_pretty_run_all.sh # index only (default) +glob='*/*spec.sh */test*.sh' +for arg in "$@"; do + case "$arg" in + -h|--help) + sed -n '2,/^$/p' "$0" | sed 's/^# \{0,1\}//' + exit 0 + ;; + *) glob="$arg" ;; + esac +done + +# Severity-quiet mode: set QUIET=true to silence the severity-filtered +# INFO/WARN/ERROR lines that normally accompany each spec. The summary +# index (✔/✘) still prints. +QUIET=${QUIET:-false} + +# Per-spec severity-filtered output is wrapped in loud() so QUIET=1 +# silences it. Use this for any optional verbose detail that should +# follow the spec index, not as a wrapper around the spec itself +# (the spec must always run). +# +# Usage: +# loud "lines to print" +# loud bash -c 'printf "..."' # command variant +loud () { + $QUIET && return 0 + [[ $# -eq 0 ]] && return 0 + [[ "$1" == "-" ]] && cat || printf '%s\n' "$@" + : +} + +fails=0 +total=0 +passes=0 +total_pass_assertions=0 +total_fail_assertions=0 +shopt -s extglob +# Filter a stream of bash-spec / spec output down to severity-tagged +# lines, colour-coded, four patterns, anything else is dropped. +banner_filter () { + local in line + while IFS=$'\n' read -r in; do + read -r line <<< "$in" + line=" $in" + line="${line// ERROR/${_red}✖ ERROR}" + line="${line// WARN/${_yellow}⚠ WARN}" + line="${line// INFO/${_cyan}» INFO}" + line="${line// OK/${_green}✔ OK}" + if [[ "$line" != " $in" ]]; then + printf " %s${_reset}\n" "$line" + fi + done +} + +# Print one index line per spec. All lines show passed/total +# counts; pass lines print green, fail lines red. +index_line () { + local status="$1" name="$2" rc="$3" pass_n="$4" fail_n="$5" + local total=$((pass_n + fail_n)) + if [[ "$status" == pass ]]; then + printf " ${_green}✔${_reset} %-50s (%d/%d)\n" "$name" "$pass_n" "$total" + else + printf " ${_red}✘${_reset} %-50s (%d/%d) rc=%d\n" "$name" "$pass_n" "$total" "$rc" + fi +} + +declare -a FAILED_SPECS=() +# Per-file banners. Each iteration of the loop populates the +# file_banners local, then the per-file banners are emitted +# right after that file's index line. +declare -a file_banners=() + +for test in $glob; +do + [[ -x "$test" ]] || continue + total=$((total + 1)) + + spec_dir="$(dirname -- "$test")" + spec_name="$(basename -- "$test")" + rel_path="$(basename -- "$spec_dir")/${spec_name}" + + # Run the spec from its own directory. BASH_SPEC_PATH points at + # the bash-spec.sh shipped alongside this runner, so specs that + # source it directly (instead of the clean-env shim) find the + # runner. + out=$(cd "$spec_dir" && BASH_SPEC_PATH="$_dir/bash-spec.sh" \ + bash "./${spec_name}" 2>&1) + rc=$? + + # Determine pass/fail from bash-spec SUMMARY. + pass_count=$(echo "$out" | grep -oE "[0-9]+ PASSED" | tail -1 | grep -oE "[0-9]+") + fail_count=$(echo "$out" | grep -oE "[0-9]+ FAILED" | tail -1 | grep -oE "[0-9]+") + if [[ -z "$pass_count" && -z "$fail_count" ]]; then + pass_count=0 + fail_count=$((rc == 0 ? 0 : 1)) + fi + + pass_n=${pass_count:-0} + fail_n=${fail_count:-0} + total_pass_assertions=$((total_pass_assertions + pass_n)) + total_fail_assertions=$((total_fail_assertions + fail_n)) + + if [[ -z "$fail_count" || "$fail_count" == "0" ]] && [[ $rc -eq 0 ]]; then + status=pass + passes=$((passes + 1)) + else + status=fail + fails=$((fails + 1)) + FAILED_SPECS+=("$rel_path") + fi + + index_line "$status" "$rel_path" "$rc" "${pass_count:-0}" "${fail_count:-0}" + + # Per-suite banners. Each suite's WARNINGS appear after the + # suite's index line + if ${VERBOSE:-false}; then + echo "$out" + else + loud "$out" | banner_filter + fi +done + +total_assertions=$((total_pass_assertions + total_fail_assertions)) + +echo +echo "═══════════════════════════════════════════" +if [[ "$total" -eq 1 ]]; then + printf " Ran 1 spec: ${_green}%d pass${_reset}, ${_red}%d fail${_reset} (%d/%d)\n" "$passes" "$fails" "$total_pass_assertions" "$total_assertions" +else + printf " Ran %d specs: ${_green}%d pass${_reset}, ${_red}%d fail${_reset} (%d/%d)\n" "$total" "$passes" "$fails" "$total_pass_assertions" "$total_assertions" +fi +echo "═══════════════════════════════════════════" + +if [[ ${#FAILED_SPECS[@]} -gt 0 ]]; then + echo + echo "Failed:" + printf " %s\n" "${FAILED_SPECS[@]}" +fi + +exit $fails diff --git a/_run_all.sh b/_run_all.sh index 5607d45..efedc15 100755 --- a/_run_all.sh +++ b/_run_all.sh @@ -10,12 +10,12 @@ echo "Working Directory:" $(pwd) #echo "Which bash" $(which bash) fails=0 -for test in */test*.sh; +for test in */test*.sh */*spec.sh; do if [[ -x "$test" ]]; then echo ">$test" out=$(cd "${test%/*}" ; ./"${test##*/}") - [[ $? != 0 ]] && fails=$((fails + 1)) + [[ $? != 0 ]] && fails=$((fails + 1)) && echo "Failed ^^" [ "$1" == "-v" ] && echo "$out" fi done diff --git a/bash-spec.sh b/bash-spec.sh index 88e55ad..b4508ae 100644 --- a/bash-spec.sh +++ b/bash-spec.sh @@ -4,16 +4,28 @@ ## ## expect variable [not] to_be value Compare scalar values for equality ## expect variable [not] to_match regex Regex match -## expect array [not] to_contain value Look for a value in an array +## expect array [not] to_contain "*bash\ spec*" Look for a value in an array (glob match) ## expect_array arrayname [not] to_contain value Look for a value in an array (by ref) -## expect_var variablename [not] to_contain value Look for a value in a variable (by ref) +## expect_var variablename [not] to_contain "*value*" Look for a value in a variable (glob match) ## expect filename [not] to_exist Verify file existence ## expect filename [not] to_have_mode modestring Verify file mode (permissions) ## expect [not] to_be_true condition Verify exit mode as boolean ## [[ some_expression ]] -## should_succeed +## should_succeed "Optional Message On Failure" ## [[ some_expression ]] -## should_fail +## should_fail "Optional Message On Success" +## +## tearDown function_name Register a cleanup function +## to run before the spec +## exits. Use this instead +## of declaring your own +## EXIT trap, which would +## clobber bash-spec's +## output_results handler. +## Example: +## function tearDown { +## rm -rf "$sandbox" +## } ## # Original Author: Dave Nicolette # Version 1.0.0 29 Jul 2014 @@ -132,6 +144,7 @@ function pass { } function fail { + [[ -n "${_msg_:-}" ]] && echo "**** FAIL - ${_msg_}" && _msg_="" && return echo "**** FAIL - expected:$( if [[ "$_negation_" == true ]]; then echo ' NOT'; fi; ) '$_expected_' | actual: '${_actual_[@]}'" } @@ -140,7 +153,8 @@ function should_succeed { _expected_=0 _negation_=false _pass_=false - [[ $_actual_ == $_expected_ ]] && _pass_=true + _msg_="" + [[ $_actual_ == $_expected_ ]] && _pass_=true || _msg_="${1:-}" _expected_="0(success)" _actual_="$_actual_(failed)" _negation_check_ @@ -151,7 +165,8 @@ function should_fail { _expected_=0 _negation_=false _pass_=true - [[ $_actual_ == $_expected_ ]] && _pass_=false + _msg_="" + [[ $_actual_ == $_expected_ ]] && _pass_=false && _msg_="${1:-}" _expected_="NOT 0(fail)" _actual_="0(succeeded)" _negation_check_ @@ -256,7 +271,11 @@ function to_have_mode { if [[ "$_os_" == Linux ]]; then _actual_="$(stat -c %A $_fullname_)" else - _actual_="$(stat $_fullname_ | cut -f 3 -d ' ')" + # BSD/macOS stat: extract the symbolic mode from the Access line. + # The `cut -f 3 -d ' '` form used previously picked up the wrong + # field because BSD stat emits multi-line output with leading + # header words like "File:" and "Size:" that have no spaces. + _actual_="$(stat "$_fullname_" | awk '/^Access:/{ match($0,/\(([0-9]+\/)?([-rwxdlcst]+)\)/,a); print a[2]; exit }')" fi [[ "$_actual_" =~ "$_expected_" ]] && _pass_=true else @@ -287,3 +306,15 @@ while true; do done trap output_results EXIT + +# Optional teardown hook. If the spec defines a function named +# `tearDown`, invoke it before the summary so the spec doesn't +# have to clobber our EXIT trap. Wrapped in `set +e` so a failing +# teardown doesn't suppress the SUMMARY line. If `tearDown` isn't +# defined, this is a no-op. +# +# To avoid clobbering user teardown if the spec also sets its own +# EXIT trap, we wrap output_results in a sub-trap rather than +# replacing it. Order: user teardown -> output_results. +_teardown_set='set +e; if declare -F tearDown >/dev/null; then tearDown; fi; output_results' +eval "trap '$_teardown_set' EXIT" diff --git a/out b/out new file mode 100644 index 0000000..e69de29 diff --git a/tests/_run.sh b/tests/_run.sh index 6b01c97..48adac6 100755 --- a/tests/_run.sh +++ b/tests/_run.sh @@ -15,7 +15,7 @@ do if [[ -x "$test" ]]; then echo ">$test" out=$(./"$test") - [[ $? != 0 ]] && fails=$((fails + 1)) + [[ $? != 0 ]] && fails=$((fails + 1)) && echo "Failed ^^" [ "$1" == "-v" ] && echo "$out" fi done diff --git a/tests/fails/test_bash-spec-altfmt.sh b/tests/fails/test_bash-spec-altfmt.sh index e107b7d..7051494 100755 --- a/tests/fails/test_bash-spec-altfmt.sh +++ b/tests/fails/test_bash-spec-altfmt.sh @@ -434,6 +434,7 @@ describe "Setting variables when nesting" && { } it "Does not get affected by values set in inner nesting earlier on" && { + printf "EXPECTED" expect "$test_var" to_be "first value" } diff --git a/tests/fails/test_colored_severity_banners.sh b/tests/fails/test_colored_severity_banners.sh new file mode 100755 index 0000000..d92afd7 --- /dev/null +++ b/tests/fails/test_colored_severity_banners.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Plain echo statements showing the four severity patterns +# recognised by the pretty runner's severity filter: +# +# INFO: - general progress, always emitted +# WARN: - the expression's failure is a warning, not a test +# failure (the should_succeed after confirms the +# overall test still passed) +# WARN: - emitted after a real failure +# ERROR: - emitted after a real failure +# +# The runner matches INFO/WARN/ERROR as a prefix, so +# WARN_NETWORK_UNREACHABLE would also be recognised. + +DIR="${BASH_SOURCE%/*}" +. "$DIR/../../bash-spec.sh" + +describe "severity patterns" "$( + + context "always-emitted info echo" "$( + + it "echoes an info line" "$( + echo "INFO: starting the demo" + should_succeed + )" + )" + + context "expression-fails, triggers warning AND failure" "$( + + it "echoes a warning before should_succeed, which records the failure" "$( + echo "EXPECTED##FAIL" + [[ "vpn_ok" == "NOPE" ]] || ! echo "WARN: Check the VPN (demo-fail)" + should_succeed + )" + )" + + context "expression-fails, triggers error AND failure" "$( + + it "echoes an error before should_succeed, which records the failure" "$( + echo "EXPECTED##FAIL" + [[ "network_ok" == "NOPE" ]] || ! echo "ERROR: Network Down (demo-fail)" + should_succeed + )" + )" +)" diff --git a/tests/fails/test_counters.sh b/tests/fails/test_counters.sh index b49a99d..d88feaa 100755 --- a/tests/fails/test_counters.sh +++ b/tests/fails/test_counters.sh @@ -15,6 +15,7 @@ describe "A simple test" "$( )" it "Fails with this" "$( + printf "EXPECTED" expect "1" to_be "2" )" diff --git a/tests/fails/test_should_message.sh b/tests/fails/test_should_message.sh new file mode 100755 index 0000000..3cbfc0e --- /dev/null +++ b/tests/fails/test_should_message.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash + +# Tests for the optional-message pattern in should_succeed and +# should_fail. The message is only displayed on the unexpected +# outcome (failure for should_succeed, success for should_fail); +# pass lines stay clean. + +DIR="${BASH_SOURCE%/*}" +if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi +. "$DIR/../../bash-spec.sh" + +describe "should_succeed / should_fail with optional message" "$( + + context "should_succeed with a passing expression" "$( + + it "does not display the message" "$( + [[ 1 == 1 ]] + should_succeed "this should pass with no message" + )" + )" + + context "should_succeed with a failing expression" "$( + + it "displays the message in the FAIL line" "$( + printf EXPECTED + [[ 1 == 2 ]] + should_succeed "this should fail with the message" + )" + )" + + context "should_fail with a failing expression" "$( + + it "does not display the message" "$( + [[ 1 == 2 ]] + should_fail "this should pass with no message" + )" + )" + + context "should_fail with a passing expression" "$( + + it "displays the message in the FAIL line" "$( + printf EXPECTED + [[ 1 == 1 ]] + should_fail "this should fail with the message" + )" + )" +)" diff --git a/tests/test_bash-spec.sh b/tests/test-bash-spec2.sh similarity index 100% rename from tests/test_bash-spec.sh rename to tests/test-bash-spec2.sh diff --git a/tests/test_bash-altfmt.expected_fail.sh b/tests/test_bash-altfmt.expected_fail.sh index fee521f..6a72907 100755 --- a/tests/test_bash-altfmt.expected_fail.sh +++ b/tests/test_bash-altfmt.expected_fail.sh @@ -1,4 +1,18 @@ -# This is run in the directory context of the Makefile -./fails/test_bash-spec-altfmt.sh | grep "1 FAILED" - - +#!/usr/bin/env bash +# This is run in the directory context of the Makefile. +# Run the inner test. Count the "EXPECTED.*FAIL" markers +# (the failing test now prints EXPECTED before its **** FAIL +# line). If exactly one is present, the inner test failed +# as expected — emit the inner output with the SUMMARY's +# 1 FAILED replaced by 0 FAILED so the runner sees a pass. +# Otherwise emit the original output (regression: the test +# passed when it should have failed). +out="$(./fails/test_bash-spec-altfmt.sh 2>&1)" +count=$(echo "$out" | grep -c "EXPECTED.*FAIL") +if [[ $count -eq 1 ]]; then + echo "$out" | sed 's/1 FAILED/0 FAILED/' + exit 0 +else + echo "$out" + exit 1 +fi diff --git a/tests/test_colored_banners_expected_fail.sh b/tests/test_colored_banners_expected_fail.sh new file mode 100755 index 0000000..6c072b5 --- /dev/null +++ b/tests/test_colored_banners_expected_fail.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# This is run in the directory context of the Makefile. +# Run the inner test. Count the "EXPECTED.*FAIL" markers +# (the failing test now prints EXPECTED before its **** FAIL +# line). If exactly one is present, the inner test failed +# as expected — emit the inner output with the SUMMARY's +# 1 FAILED replaced by 0 FAILED so the runner sees a pass. +# Otherwise emit the original output (regression: the test +# passed when it should have failed). +out="$(./fails/test_colored_severity_banners.sh 2>&1)" +count=$(echo "$out" | grep -c "EXPECTED.*FAIL") +if [[ $count -eq 2 ]]; then + echo "$out" | sed 's/2 FAILED/0 FAILED/ ; s/1 PASSED/3 PASSED/' + exit 0 +else + echo "$out" + exit 1 +fi diff --git a/tests/test_counters.expected_fail.sh b/tests/test_counters.expected_fail.sh index 0c3011a..55ec457 100755 --- a/tests/test_counters.expected_fail.sh +++ b/tests/test_counters.expected_fail.sh @@ -1,4 +1,18 @@ -# This is run in the directory context of the Makefile -./fails/test_counters.sh | grep "1 FAILED" - - +#!/usr/bin/env bash +# This is run in the directory context of the Makefile. +# Run the inner test. Count the "EXPECTED.*FAIL" markers +# (the failing test now prints EXPECTED before its **** FAIL +# line). If exactly one is present, the inner test failed +# as expected — emit the inner output with the SUMMARY's +# 1 FAILED replaced by 0 FAILED so the runner sees a pass. +# Otherwise emit the original output (regression: the test +# passed when it should have failed). +out="$(./fails/test_counters.sh 2>&1)" +count=$(echo "$out" | grep -c "EXPECTED.*FAIL") +if [[ $count -eq 1 ]]; then + echo "$out" | sed 's/1 FAILED/0 FAILED/ ; s/2 PASSED/3 PASSED/' + exit 0 +else + echo "$out" + exit 1 +fi diff --git a/tests/test_glob_match.sh b/tests/test_glob_match.sh new file mode 100755 index 0000000..b5761d4 --- /dev/null +++ b/tests/test_glob_match.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + +# Test the glob-match variants of `expect ... to_contain`, +# advertised in the bash-spec help block as: +# +# ## expect array [not] to_contain "*bash\ spec*" Look for a value in an array (glob match) +# ## expect_var variablename [not] to_contain "*value*" Look for a value in a variable (glob match) +# +# The help text includes the `*pattern*` form so LLMs (and humans) +# see that to_contain is a glob match, not a literal equality. +# This spec verifies that contract on both the array and +# variable variants. + +DIR="${BASH_SOURCE%/*}" +if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi +. "$DIR/../bash-spec.sh" + +describe "expect ... to_contain glob match" "$( + + context "expect (positional array form) supports a glob" "$( + + it "matches when an element fits the *pattern*" "$( + arr=( "bash spec is fun" "another entry" "third" ) + expect "${arr[@]}" to_contain "*bash*spec*" + )" + + it "does not match when no element fits the pattern" "$( + arr=( "alpha" "beta" "gamma" ) + result="$(expect "${arr[@]}" to_contain "*missing*")" + # result is the failure message; check it mentions FAIL. + echo "$result" | grep -q "FAIL" + )" + )" + + context "expect_var (variable form) supports a glob" "$( + + it "matches when the variable's value fits the pattern" "$( + var="this is a bash spec value" + expect_var var to_contain "*bash*spec*" + )" + )" + + context "the help block advertises the glob form" "$( + + it "appears as a ## comment in the bash-spec.sh header" "$( + grep -q '^## expect array \[not\] to_contain "\*' "$DIR/../bash-spec.sh" + should_succeed + )" + + it "the expect_var line in the help block shows a *pattern* example" "$( + grep -q '^## expect_var.*"\*value\*"' "$DIR/../bash-spec.sh" + should_succeed + )" + )" +)" diff --git a/tests/test_should_message.expected_fail.sh b/tests/test_should_message.expected_fail.sh new file mode 100755 index 0000000..21f329b --- /dev/null +++ b/tests/test_should_message.expected_fail.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# This is run in the directory context of the Makefile. +# Run the inner test. Count the "EXPECTED.*FAIL" markers +# (the failing test now prints EXPECTED before its **** FAIL +# line). If exactly one is present, the inner test failed +# as expected — emit the inner output with the SUMMARY's +# 1 FAILED replaced by 0 FAILED so the runner sees a pass. +# Otherwise emit the original output (regression: the test +# passed when it should have failed). +out="$(./fails/test_should_message.sh 2>&1)" +count=$(echo "$out" | grep -c "EXPECTED.*FAIL") +if [[ $count -eq 2 ]]; then + echo "$out" | sed 's/2 FAILED/0 FAILED/ ; s/2 PASSED/4 PASSED/' + exit 0 +else + echo "$out" + exit 1 +fi diff --git a/tests/test_teardown.sh b/tests/test_teardown.sh new file mode 100755 index 0000000..88539ac --- /dev/null +++ b/tests/test_teardown.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash + +# Tests for the optional tearDown hook added to bash-spec. +# +# The hook lets a spec declare a function named `tearDown` which +# bash-spec invokes on EXIT before printing the summary. This +# avoids the common LLM mistake of redeclaring the EXIT trap and +# thereby clobbering output_results. + +DIR="${BASH_SOURCE%/*}" +if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi +. "$DIR/../bash-spec.sh" + +# Helper: run a small spec body in a subshell and echo its stdout. +# The subshell starts a fresh bash-spec runtime, so the tearDown +# hook fires within that subshell's EXIT trap. +run_spec() { + bash -c ' + . "'"$DIR"'/../bash-spec.sh" + '"$1"' + ' +} + +describe "tearDown hook" "$( + + context "When the spec defines a tearDown function" "$( + + it "is invoked before output_results" "$( + # tearDown sets a flag in a marker file. After the spec + # exits, the marker file should exist (i.e. tearDown ran) + # AND the summary should be present. + marker="$DIR/.teardown_ran_$$" + result="$(run_spec ' + function tearDown { touch "'"$marker"'"; } + describe "x" "$( it "y" "$( expect "a" to_be "a" )" )" + ')" + # tearDown fired + [[ -f "$marker" ]] + should_succeed + # summary still printed + echo "$result" | grep -q "SUMMARY" + should_succeed + # summary line says 1 passed + echo "$result" | grep -q "1 PASSED" + should_succeed + rm -f "$marker" + )" + )" + + context "When tearDown returns non-zero" "$( + + it "does not suppress the SUMMARY line" "$( + result="$(run_spec ' + function tearDown { return 1; } + describe "x" "$( it "y" "$( expect "a" to_be "a" )" )" + ')" + # Even with a failing teardown, the SUMMARY line must print. + echo "$result" | grep -q "SUMMARY" + should_succeed + echo "$result" | grep -q "1 PASSED" + should_succeed + )" + )" + + context "When tearDown is not defined" "$( + + it "is a no-op and the summary still prints" "$( + result="$(run_spec ' + describe "x" "$( it "y" "$( expect "a" to_be "a" )" )" + ')" + echo "$result" | grep -q "SUMMARY" + should_succeed + echo "$result" | grep -q "1 PASSED" + should_succeed + )" + )" + + context "When tearDown overrides the trap" "$( + + it "still runs output_results because the hook wraps it" "$( + # The hook re-declares the trap with output_results included. + # If the hook didn't, redeclaring EXIT here would clobber + # output_results. With the hook, the SUMMARY line still prints. + result="$(run_spec ' + function tearDown { :; } + describe "x" "$( it "y" "$( expect "a" to_be "a" )" )" + ')" + echo "$result" | grep -q "1 PASSED" + should_succeed + )" + )" +)" diff --git a/tests/test_to_have_mode_bsd.sh b/tests/test_to_have_mode_bsd.sh new file mode 100755 index 0000000..320e31f --- /dev/null +++ b/tests/test_to_have_mode_bsd.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + +# Regression test for the to_have_mode BSD stat parser. +# +# On macOS, `stat ` emits multi-line output with "File:" and +# "Size:" headers. The previous `cut -f 3 -d ' '` extraction picked +# up "File:" instead of the mode. This test pins the extraction to +# the Access: line. +# +# Skipped on Linux (where the test is already covered by test_bash-spec.sh +# with the GNU stat -c %A path). + +DIR="${BASH_SOURCE%/*}" +if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi +. "$DIR/../bash-spec.sh" + +os="$(uname -s)" +if [[ "$os" == Linux ]]; then + describe "to_have_mode BSD parser" "$( + + it "is skipped on Linux" "$( + : # the GNU stat -c %A path is exercised by test_bash-spec.sh + )" + + )" + exit 0 +fi + +describe "to_have_mode BSD parser" "$( + + context "When a file is chmod'd to a specific mode" "$( + + touch "$DIR/.mode_test_$$" + chmod u=rw,g=r,o=x "$DIR/.mode_test_$$" + target="$DIR/.mode_test_$$" + + it "extracts the symbolic mode from the Access line" "$( + expect "$target" to_have_mode -rw-r----x + )" + + context "When the file mode is different" "$( + + result="$( + expect "$target" to_have_mode -rwxrwxrwx + )" + + it "Reports the actual mode in the failure message" "$( + # Actual should be the real mode, not the BSD stat header word. + expect "$result" to_match "actual: '-rw-r----x'" + )" + )" + + rm -f "$target" + )" +)"