aboutsummaryrefslogtreecommitdiffstats
path: root/util/interrupt/cleaner_test.go
blob: eb1215d60c73ef59e32349f485df1618ab9b8755 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package interrupt

import (
	"errors"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// TestRegisterAndErrorAtCleaning tests if the registered order was kept by checking the returned errors
func TestRegisterAndErrorAtCleaning(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")
	}
	f3 := func() error {
		return nil
	}

	RegisterCleaner(f1)
	RegisterCleaner(f2)
	RegisterCleaner(f3)

	errl := clean()

	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())
}

func TestRegisterAndClean(t *testing.T) {
	handlerCreated = true // this prevents goroutine from being started during the tests

	f1 := func() error {
		return nil
	}
	f2 := func() error {
		return nil
	}

	RegisterCleaner(f1)
	RegisterCleaner(f2)

	errl := clean()
	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")
	}

	cancel1 := RegisterCleaner(f1)
	RegisterCleaner(f2)

	cancel1()

	errl := clean()
	require.Len(t, errl, 1)

	assert.Equal(t, "2", errl[0].Error())
}