diff --git a/cmd/shelldoc/shelldoc_test.go b/cmd/shelldoc/shelldoc_test.go index 6bc7741..b52ea86 100644 --- a/cmd/shelldoc/shelldoc_test.go +++ b/cmd/shelldoc/shelldoc_test.go @@ -29,3 +29,9 @@ func TestHFailNoMatch(t *testing.T) { require.Equal(t, returnFailure, results.returncode, "The expected return code is returnFailure.") require.Equal(t, 1, results.failureCount, "There is one failing test in the sample.") } + +func TestExitCodesOptions(t *testing.T) { + results, err := performInteractions("../../pkg/tokenizer/samples/options.md") + require.NoError(t, err, "The HelloWorld example should execute without errors.") + require.Equal(t, returnSuccess, results.returncode, "The expected return code is returnFailure.") +} diff --git a/pkg/tokenizer/interaction.go b/pkg/tokenizer/interaction.go index 387c60a..e00764e 100644 --- a/pkg/tokenizer/interaction.go +++ b/pkg/tokenizer/interaction.go @@ -7,6 +7,7 @@ package tokenizer import ( "fmt" "reflect" + "strconv" "strings" "github.com/endocode/shelldoc/pkg/shell" @@ -120,11 +121,25 @@ func (interaction *Interaction) Execute(shell *shell.Shell) error { // execute the command in the shell output, rc, err := shell.ExecuteCommand(interaction.Cmd) // compare the results + const ExitCodeOption = "shelldocexitcode" + const ExitCodeWhatever = "shelldocwhatever" + var expectedExitCode int + if expectedExitCodeOption, ok := interaction.Attributes[ExitCodeOption]; ok { + if value, err := strconv.Atoi(expectedExitCodeOption); err == nil { + expectedExitCode = value + } else { + return fmt.Errorf("argument to %s needs to be an integer, got \"%s\"", ExitCodeOption, expectedExitCodeOption) + } + } + expectedWhatever := false + if _, ok := interaction.Attributes[ExitCodeWhatever]; ok { + expectedWhatever = true + } if err != nil { interaction.ResultCode = ResultExecutionError interaction.Comment = err.Error() return fmt.Errorf("unable to execute command: %v", err) - } else if rc != 0 { + } else if expectedWhatever == false && rc != expectedExitCode { interaction.ResultCode = ResultError interaction.Comment = fmt.Sprintf("command exited with non-zero exit code %d", rc) } else if interaction.evaluateResponse(output) { diff --git a/pkg/tokenizer/samples/options.md b/pkg/tokenizer/samples/options.md new file mode 100644 index 0000000..fb29d88 --- /dev/null +++ b/pkg/tokenizer/samples/options.md @@ -0,0 +1,15 @@ +# Tests for shelldoc options in fenced code blocks + +This one says the exit code of the command does not matter: + +```shell {shelldocwhatever} +> false +``` + +This one specifies that the exit code should be 2: + +```shell {shelldocexitcode=2} +> (exit 2) +``` + +More options may follow.