Skip to content

Commit

Permalink
testutil: support empty string cmd args
Browse files Browse the repository at this point in the history
FakeCommand allows unit tests to check which command-line arguments
were passed, by recording a log of calls with their arguments.

The following examples do not work:

1. shutdown -r "+0" ""

2. echo ""

The last argument supplies the wall message, and an empty argument
is valid. Having this support in place allows code to simply pass
an empty argument for exec.Command(...).

The issue is that both the argument and command delimiter uses null
characters, which makes the command split operation split on the
first occurrence of two null chars, which breaks the examples above.

To add support for this:

- Change the command delimiter from \000\000 => \000\f\n\r

- Update the Calls() function to split the lines correctly.
  • Loading branch information
flotter committed Jun 21, 2023
1 parent 8902cbe commit 43a5daf
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions internals/testutil/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,18 @@ type FakeCmd struct {
// faking commands that need "\n" in their args (like zenity)
// we use the following convention:
// - generate \0 to separate args
// - generate \0\0 to separate commands
// - generate \0\f\n\r magic sequence to separate commands
var scriptTpl = `#!/bin/bash
printf "%%s" "$(basename "$0")" >> %[1]q
printf '\0' >> %[1]q
for arg in "$@"; do
printf "%%s" "$arg" >> %[1]q
printf '\0' >> %[1]q
done
printf '\0' >> %[1]q
printf '\f\n\r' >> %[1]q
%s
`

Expand Down Expand Up @@ -176,12 +177,11 @@ func (cmd *FakeCmd) Calls() [][]string {
if err != nil {
panic(err)
}
logContent := strings.TrimSuffix(string(raw), "\000")
logContent := strings.TrimSuffix(string(raw), "\000\f\n\r")

allCalls := [][]string{}
calls := strings.Split(logContent, "\000\000")
calls := strings.Split(logContent, "\000\f\n\r")
for _, call := range calls {
call = strings.TrimSuffix(call, "\000")
allCalls = append(allCalls, strings.Split(call, "\000"))
}
return allCalls
Expand Down

0 comments on commit 43a5daf

Please sign in to comment.