From 0582768f7560bd305e506280b30f48d97f4f93a5 Mon Sep 17 00:00:00 2001 From: Martin Schulze <37703201+martin-schulze-vireso@users.noreply.github.com> Date: Sat, 6 Nov 2021 08:19:58 +0100 Subject: [PATCH] Add --- SC2315.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 SC2315.md diff --git a/SC2315.md b/SC2315.md new file mode 100644 index 0000000..a4cd0bf --- /dev/null +++ b/SC2315.md @@ -0,0 +1,45 @@ +## In bats, ! does not cause a test failure. Fold the `!` into the conditional! + +### Problematic code: + +```sh +#!/usr/bin/env bats + +@test "test" { + # ... code + ! [ $status == 0 ] + # ... more code +} +``` + +### Correct code: + +```sh +#!/usr/bin/env bats + +@test "test" { + # ... code + [ $status != 0 ] + # ... more code +} +``` + +### Rationale: + +Bats uses `set -e` and `trap ERR` to catch test failures as early as possible. +Although the return code of a `!` negated command is inverted, they will never trigger `errexit`, due to a bash design decision (see [Related Resources](#related-resources)). +This means that tests which use `!` can never fail. + +### Exceptions: + +The return code of the last command in the test will be the exit code of the test function. +This means that you can use `! ` on the last line of the test and it will still fail appropriately. +However, you are encouraged to still transform the code in this case for consistency. + +### Related resources: + +* [SC2314: In bats, ! does not cause a test failure (for non `[ ]` commands)](SC2314) +* [SC2251: This ! is not on a condition and skips errexit](SC2251.md) +* [Stackoverflow: Why do I need parenthesis In bash `set -e` and negated return code](https://stackoverflow.com/a/39582012/760746) +* [bash manpage](https://linux.die.net/man/1/bash) (look at `trap [-lp] [[arg] sigspec ...]`): + > The ERR trap is not executed [...] if the command's return value is being inverted via ! \ No newline at end of file