diff --git a/check-uptime/lib/check-uptime.go b/check-uptime/lib/check-uptime.go index d660c49e..07de8a00 100644 --- a/check-uptime/lib/check-uptime.go +++ b/check-uptime/lib/check-uptime.go @@ -10,7 +10,7 @@ import ( "github.com/mackerelio/go-osstat/uptime" ) -var opts struct { +type uptimeOpts struct { WarnUnder *float64 `long:"warn-under" value-name:"N" description:"(DEPRECATED) Trigger a warning if under the seconds"` WarningUnder *float64 `short:"w" long:"warning-under" value-name:"N" description:"Trigger a warning if under the seconds"` CritUnder *float64 `short:"c" long:"critical-under" value-name:"N" description:"Trigger a critial if under the seconds"` @@ -21,16 +21,22 @@ var opts struct { // Do the plugin func Do() { - ckr := run(os.Args[1:]) + opts, err := parseArgs(os.Args[1:]) + if err != nil { + os.Exit(1) + } + ckr := opts.run() ckr.Name = "Uptime" ckr.Exit() } -func run(args []string) *checkers.Checker { - _, err := flags.ParseArgs(&opts, args) - if err != nil { - os.Exit(1) - } +func parseArgs(args []string) (*uptimeOpts, error) { + opts := &uptimeOpts{} + _, err := flags.ParseArgs(opts, args) + return opts, err +} + +func (opts *uptimeOpts) run() *checkers.Checker { utDur, err := uptime.Get() if err != nil { return checkers.Unknown(fmt.Sprintf("Failed to fetch uptime metrics: %s", err)) diff --git a/check-uptime/lib/check-uptime_test.go b/check-uptime/lib/check-uptime_test.go new file mode 100644 index 00000000..1312d443 --- /dev/null +++ b/check-uptime/lib/check-uptime_test.go @@ -0,0 +1,56 @@ +package checkuptime + +import ( + "testing" + + "github.com/mackerelio/checkers" + "github.com/stretchr/testify/assert" +) + +func TestCheckUptime(t *testing.T) { + tests := []struct { + args []string + want checkers.Status + }{ + { + []string{}, + checkers.OK, + }, + { + []string{"-w", "-1"}, + checkers.OK, + }, + { + []string{"-W", "-1"}, + checkers.WARNING, + }, + { + []string{"-c", "-1"}, + checkers.OK, + }, + { + []string{"-C", "-1"}, + checkers.CRITICAL, + }, + { + []string{"-W", "-1", "-C", "-1"}, + checkers.CRITICAL, + }, + { + []string{"--warn-under", "-1"}, + checkers.OK, + }, + { + []string{"--warn-over", "-1"}, + checkers.WARNING, + }, + } + for _, tt := range tests { + opts, err := parseArgs(tt.args) + if err != nil { + t.Fatal(err) + } + ckr := opts.run() + assert.Equal(t, tt.want, ckr.Status) + } +}