BASH_UNIT(1)

πŸ“¦
version 2.3.3 Β· 2 versions
, in ubuntu resolute, ubuntu stonking

🌸 BASH_UNIT πŸ’…

okay bestie, welcome to bash_unit β€” the bash unit testing enterprise edition framework for professionals, and yes the "enterprise edition for professionals" is doing a lot of heavy lifting there but we love it, no cap ✨


✨ SYNOPSIS ✨

bash_unit [-f tap] [-p <pattern>] [-s <pattern>] [-r] [test_file]

πŸ’– DESCRIPTION πŸ’–

so here's the vibe: bash_unit lets you write unit tests (they're literally just functions starting with test), run them, and if something goes off, it shows you the stack trace with source file and line number indications so you can actually go find the problem instead of crying. 😭 super helpful, we stan.

Need a quick start? fr fr, the getting started project at https://github.com/bash-unit/getting_started/ will get you on track in no time. πŸ¦‹

The following functions are available in your tests (detailed documentation below, keep scrolling bestie):

  • fail [message]
  • assert <assertion> [message]
  • assert_fail <assertion> [message]
  • assert_status_code <expected_status_code> <assertion> [message]
  • assert_equals <expected> <actual> [message]
  • assert_not_equals <unexpected> <actual> [message]
  • assert_matches <expected-regex> <actual> [message]
  • assert_not_matches <unexpected-regex> <actual> [message]
  • assert_within_delta <expected num> <actual num> <max delta> [message]
  • assert_no_diff <expected> <actual> [message]
  • skip_if <condition> <pattern>
  • fake <command> [replacement code]

(and btw β€” not me telling you this, but the documentation you are reading right now is itself tested with bash-unit. yes really. self-aware king behavior πŸ‘‘)

bash_unit is free software you may contribute to. See CONTRIBUTING.md.


✨ OPTIONS ✨

  • -p pattern β€” filters which tests actually run, based on the pattern you give it. You can specify several patterns by repeating this option, once for each pattern. πŸ’…
  • -s pattern β€” skips the tests whose name matches the given pattern. Same deal, you can specify several patterns by repeating this option for each one. Skipped tests will still show up in bash_unit output as skipped. (see also skip_if) πŸ™ˆ
  • -r β€” runs test cases in random order. And lowkey important: this only affects the order within a test file. Files are always executed in the order in which they are specified on the command line. πŸ”₯
  • -f output_format β€” specify an alternative output format. The only supported value is tap.
  • -q β€” quiet mode. Will only output the status of each test with no further information, even in case of failure. 🀫

🌈 GitHub Actions

Here's an example of how you could integrate bash_unit with GitHub Actions (https://docs.github.com/fr/actions):

name: bash_unit tests
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  ubuntu:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Unit testing with bash_unit
      run: |
        curl -s https://raw.githubusercontent.com/bash-unit/bash_unit/master/install.sh | bash
        FORCE_COLOR=true ./bash_unit tests/test_*

See this bash_unit getting started github project at https://github.com/pgrange/bash_unit_getting_started for a working example. 🫢


πŸŽ€ GitLab CI

And here's how you could integrate bash_unit with GitLab CI (https://docs.gitlab.com/ee/ci/):

test:
  image: debian
  script:
    - apt-get update
    - apt-get install --no-install-recommends -y curl ca-certificates
    - curl -s https://raw.githubusercontent.com/bash-unit/bash_unit/master/install.sh | bash
    - FORCE_COLOR=true ./bash_unit tests/test_*

See this bash_unit getting started gitlab project at https://gitlab.com/pgrange/bash_unit_getting_started for a working example. πŸ’œ


🧚 pre-commit hook

You can run bash_unit as a pre-commit (https://pre-commit.com) hook. iconic honestly.

Add the following to your pre-commit configuration. By default it will run scripts that are identified as shell scripts that match the path ^tests/(.*/)?test_.*\.sh$. ⭐

repos:
  - repo: https://github.com/bash-unit/bash_unit
    rev: v2.2.0
    hooks:
      - id: bash-unit
        always-run: true

πŸ’– HOW TO RUN TESTS πŸ’–

okay bestie, running your tests is literally the easiest part, no cap. you just call bash_unit and hand it all your test files as parameters. that's it. that's the whole vibe. 🫢

so like, to run some bash_unit tests, from the bash_unit directory:

./bash_unit tests/test_core.sh

Running tests in tests/test_core.sh
        Running test_assert_equals_fails_when_not_equal ... SUCCESS
        Running test_assert_equals_succeed_when_equal ... SUCCESS
        Running test_assert_fails ... SUCCESS
        Running test_assert_fails_fails ... SUCCESS
        Running test_assert_fails_succeeds ... SUCCESS
        Running test_assert_matches_fails_when_not_matching ... SUCCESS
        Running test_assert_matches_succeed_when_matching ... SUCCESS
        Running test_assert_no_diff_fails_when_diff ... SUCCESS
        Running test_assert_no_diff_succeeds_when_no_diff ... SUCCESS
        Running test_assert_not_equals_fails_when_equal ... SUCCESS
        Running test_assert_not_equals_succeeds_when_not_equal ... SUCCESS
        Running test_assert_not_matches_fails_when_matching ... SUCCESS
        Running test_assert_not_matches_succeed_when_not_matching ... SUCCESS
        Running test_assert_shows_stderr_on_failure ... SUCCESS
        Running test_assert_shows_stdout_on_failure ... SUCCESS
        Running test_assert_status_code_fails ... SUCCESS
        Running test_assert_status_code_succeeds ... SUCCESS
        Running test_assert_succeeds ... SUCCESS
        Running test_assert_within_delta_fails ... SUCCESS
        Running test_assert_within_delta_succeeds ... SUCCESS
        Running test_fail_fails ... SUCCESS
        Running test_fail_prints_failure_message ... SUCCESS
        Running test_fail_prints_where_is_error ... SUCCESS
        Running test_fake_actually_fakes_the_command ... SUCCESS
        Running test_fake_can_fake_inline ... SUCCESS
        Running test_fake_echo_stdin_when_no_params ... SUCCESS
        Running test_fake_exports_faked_in_subshells ... SUCCESS
        Running test_fake_transmits_params_to_fake_code ... SUCCESS
        Running test_fake_transmits_params_to_fake_code_as_array ... SUCCESS
        Running test_should_pretty_format_even_when_LANG_is_unset ... SUCCESS
Overall result: SUCCESS

look at that Overall result: SUCCESS, we love to see it. πŸ˜­πŸ’…


but maybe you don't wanna run everything?? maybe you're in your selective era. that's fine, you can run only specific tests with the -p option. it takes a pattern as its parameter and filters your test functions against that pattern. so like, main character energy only:

./bash_unit -p fail_fails -p assert tests/test_core.sh

Running tests in tests/test_core.sh
        Running test_assert_equals_fails_when_not_equal ... SUCCESS
        Running test_assert_equals_succeed_when_equal ... SUCCESS
        Running test_assert_fails ... SUCCESS
        Running test_assert_fails_fails ... SUCCESS
        Running test_assert_fails_succeeds ... SUCCESS
        Running test_assert_matches_fails_when_not_matching ... SUCCESS
        Running test_assert_matches_succeed_when_matching ... SUCCESS
        Running test_assert_no_diff_fails_when_diff ... SUCCESS
        Running test_assert_no_diff_succeeds_when_no_diff ... SUCCESS
        Running test_assert_not_equals_fails_when_equal ... SUCCESS
        Running test_assert_not_equals_succeeds_when_not_equal ... SUCCESS
        Running test_assert_not_matches_fails_when_matching ... SUCCESS
        Running test_assert_not_matches_succeed_when_not_matching ... SUCCESS
        Running test_assert_shows_stderr_on_failure ... SUCCESS
        Running test_assert_shows_stdout_on_failure ... SUCCESS
        Running test_assert_status_code_fails ... SUCCESS
        Running test_assert_status_code_succeeds ... SUCCESS
        Running test_assert_succeeds ... SUCCESS
        Running test_assert_within_delta_fails ... SUCCESS
        Running test_assert_within_delta_succeeds ... SUCCESS
        Running test_fail_fails ... SUCCESS
Overall result: SUCCESS

and you can also combine -p with -s to skip some of the tests. -s also takes a pattern as parameter, and it marks as skipped any test function that matches it. so basically: -p says "yes queen", -s says "not today." πŸŽ€

./bash_unit -p fail_fails -p assert -s no -s status tests/test_core.sh

Running tests in tests/test_core.sh
        Running test_assert_equals_fails_when_not_equal ... SKIPPED
        Running test_assert_matches_fails_when_not_matching ... SKIPPED
        Running test_assert_no_diff_fails_when_diff ... SKIPPED
        Running test_assert_no_diff_succeeds_when_no_diff ... SKIPPED
        Running test_assert_not_equals_fails_when_equal ... SKIPPED
        Running test_assert_not_equals_succeeds_when_not_equal ... SKIPPED
        Running test_assert_not_matches_fails_when_matching ... SKIPPED
        Running test_assert_not_matches_succeed_when_not_matching ... SKIPPED
        Running test_assert_status_code_fails ... SKIPPED
        Running test_assert_status_code_succeeds ... SKIPPED
        Running test_assert_equals_succeed_when_equal ... SUCCESS
        Running test_assert_fails ... SUCCESS
        Running test_assert_fails_fails ... SUCCESS
        Running test_assert_fails_succeeds ... SUCCESS
        Running test_assert_matches_succeed_when_matching ... SUCCESS
        Running test_assert_shows_stderr_on_failure ... SUCCESS
        Running test_assert_shows_stdout_on_failure ... SUCCESS
        Running test_assert_succeeds ... SUCCESS
        Running test_assert_within_delta_fails ... SUCCESS
        Running test_assert_within_delta_succeeds ... SUCCESS
        Running test_fail_fails ... SUCCESS
Overall result: SUCCESS

okay and here's the ✨iconic✨ part: bash_unit supports the Test Anything Protocol http://testanything.org/, so you can ask for a tap formatted output with the -f option. it's giving interoperability. πŸ”₯

./bash_unit -f tap tests/test_core.sh

# Running tests in tests/test_core.sh
ok - test_assert_equals_fails_when_not_equal
ok - test_assert_equals_succeed_when_equal
ok - test_assert_fails
ok - test_assert_fails_fails
ok - test_assert_fails_succeeds
ok - test_assert_matches_fails_when_not_matching
ok - test_assert_matches_succeed_when_matching
ok - test_assert_no_diff_fails_when_diff
ok - test_assert_no_diff_succeeds_when_no_diff
ok - test_assert_not_equals_fails_when_equal
ok - test_assert_not_equals_succeeds_when_not_equal
ok - test_assert_not_matches_fails_when_matching
ok - test_assert_not_matches_succeed_when_not_matching
ok - test_assert_shows_stderr_on_failure
ok - test_assert_shows_stdout_on_failure
ok - test_assert_status_code_fails
ok - test_assert_status_code_succeeds
ok - test_assert_succeeds
ok - test_assert_within_delta_fails
ok - test_assert_within_delta_succeeds
ok - test_fail_fails
ok - test_fail_prints_failure_message
ok - test_fail_prints_where_is_error
ok - test_fake_actually_fakes_the_command
ok - test_fake_can_fake_inline
ok - test_fake_echo_stdin_when_no_params
ok - test_fake_exports_faked_in_subshells
ok - test_fake_transmits_params_to_fake_code
ok - test_fake_transmits_params_to_fake_code_as_array
ok - test_should_pretty_format_even_when_LANG_is_unset
1..30

thirty oks and a little 1..30 at the end, we are SO back. 🌸


πŸ¦‹ HOW TO WRITE TESTS πŸ¦‹

so you wanna write some tests, bestie? say less. you write your test functions in a file, and the name of a test function has to start with test. only functions starting with test will be tested β€” everything else is just... vibes in the background. periodt.

use the bash_unit assertion functions inside your test functions, more on that below. πŸ‘‘

you may write a setup function that will be executed before each test is run. πŸŽ€

you may write a teardown function that will be executed after each test is run. 🧹

you may write a setup_suite function that will be executed only once before all the tests of your test file. ⭐

you may write a teardown_suite function that will be executed only once after all the tests of your test file. 🌈


okay now the important part, don't skip this one:

if you write code outside of any bash function, that code will be executed once at test file loading time, because your file is a bash script and bash_unit sources it before running your tests. it is suggested to write a setup_suite function and avoid any code outside a bash function. also β€” and this is a hard rule, not a suggestion β€” you must not use any bash_unit assertion in setup_suite, and you must not use exit in setup_suite, otherwise teardown_suite will not be run. see issue 43 https://github.com/bash-unit/bash_unit/issues/43 for more details. πŸ‘€

πŸ’€ yeah this one bites people. no assertions and no exit in setup_suite, or your teardown_suite just ghosts you.

if you want to keep an eye on a test that's not yet implemented, prefix the name of the function by todo instead of test. tests to do are not executed and do not impact the global status of your test suite, but they are displayed in bash_unit output. it's like a little bookmark for your future self. πŸ™ˆ

also, bash_unit changes the current working directory to the one of the running test file. so if you need to access files from your test code β€” for instance the script under test β€” use paths relative to the test file. iykyk. 🫢

and lastly, you may need to change the behavior of some commands to create the right conditions for your code under test to behave as expected. the fake function may help you do that, see below. πŸ’…

✨ TEST FUNCTIONS ✨

okay bestie, this is the part where it gets good. bash_unit ships with a whole lil arsenal of shell oriented assertion functions β€” they're the little besties you call from inside your tests to say "hey, this better be true or I'm gonna scream." πŸ’–


πŸ’… fail

fail [message]

Straight up fails the test, periodt. You can hand it an optional message and it'll show that too.

test_can_fail() {
  fail "this test failed on purpose"
}
        Running test_can_fail ... FAILURE
this test failed on purpose
doc:2:test_can_fail()

πŸŽ€ assert

assert <assertion> [message]

Evaluates assertion and fails if the assertion fails. An assertion fails if its evaluation returns a status code different from 0 β€” that's the whole rule, no cap.

In case of failure, the standard output and standard error of the evaluated assertion get displayed, and the optional message shows up too.

test_assert_fails() {
  assert false "this test failed, obviously"
}
test_assert_succeed() {
  assert true
}
        Running test_assert_fails ... FAILURE
this test failed, obviously
doc:2:test_assert_fails()
        Running test_assert_succeed ... SUCCESS

But you probably wanna assert stuff that isn't obvious, bestie. 🌸

code() {
  touch /tmp/the_file
}

test_code_creates_the_file() {
  code

  assert "test -e /tmp/the_file"
}

test_code_makes_the_file_executable() {
  code

  assert "test -x /tmp/the_file" "/tmp/the_file should be executable"
}
        Running test_code_creates_the_file ... SUCCESS
        Running test_code_makes_the_file_executable ... FAILURE
/tmp/the_file should be executable
doc:14:test_code_makes_the_file_executable()

It may also be fun to use assert to check for the expected content of a file. and by "fun" I mean "the moment of truth" energy 😭

code() {
  echo 'not so cool' > /tmp/the_file
}

test_code_write_appropriate_content_in_the_file() {
  code

  assert "diff <(echo 'this is cool') /tmp/the_file"
}
        Running test_code_write_appropriate_content_in_the_file ... FAILURE
out> 1c1
out> < this is cool
out> ---
out> > not so cool
doc:8:test_code_write_appropriate_content_in_the_file()

🫢 assert_fail

assert_fail <assertion> [message]

Asserts that assertion fails. It's the literal opposite of assert β€” the hater of the group, in the best possible way.

assertion fails if its evaluation returns a status code different from 0.

If the evaluated expression does not fail, then assert_fail will fail and display the standard output and error of the evaluated assertion. The optional message is also displayed.

code() {
  echo 'not so cool' > /tmp/the_file
}

test_code_does_not_write_cool_in_the_file() {
  code

  assert_fails "grep cool /tmp/the_file" "should not write 'cool' in /tmp/the_file"
}

test_code_does_not_write_this_in_the_file() {
  code

  assert_fails "grep this /tmp/the_file" "should not write 'this' in /tmp/the_file"
}
        Running test_code_does_not_write_cool_in_the_file ... FAILURE
should not write 'cool' in /tmp/the_file
out> not so cool
doc:8:test_code_does_not_write_cool_in_the_file()
        Running test_code_does_not_write_this_in_the_file ... SUCCESS

(yes, the examples really do call assert_fails β€” that's exactly what's written up there, I'm just the messenger πŸ’€)


πŸ”₯ assert_status_code

assert_status_code <expected_status_code> <assertion> [message]

Checks for a precise status code on the evaluation of assertion. This is highkey useful when you wanna distinguish between several error conditions in your code β€” like, not just "it broke" but "it broke in this exact way." πŸ‘‘

In case of failure, the standard output and error of the evaluated assertion is displayed. The optional message is also displayed.

code() {
  exit 23
}

test_code_should_fail_with_code_25() {
  assert_status_code 25 code
}
        Running test_code_should_fail_with_code_25 ... FAILURE
 expected status code 25 but was 23
doc:6:test_code_should_fail_with_code_25()

πŸ’œ assert_equals

assert_equals <expected> <actual> [message]

Asserts for equality of the two strings expected and actual. πŸ¦‹

test_obvious_inequality_with_assert_equals(){
  assert_equals "a string" "another string" "a string should be another string"
}
test_obvious_equality_with_assert_equals(){
  assert_equals a a
}
        Running test_obvious_equality_with_assert_equals ... SUCCESS
        Running test_obvious_inequality_with_assert_equals ... FAILURE
a string should be another string
 expected [a string] but was [another string]
doc:2:test_obvious_inequality_with_assert_equals()

🌸 assert_not_equals

assert_not_equals <unexpected> <actual> [message]

Asserts for inequality of the two strings unexpected and actual β€” the yin to assert_equals' yang ✨

test_obvious_equality_with_assert_not_equals(){
  assert_not_equals "a string" "a string" "a string should be different from another string"
}
test_obvious_inequality_with_assert_not_equals(){
  assert_not_equals a b
}
        Running test_obvious_equality_with_assert_not_equals ... FAILURE
a string should be different from another string
 expected different value than [a string] but was the same
doc:2:test_obvious_equality_with_assert_not_equals()
        Running test_obvious_inequality_with_assert_not_equals ... SUCCESS

🧚 assert_matches

assert_matches <expected-regex> <actual> [message]

Asserts that the string actual matches the regex pattern expected-regex. regex girlies rise πŸ™ˆ

test_obvious_notmatching_with_assert_matches(){
  assert_matches "a str.*" "another string" "'another string' should not match 'a str.*'"
}
test_obvious_matching_with_assert_matches(){
  assert_matches "a[nN].t{0,1}.*r str.*" "another string"
}
        Running test_obvious_matching_with_assert_matches ... SUCCESS
        Running test_obvious_notmatching_with_assert_matches ... FAILURE
'another string' should not match 'a str.*'
 expected regex [a str.*] to match [another string]
doc:2:test_obvious_notmatching_with_assert_matches()

⭐ assert_not_matches

assert_not_matches <unexpected-regex> <actual> [message]

Asserts that the string actual does not match the regex pattern unexpected-regex.

test_obvious_matching_with_assert_not_matches(){
  assert_not_matches "a str.*" "a string" "'a string' should not match 'a str.*'"
}
test_obvious_notmatching_with_assert_not_matches(){
  assert_not_matches "a str.*" "another string"
}
        Running test_obvious_matching_with_assert_not_matches ... FAILURE
'a string' should not match 'a str.*'
 expected regex [a str.*] should not match but matched [a string]
doc:2:test_obvious_matching_with_assert_not_matches()
        Running test_obvious_notmatching_with_assert_not_matches ... SUCCESS

🌈 assert_within_delta

assert_within_delta <expected num> <actual num> <max delta> [message]

Asserts that expected num matches actual num up to a given max delta.

⚠️ Heads up: this function only support integers. (their words, not mine πŸ’…)

Given an expectation of 5 and a delta of 2, this would match 3, 4, 5, 6, and 7:

test_matches_within_delta(){
  assert_within_delta 5 3 2
  assert_within_delta 5 4 2
  assert_within_delta 5 5 2
  assert_within_delta 5 6 2
  assert_within_delta 5 7 2
}
test_does_not_match_within_delta(){
  assert_within_delta 5 2 2
}
        Running test_does_not_match_within_delta ... FAILURE
 expected value [5] to match [2] with a maximum delta of [2]
doc:9:test_does_not_match_within_delta()
        Running test_matches_within_delta ... SUCCESS

πŸ‘‘ assert_no_diff

assert_no_diff <expected> <actual> [message]

Asserts that the content of the file actual does not have any differences from the one expected. file comparison slay πŸ’–

test_obvious_notmatching_with_assert_no_diff(){
  assert_no_diff <(echo foo) <(echo bar)
}
test_obvious_matching_with_assert_assert_no_diff(){
  assert_no_diff bash_unit bash_unit
}
        Running test_obvious_matching_with_assert_assert_no_diff ... SUCCESS
        Running test_obvious_notmatching_with_assert_no_diff ... FAILURE
 expected 'doc' to be identical to 'doc' but was different
out> 1c1
out> < foo
out> ---
out> > bar
doc:2:test_obvious_notmatching_with_assert_no_diff()

πŸŒ™ SKIP_IF FUNCTION πŸŒ™

πŸ’€ skip_if

skip_if <condition> <pattern>

If condition is true, this will skip all the tests in the current file which match the given pattern. it's not a failure, it's a "not today, bestie" πŸ’…

This can be useful when one has tests that are dependent on system environment, for instance:

skip_if "uname | grep Darwin" linux
skip_if "uname | grep Linux" darwin

test_linux_proc_exists() {
  assert "ls /proc/" "there should exist /proc on Linux"
}
test_darwin_proc_does_not_exist() {
  assert_fail "ls /proc/" "there should not exist /proc on Darwin"
}

will output, on a Linux system:

        Running test_darwin_proc_does_not_exist ... SKIPPED
        Running test_linux_proc_exists ... SUCCESS

🎭 FAKE FUNCTION 🎭

fake <command> [replacement code]

okay so THIS is the good stuff. πŸ’… fake takes a command and swaps it out for replacement code β€” if you gave it any β€” for the rest of your test's whole entire life. If you don't hand it any replacement code? Then it just replaces command with something that echoes the stdin of fake. Lowkey iconic for when you need to simulate a whole environment for the code you're testing. 🧚

Like, for instance:

fake ps echo hello world
ps

and it will print:

hello world

Same vibe, but feeding it through stdin of fake instead:

fake ps << EOF
hello world
EOF
ps

hello world

πŸ“₯ Using stdin

Here's a lil example where we parameterize fake with its own stdin, so we can test that code fails when a process isn't running and succeeds when it is:

code() {
  ps a | grep apache
}

test_code_succeeds_if_apache_runs() {
  fake ps <<EOF
  PID TTY          TIME CMD
13525 pts/7    00:00:01 bash
24162 pts/7    00:00:00 ps
 8387 ?            0:00 /usr/sbin/apache2 -k start
EOF

  assert code "code should succeed when apache is running"
}

test_code_fails_if_apache_does_not_run() {
  fake ps <<EOF
  PID TTY          TIME CMD
13525 pts/7    00:00:01 bash
24162 pts/7    00:00:00 ps
EOF

  assert_fails code "code should fail when apache is not running"
}

and the output is giving:

Running test_code_fails_if_apache_does_not_run ... SUCCESS
Running test_code_succeeds_if_apache_runs ... SUCCESS

🧩 Using a function

In that last example we faked ps by passing the code inline:

fake ps echo hello world
ps

hello world

But bestie, if you need more complex code to fake your command, you can absolutely abstract it into a function:

_ps() {
  echo hello world
}
fake ps _ps
ps

hello world

⚠️ BUT be careful β€” your _ps function is not exported to sub-processes. Which means, depending on how your code under test actually works, _ps might not even be defined in the context where ps gets called. Like:

_ps() {
  echo hello world
}
fake ps _ps

bash -c ps

environment: line 1: _ps: command not found

It fully depends on your code under test, but it's safer to just export the functions your fake needs, so they're available in sub-processes:

_ps() {
  echo hello world
}
export -f _ps
fake ps _ps

bash -c ps

hello world

Also, fake is limited by the fact that it defines a bash function to override the actual command. In some contexts a command simply can't be overridden by a function. Like, if your code under test relies on exec to launch ps, then fake will have no effect. Periodt. πŸ’€

And fake may also cause strange behaviors from bash_unit when you try to fake really basic stuff. bash_unit tries to be as immune to this as possible, but there are limits. Especially β€” and as surprising as it might seem β€” bash allows creating functions named after builtin commands, and bash_unit won't resist that kind of situation. So for instance, do not try to fake: exit; local; trap; eval; export; if; then; else; fi; while; do; done; $; echo; [ (I know, this is not a builtin but don't).


πŸŽ€ fake parameters

fake stores the parameters you gave to the fake in the global variable FAKE_PARAMS so you can use them inside your fake. πŸ’–

It's useful if you need to adapt the behavior based on the given parameters.

It can also help in asserting the values of these parameters ... but ngl this may be quite tricky.

For instance, in our previous code that checks apache is running, we have an issue: our code does not use ps with the appropriate parameters. So we'll try to check that the parameters given to ps are ax.

The first naive approach would be:

code() {
  ps a | grep apache
}

test_code_gives_ps_appropriate_parameters() {
  _ps() {
    cat <<EOF
  PID TTY          TIME CMD
13525 pts/7    00:00:01 bash
24162 pts/7    00:00:00 ps
 8387 ?            0:00 /usr/sbin/apache2 -k start
EOF
    assert_equals ax "${FAKE_PARAMS[@]}"
  }
  export -f _ps
  fake ps _ps

  code >/dev/null
}

This test calls code, which calls ps, which is actually implemented by _ps. Since code does not use ax but only a as parameters, this test should fail. But ...

Running test_code_gives_ps_appropriate_parameters ... SUCCESS

The problem here is that ps fails (because of the failed assert_equals assertion). But ps is piped with grep:

code() {
  ps a | grep apache
}

With bash, the result code of a pipeline equals the result code of the last command of the pipeline. The last command is grep, and since grep succeeds, the failure of _ps is lost and our test succeeds. We have only succeeded in messing with the test output, nothing more. 😭

An alternative may be to activate bash pipefail option, but this may introduce unwanted side effects. We can also simply not output anything in _ps so that grep fails:

code() {
  ps a | grep apache
}

test_code_gives_ps_appropriate_parameters() {
  _ps() {
    assert_equals ax "${FAKE_PARAMS[@]}"
  }
  export -f _ps
  fake ps _ps

  code >/dev/null
}

The problem here is that we use a trick to make the code under test fail, but the failure has nothing to do with the actual assert_equals failure. This is really bad, don't do that. 🚫

Moreover, assert_equals output is captured by ps and this just messes with the display of our test results:

Running test_code_gives_ps_appropriate_parameters ...

The only correct alternative is for the fake ps to write FAKE_PARAMS in a file descriptor, so that your test can grab them after code execution and assert their value. For instance by writing to a file:

code() {
  ps a | grep apache
}

test_code_gives_ps_appropriate_parameters() {
  _ps() {
    echo ${FAKE_PARAMS[@]} > /tmp/fake_params
  }
  export -f _ps
  fake ps _ps

  code || true

  assert_equals ax "$(head -n1 /tmp/fake_params)"
}

setup() {
  rm -f /tmp/fake_params
}

Here our fake writes to /tmp/fake. We delete this file in setup to be sure that we do not get inappropriate data from a previous test. We assert that the first line of /tmp/fake equals ax. Also, note that we know that code will fail, and write this to ignore the error: code || true.

Running test_code_gives_ps_appropriate_parameters ... FAILURE
 expected [ax] but was [a]
doc:14:test_code_gives_ps_appropriate_parameters()

We can also compact the fake definition:

code() {
  ps a | grep apache
}

test_code_gives_ps_appropriate_parameters() {
  fake ps 'echo ${FAKE_PARAMS[@]} >/tmp/fake_params'

  code || true

  assert_equals ax "$(head -n1 /tmp/fake_params)"
}

setup() {
  rm -f /tmp/fake_params
}
Running test_code_gives_ps_appropriate_parameters ... FAILURE
 expected [ax] but was [a]
doc:10:test_code_gives_ps_appropriate_parameters()

Finally, we can avoid the /tmp/fake_params temporary file by using coproc:

code() {
  ps a | grep apache
}

test_get_data_from_fake() {
  #Fasten you seat belt ...
  coproc cat
  exec {test_channel}>&${COPROC[1]}
  fake ps 'echo ${FAKE_PARAMS[@]} >&$test_channel'

  code || true

  assert_equals ax "$(head -n1 <&${COPROC[0]})"
}
Running test_get_data_from_fake ... FAILURE
 expected [ax] but was [a]
doc:13:test_get_data_from_fake()

✨ and that's the whole entire page bestie ✨

This one comes from the bash_unit source, dated 2025-09-01, and it's filed under BASH_UNIT(1). Go fake some commands, stay safe, and remember: if it's not in FAKE_PARAMS, it didn't happen. πŸ’–πŸ‘‘πŸ¦‹

πŸ“¦ where this page comes from