|
| 1 | +# `assert_regex` |
| 2 | +# |
| 3 | +# This function is similar to `assert_equal` but uses pattern matching instead |
| 4 | +# of equality, by wrapping `[[ value =~ pattern ]]`. |
| 5 | +# |
| 6 | +# Fail if the value (first parameter) does not match the pattern (second |
| 7 | +# parameter). |
| 8 | +# |
| 9 | +# ```bash |
| 10 | +# @test 'assert_regex()' { |
| 11 | +# assert_regex 'what' 'x$' |
| 12 | +# } |
| 13 | +# ``` |
| 14 | +# |
| 15 | +# On failure, the value and the pattern are displayed. |
| 16 | +# |
| 17 | +# ``` |
| 18 | +# -- values does not match regular expression -- |
| 19 | +# value : what |
| 20 | +# pattern : x$ |
| 21 | +# -- |
| 22 | +# ``` |
| 23 | +# |
| 24 | +# If the value is longer than one line then it is displayed in *multi-line* |
| 25 | +# format. |
| 26 | +# |
| 27 | +# An error is displayed if the specified extended regular expression is invalid. |
| 28 | +# |
| 29 | +# For description of the matching behavior, refer to the documentation of the |
| 30 | +# `=~` operator in the |
| 31 | +# [Bash manual]: https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html. |
| 32 | +# Note that the `BASH_REMATCH` array is available immediately after the |
| 33 | +# assertion succeeds but is fragile, i.e. prone to being overwritten as a side |
| 34 | +# effect of other actions. |
| 35 | +assert_regex() { |
| 36 | + local -r value="${1}" |
| 37 | + local -r pattern="${2}" |
| 38 | + |
| 39 | + if [[ '' =~ ${pattern} ]] || (( ${?} == 2 )); then |
| 40 | + echo "Invalid extended regular expression: \`${pattern}'" \ |
| 41 | + | batslib_decorate 'ERROR: assert_regex' \ |
| 42 | + | fail |
| 43 | + elif ! [[ "${value}" =~ ${pattern} ]]; then |
| 44 | + if shopt -p nocasematch &>/dev/null; then |
| 45 | + local case_sensitive=insensitive |
| 46 | + else |
| 47 | + local case_sensitive=sensitive |
| 48 | + fi |
| 49 | + batslib_print_kv_single_or_multi 8 \ |
| 50 | + 'value' "${value}" \ |
| 51 | + 'pattern' "${pattern}" \ |
| 52 | + 'case' "${case_sensitive}" \ |
| 53 | + | batslib_decorate 'value does not match regular expression' \ |
| 54 | + | fail |
| 55 | + fi |
| 56 | +} |
0 commit comments