1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#!/usr/bin/env bats
load test_helper
#
# Literal matching
#
# Correctness
@test "assert_regex() <value> <pattern>: succeeds if a <value> substring matches extended regular expression <pattern>" {
run assert_regex 'abc' '^[a-z]b[c-z]+'
assert_test_pass
}
@test "assert_regex() <value> <pattern>: fails if no <value> substring matches extended regular expression <pattern>" {
run assert_regex 'bcd' '^[a-z]b[c-z]+'
assert_test_fail <<'ERR_MSG'
-- value does not match regular expression --
value : bcd
pattern : ^[a-z]b[c-z]+
case : sensitive
--
ERR_MSG
}
@test "assert_regex() <value> <pattern>: provides results in BASH_REMATCH" {
unset -v BASH_REMATCH
assert_regex 'abcd' 'b.d'
declare -p BASH_REMATCH
[ "${BASH_REMATCH[0]}" = 'bcd' ]
}
@test "assert_regex() <value> <pattern>: matches case-insensitively when 'nocasematch' is set" {
shopt -s nocasematch
assert_regex 'aBc' 'ABC'
}
@test "assert_regex() <value> <pattern>: outputs multi-line <value> nicely when it fails" {
run assert_regex $'bcd\n123' '^[a-z]b[c-z]+'
assert_test_fail <<'ERR_MSG'
-- value does not match regular expression --
value (2 lines):
bcd
123
pattern (1 lines):
^[a-z]b[c-z]+
case (1 lines):
sensitive
--
ERR_MSG
shopt -s nocasematch
run assert_regex $'bcd\n123' '^[a-z]b[c-z]+'
assert_test_fail <<'ERR_MSG'
-- value does not match regular expression --
value (2 lines):
bcd
123
pattern (1 lines):
^[a-z]b[c-z]+
case (1 lines):
insensitive
--
ERR_MSG
}
# Error handling
@test "assert_regex() <value> <pattern>: returns 1 and displays an error message if <pattern> is not a valid extended regular expression" {
run assert_regex value '[.*'
if (( BASH_VERSINFO[0] > 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >=3) )); then
[[ "$output" =~ "invalid regular expression "([^$'\n']+) ]]
assert_test_fail <<ERR_MSG
-- ERROR: assert_regex --
invalid regular expression ${BASH_REMATCH[1]}
--
ERR_MSG
else
assert_test_fail <<'ERR_MSG'
-- ERROR: assert_regex --
Invalid extended regular expression: `[.*'
--
ERR_MSG
fi
}
@test "assert_regex allows regex matching empty string (see #53)" {
run assert_regex any_value '.*'
assert_success
}
|