Skip to content

Commit

Permalink
Add tests for error cases
Browse files Browse the repository at this point in the history
  • Loading branch information
tesujimath committed Oct 27, 2024
1 parent f2afb5d commit 1e189ad
Show file tree
Hide file tree
Showing 8 changed files with 31 additions and 5 deletions.
5 changes: 3 additions & 2 deletions bash-env-json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ function capture() {
local -n _capture_env="$1"
local -n _capture_shellvars="$2"
local _name _value
local -A _omit_shellvars=([_value]=X [BASH_LINENO]=X)
# some shell variables leak into our environment, so inhibit that:
local -A _inhibit_shellvars=([_value]=X [BASH_LINENO]=X [COLUMNS]=X [LINES]=X)

# environment variables
while IFS='=' read -r -d '' _name _value; do
Expand All @@ -44,7 +45,7 @@ function capture() {
set | sed -n -e '/^[a-zA-Z_][a-zA-Z_0-9]*=/s/=.*$//p'
set +o posix
); do
if test -v "$_name" -a ! "${_capture_env[$_name]+EXISTS}" -a ! "${_omit_shellvars[$_name]+EXISTS}"; then
if test -v "$_name" -a ! "${_capture_env[$_name]+EXISTS}" -a ! "${_inhibit_shellvars[$_name]+EXISTS}"; then
_capture_shellvars["$_name"]="${!_name}"
fi
done
Expand Down
25 changes: 22 additions & 3 deletions tests.bats
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
#!/usr/bin/env bats

function test_case() {
. "tests/${2:-$1}.setup.env"
local _setup_file="tests/$1.setup.env"
local _test_file="tests/$1.env"
local _expected_output="tests/$1.json"

# setup cleans the environment of the unexpected
. "$_setup_file"

# args after the first two are passed through verbatim
shift
echo "$@"

# sort and remove `meta` before comparison with expected output
bash-env-json "tests/$1.env" | jq --sort-keys 'del(.meta)' | diff -w - "tests/${2:-$1}.json"
bash-env-json "$@" "$_test_file" | jq --sort-keys 'del(.meta)' | diff -w - "$_expected_output"
}

@test "empty" {
Expand All @@ -27,5 +37,14 @@ function test_case() {
}

@test "ming-the-merciless" {
test_case "Ming's menu of (merciless) monstrosities" ming-the-merciless
test_case "Ming's menu of (merciless) monstrosities"
}

@test "error" {
test_case error
}


@test "shell-function-error" {
test_case shell-function-error --shellfns f
}
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions tests/error.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"error": "tests/error.env: line 4: @oops: command not found"
}
Empty file added tests/error.setup.env
Empty file.
3 changes: 3 additions & 0 deletions tests/shell-function-error.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"error": "tests/shell-function-error.env: line 2: whacky-doodle-doo: command not found"
}
Empty file.

0 comments on commit 1e189ad

Please sign in to comment.