|
| 1 | +# `refute_regex` |
| 2 | +# |
| 3 | +# This function is similar to `refute_equal` but uses pattern matching instead |
| 4 | +# of equality, by wrapping `! [[ value =~ pattern ]]`. |
| 5 | +# |
| 6 | +# Fail if the value (first parameter) matches the pattern (second parameter). |
| 7 | +# |
| 8 | +# ```bash |
| 9 | +# @test 'refute_regex()' { |
| 10 | +# refute_regex 'WhatsApp' 'Threema' |
| 11 | +# } |
| 12 | +# ``` |
| 13 | +# |
| 14 | +# On failure, the value, the pattern and the match are displayed. |
| 15 | +# |
| 16 | +# ``` |
| 17 | +# @test 'refute_regex()' { |
| 18 | +# refute_regex 'WhatsApp' 'What.' |
| 19 | +# } |
| 20 | +# |
| 21 | +# -- value matches regular expression -- |
| 22 | +# value : WhatsApp |
| 23 | +# pattern : What. |
| 24 | +# match : Whats |
| 25 | +# case : sensitive |
| 26 | +# -- |
| 27 | +# ``` |
| 28 | +# |
| 29 | +# If the value or pattern is longer than one line then it is displayed in |
| 30 | +# *multi-line* format. |
| 31 | +# |
| 32 | +# An error is displayed if the specified extended regular expression is invalid. |
| 33 | +# |
| 34 | +# For description of the matching behavior, refer to the documentation of the |
| 35 | +# `=~` operator in the |
| 36 | +# [Bash manual]: https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html. |
| 37 | +# |
| 38 | +# Note that the `BASH_REMATCH` array is available immediately after the |
| 39 | +# assertion fails but is fragile, i.e. prone to being overwritten as a side |
| 40 | +# effect of other actions like calling `run`. Thus, it's good practice to avoid |
| 41 | +# using `BASH_REMATCH` in conjunction with `refute_regex()`. The valuable |
| 42 | +# information the array contains is the matching part of the value which is |
| 43 | +# printed in the failing test log, as mentioned above. |
| 44 | +refute_regex() { |
| 45 | + local -r value="${1}" |
| 46 | + local -r pattern="${2}" |
| 47 | + |
| 48 | + if [[ '' =~ ${pattern} ]] || (( ${?} == 2 )); then |
| 49 | + echo "Invalid extended regular expression: \`${pattern}'" \ |
| 50 | + | batslib_decorate 'ERROR: refute_regex' \ |
| 51 | + | fail |
| 52 | + elif [[ "${value}" =~ ${pattern} ]]; then |
| 53 | + if shopt -p nocasematch &>/dev/null; then |
| 54 | + local case_sensitive=insensitive |
| 55 | + else |
| 56 | + local case_sensitive=sensitive |
| 57 | + fi |
| 58 | + batslib_print_kv_single_or_multi 8 \ |
| 59 | + 'value' "${value}" \ |
| 60 | + 'pattern' "${pattern}" \ |
| 61 | + 'match' "${BASH_REMATCH[0]}" \ |
| 62 | + 'case' "${case_sensitive}" \ |
| 63 | + | batslib_decorate 'value matches regular expression' \ |
| 64 | + | fail |
| 65 | + fi |
| 66 | +} |
0 commit comments