Skip to content

Commit

Permalink
test signal errors (#28)
Browse files Browse the repository at this point in the history
* test signal errors

* fix documentation
  • Loading branch information
achille-roussel authored Sep 11, 2017
1 parent 592b054 commit 406fcab
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
30 changes: 30 additions & 0 deletions signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"runtime"
"sync"
"sync/atomic"
"syscall"
"time"
)

Expand Down Expand Up @@ -135,3 +136,32 @@ func (s *signalCtx) cancel(err error) {
close(s.done)
})
}

// IsSignal returns true if the given error is a *SignalError that was
// generated upon receipt of one of the given signals. If no signal is
// passed, the function only tests for err to be of type *SginalError.
func IsSignal(err error, signals ...os.Signal) bool {
if e, ok := err.(*SignalError); ok {
if len(signals) == 0 {
return true
}
for _, signal := range signals {
if signal == e.Signal {
return true
}
}
}
return false
}

// IsTermination returns true if the given error was caused by receiving a
// termination signal.
func IsTermination(err error) bool {
return IsSignal(err, syscall.SIGTERM)
}

// IsInterruption returns true if the given error was caused by receiving an
// interruption signal.
func IsInterruption(err error) bool {
return IsSignal(err, syscall.SIGINT)
}
19 changes: 19 additions & 0 deletions signal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"os"
"reflect"
"syscall"
"testing"
"time"
)
Expand Down Expand Up @@ -117,3 +118,21 @@ func TestWithSignals(t *testing.T) {
}
})
}

func TestIsTermination(t *testing.T) {
if !IsTermination(&SignalError{Signal: syscall.SIGTERM}) {
t.Error("SIGTERM wasn't recognized as a termination error")
}
if IsTermination(&SignalError{Signal: syscall.SIGINT}) {
t.Error("SIGINT was mistakenly recognized as a termination error")
}
}

func TestIsInterruption(t *testing.T) {
if !IsInterruption(&SignalError{Signal: syscall.SIGINT}) {
t.Error("SIGINT wasn't recognized as a interruption error")
}
if IsInterruption(&SignalError{Signal: syscall.SIGTERM}) {
t.Error("SIGTERM was mistakenly recognized as a interruption error")
}
}

0 comments on commit 406fcab

Please sign in to comment.