cleaner_test.go

 1package interrupt
 2
 3import (
 4	"errors"
 5	"testing"
 6
 7	"github.com/stretchr/testify/assert"
 8	"github.com/stretchr/testify/require"
 9)
10
11// TestRegisterAndErrorAtCleaning tests if the registered order was kept by checking the returned errors
12func TestRegisterAndErrorAtCleaning(t *testing.T) {
13	handlerCreated = true // this prevents goroutine from being started during the tests
14
15	f1 := func() error {
16		return errors.New("1")
17	}
18	f2 := func() error {
19		return errors.New("2")
20	}
21	f3 := func() error {
22		return nil
23	}
24
25	RegisterCleaner(f1)
26	RegisterCleaner(f2)
27	RegisterCleaner(f3)
28
29	errl := clean()
30
31	require.Len(t, errl, 2)
32
33	// cleaners should execute in the reverse order they have been defined
34	assert.Equal(t, "2", errl[0].Error())
35	assert.Equal(t, "1", errl[1].Error())
36}
37
38func TestRegisterAndClean(t *testing.T) {
39	handlerCreated = true // this prevents goroutine from being started during the tests
40
41	f1 := func() error {
42		return nil
43	}
44	f2 := func() error {
45		return nil
46	}
47
48	RegisterCleaner(f1)
49	RegisterCleaner(f2)
50
51	errl := clean()
52	assert.Len(t, errl, 0)
53}
54
55func TestCancel(t *testing.T) {
56	handlerCreated = true // this prevents goroutine from being started during the tests
57
58	f1 := func() error {
59		return errors.New("1")
60	}
61	f2 := func() error {
62		return errors.New("2")
63	}
64
65	cancel1 := RegisterCleaner(f1)
66	RegisterCleaner(f2)
67
68	cancel1()
69
70	errl := clean()
71	require.Len(t, errl, 1)
72
73	assert.Equal(t, "2", errl[0].Error())
74}