diff --git a/nagios.go b/nagios.go index cf56e17..7daba21 100644 --- a/nagios.go +++ b/nagios.go @@ -396,11 +396,14 @@ func (p *Plugin) AddUniqueError(errs ...error) { } // SetOutputTarget assigns a target for Nagios plugin output. By default -// output is emitted to os.Stdout. +// output is emitted to os.Stdout. If given an invalid output target the +// default output target will be used instead. func (p *Plugin) SetOutputTarget(w io.Writer) { // Guard against potential nil argument. if w == nil { p.outputSink = os.Stdout + + return } p.outputSink = w diff --git a/unexported_test.go b/unexported_test.go index 262870f..cc9227b 100644 --- a/unexported_test.go +++ b/unexported_test.go @@ -10,12 +10,66 @@ package nagios import ( "fmt" + "os" "strings" "testing" "github.com/google/go-cmp/cmp" ) +func TestPluginSetOutputTargetIsValidWithValidInput(t *testing.T) { + t.Parallel() + + plugin := NewPlugin() + + // Assert that plugin.outputSink is still unset + if plugin.outputSink != nil { + t.Fatal("ERROR: plugin outputSink is not at the expected default unset value.") + } else { + t.Log("OK: plugin outputSink is at the expected default unset value.") + } + + var outputBuffer strings.Builder + + plugin.SetOutputTarget(&outputBuffer) + + // Assert that plugin.outputSink is set as expected. + switch { + case plugin.outputSink == nil: + t.Fatal("ERROR: plugin outputSink is unset instead of the given custom value.") + case plugin.outputSink == os.Stdout: + t.Fatal("ERROR: plugin outputSink is set to the default/fallback value instead of the expected custom value.") + default: + t.Log("OK: plugin outputSink is at the expected custom value.") + } +} + +// TestPluginSetOutputTargetIsValidWithInvalidInput asserts that when given an +// invalid output target that the method falls back to a safe default value. +func TestPluginSetOutputTargetIsValidWithInvalidInput(t *testing.T) { + t.Parallel() + + plugin := NewPlugin() + + // Assert that plugin.outputSink is still unset + if plugin.outputSink != nil { + t.Fatal("ERROR: plugin outputSink is not at the expected default unset value.") + } else { + t.Log("OK: plugin outputSink is at the expected default unset value.") + } + + t.Log("Attempting to set invalid output target. This should cause the default output sink to be set instead.") + plugin.SetOutputTarget(nil) + + // Assert that plugin.outputSink is set to a non-nil default/fallback + // value as expected. + if plugin.outputSink == nil { + t.Fatal("ERROR: plugin outputSink is not at the expected default/fallback value.") + } else { + t.Log("OK: plugin outputSink is at the expected default/fallback value.") + } +} + // TestServiceOutputIsNotInterpolated is intended to prevent further // regressions of formatting being applied to literal/preformatted Service // Output (aka, "one-line summary" output).