Skip to content

Commit

Permalink
tests/functional: Make our grep* helpers reject newlines in the query
Browse files Browse the repository at this point in the history
Newlines behave like *OR*; not "and then".
  • Loading branch information
roberth committed Jul 15, 2024
1 parent f2df3f0 commit 644b97c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
19 changes: 16 additions & 3 deletions tests/functional/common/vars-and-functions.sh
Original file line number Diff line number Diff line change
Expand Up @@ -336,13 +336,24 @@ callerPrefix() {
done
}

checkGrepArgs() {
local arg
for arg in "$@"; do
if [[ "$arg" != "${arg//$'\n'/_}" ]]; then
echo "$(callerPrefix)newline not allowed in arguments; grep would try each line individually as if connected by an OR operator" >&2
return -101
fi
done
}

# `grep -v` doesn't work well for exit codes. We want `!(exist line l. l
# matches)`. It gives us `exist line l. !(l matches)`.
#
# `!` normally doesn't work well with `set -e`, but when we wrap in a
# function it *does*.
grepInverse() {
! grep "$@"
checkGrepArgs "$@" && \
! grep "$@"
}

# A shorthand, `> /dev/null` is a bit noisy.
Expand All @@ -357,12 +368,14 @@ grepInverse() {
# the producer into the pipe. But rest assured we've seen it happen in
# CI reliably.
grepQuiet() {
grep "$@" > /dev/null
checkGrepArgs "$@" && \
grep "$@" > /dev/null
}

# The previous two, combined
grepQuietInverse() {
! grep "$@" > /dev/null
checkGrepArgs "$@" && \
! grep "$@" > /dev/null
}

# Return the number of arguments
Expand Down
5 changes: 5 additions & 0 deletions tests/functional/test-infra.sh
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,8 @@ unset res
res=$(set -eu -o pipefail; echo foo | expect 1 grepQuietInverse foo | wc -c)
(( res == 0 ))
unset res

# `grepQuiet` does not allow newlines in its arguments, because grep quietly
# treats them as multiple queries.
( echo foo; echo bar; ) | expectStderr -101 grepQuiet $'foo\nbar' \
| grepQuiet -E 'test-infra\.sh:[0-9]+: in call to grepQuiet: newline not allowed in arguments; grep would try each line individually as if connected by an OR operator'

0 comments on commit 644b97c

Please sign in to comment.