2018-10-25 01:06:10 +03:00
|
|
|
package interrupt
|
|
|
|
|
|
|
|
import (
|
2018-10-26 00:07:02 +03:00
|
|
|
"errors"
|
2018-10-25 01:06:10 +03:00
|
|
|
"testing"
|
2019-08-30 13:17:29 +03:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2018-10-25 01:06:10 +03:00
|
|
|
)
|
|
|
|
|
2018-10-26 00:07:02 +03:00
|
|
|
// TestRegisterAndErrorAtCleaning tests if the registered order was kept by checking the returned errors
|
|
|
|
func TestRegisterAndErrorAtCleaning(t *testing.T) {
|
2019-08-30 13:17:29 +03:00
|
|
|
handlerCreated = true // this prevents goroutine from being started during the tests
|
2018-10-25 01:06:10 +03:00
|
|
|
|
2019-08-30 13:17:29 +03:00
|
|
|
f1 := func() error {
|
|
|
|
return errors.New("1")
|
2018-10-25 01:06:10 +03:00
|
|
|
}
|
|
|
|
f2 := func() error {
|
2019-08-30 13:17:29 +03:00
|
|
|
return errors.New("2")
|
2018-10-25 01:06:10 +03:00
|
|
|
}
|
|
|
|
f3 := func() error {
|
|
|
|
return nil
|
|
|
|
}
|
2019-08-30 13:17:29 +03:00
|
|
|
|
|
|
|
RegisterCleaner(f1)
|
|
|
|
RegisterCleaner(f2)
|
|
|
|
RegisterCleaner(f3)
|
2018-10-26 00:07:02 +03:00
|
|
|
|
2018-10-27 12:51:50 +03:00
|
|
|
errl := clean()
|
2018-10-26 00:07:02 +03:00
|
|
|
|
2019-08-30 13:17:29 +03:00
|
|
|
require.Len(t, errl, 2)
|
|
|
|
|
|
|
|
// cleaners should execute in the reverse order they have been defined
|
|
|
|
assert.Equal(t, "2", errl[0].Error())
|
|
|
|
assert.Equal(t, "1", errl[1].Error())
|
2018-10-26 00:07:02 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestRegisterAndClean(t *testing.T) {
|
2019-08-30 13:17:29 +03:00
|
|
|
handlerCreated = true // this prevents goroutine from being started during the tests
|
2018-10-25 01:06:10 +03:00
|
|
|
|
2019-08-30 13:17:29 +03:00
|
|
|
f1 := func() error {
|
2018-10-26 00:07:02 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
f2 := func() error {
|
|
|
|
return nil
|
|
|
|
}
|
2019-08-30 13:17:29 +03:00
|
|
|
|
|
|
|
RegisterCleaner(f1)
|
|
|
|
RegisterCleaner(f2)
|
2018-10-26 00:07:02 +03:00
|
|
|
|
2018-10-27 12:51:50 +03:00
|
|
|
errl := clean()
|
2019-08-30 13:17:29 +03:00
|
|
|
assert.Len(t, errl, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestCancel(t *testing.T) {
|
|
|
|
handlerCreated = true // this prevents goroutine from being started during the tests
|
|
|
|
|
|
|
|
f1 := func() error {
|
|
|
|
return errors.New("1")
|
|
|
|
}
|
|
|
|
f2 := func() error {
|
|
|
|
return errors.New("2")
|
2018-10-26 00:07:02 +03:00
|
|
|
}
|
2019-08-30 13:17:29 +03:00
|
|
|
|
|
|
|
cancel1 := RegisterCleaner(f1)
|
|
|
|
RegisterCleaner(f2)
|
|
|
|
|
|
|
|
cancel1()
|
|
|
|
|
|
|
|
errl := clean()
|
|
|
|
require.Len(t, errl, 1)
|
|
|
|
|
|
|
|
assert.Equal(t, "2", errl[0].Error())
|
2018-10-25 01:06:10 +03:00
|
|
|
}
|