aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--util/interrupt/cleaner.go19
-rw-r--r--util/interrupt/cleaner_test.go41
2 files changed, 42 insertions, 18 deletions
diff --git a/util/interrupt/cleaner.go b/util/interrupt/cleaner.go
index 3f6c3afb..76c9d04d 100644
--- a/util/interrupt/cleaner.go
+++ b/util/interrupt/cleaner.go
@@ -16,7 +16,7 @@ var active = false
// RegisterCleaner is responsible for regisreting a cleaner function. When a function is registered, the Signal watcher is started in a goroutine.
func RegisterCleaner(f ...Cleaner) {
for _, fn := range f {
- cleaners = append(cleaners, fn)
+ cleaners = append([]Cleaner{fn}, cleaners...)
if !active {
active = true
go func() {
@@ -25,18 +25,25 @@ func RegisterCleaner(f ...Cleaner) {
<-ch
// Prevent un-terminated ^C character in terminal
fmt.Println()
- clean()
+ fmt.Println("Cleaning")
+ errl := Clean()
+ for _, err := range errl {
+ fmt.Println(err)
+ }
os.Exit(1)
}()
}
}
}
-// Clean invokes all registered cleanup functions
-func clean() {
- fmt.Println("Cleaning")
+// Clean invokes all registered cleanup functions, and returns a list of errors, if they exist.
+func Clean() (errorlist []error) {
for _, f := range cleaners {
- _ = f()
+ err := f()
+ if err != nil {
+ errorlist = append(errorlist, err)
+ }
}
cleaners = []Cleaner{}
+ return
}
diff --git a/util/interrupt/cleaner_test.go b/util/interrupt/cleaner_test.go
index f839c0dc..c4e5c9b3 100644
--- a/util/interrupt/cleaner_test.go
+++ b/util/interrupt/cleaner_test.go
@@ -1,33 +1,50 @@
package interrupt
import (
+ "errors"
"testing"
)
-func TestRegister(t *testing.T) {
+// TestRegisterAndErrorAtCleaning tests if the registered order was kept by checking the returned errors
+func TestRegisterAndErrorAtCleaning(t *testing.T) {
active = true // this prevents goroutine from being started during the tests
f := func() error {
- return nil
+ return errors.New("X")
}
f2 := func() error {
- return nil
+ return errors.New("Y")
}
f3 := func() error {
return nil
}
RegisterCleaner(f)
RegisterCleaner(f2, f3)
- count := 0
- for _, fn := range cleaners {
- errt := fn()
- count++
- if errt != nil {
- t.Fatalf("bad err value")
- }
+ // count := 0
+
+ errl := Clean()
+ if len(errl) != 2 {
+ t.Fatalf("unexpected error count")
}
- if count != 3 {
- t.Fatalf("different number of errors")
+ if errl[0].Error() != "Y" && errl[1].Error() != "X" {
+ t.Fatalf("unexpected error order")
+
}
+}
+
+func TestRegisterAndClean(t *testing.T) {
+ active = true // this prevents goroutine from being started during the tests
+ f := func() error {
+ return nil
+ }
+ f2 := func() error {
+ return nil
+ }
+ RegisterCleaner(f, f2)
+
+ errl := Clean()
+ if len(errl) != 0 {
+ t.Fatalf("unexpected error count")
+ }
}