summaryrefslogtreecommitdiff
path: root/vendor/github.com/mitchellh/packer/builder/azure/common/interruptible_task_test.go
blob: d2090d87be42ae7bc830b2b94e4e69faa93fc168 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package common

import (
	"fmt"
	"testing"
	"time"
)

func TestInterruptibleTaskShouldImmediatelyEndOnCancel(t *testing.T) {
	testSubject := NewInterruptibleTask(
		func() bool { return true },
		func(<-chan struct{}) error {
			for {
				time.Sleep(time.Second * 30)
			}
		})

	result := testSubject.Run()
	if result.IsCancelled != true {
		t.Fatal("Expected the task to be cancelled, but it was not.")
	}
}

func TestInterruptibleTaskShouldRunTaskUntilCompletion(t *testing.T) {
	var count int

	testSubject := &InterruptibleTask{
		IsCancelled: func() bool {
			return false
		},
		Task: func(<-chan struct{}) error {
			for i := 0; i < 10; i++ {
				count += 1
			}

			return nil
		},
	}

	result := testSubject.Run()
	if result.IsCancelled != false {
		t.Errorf("Expected the task to *not* be cancelled, but it was.")
	}

	if count != 10 {
		t.Errorf("Expected the task to wait for completion, but it did not.")
	}

	if result.Err != nil {
		t.Errorf("Expected the task to return a nil error, but got=%s", result.Err)
	}
}

func TestInterruptibleTaskShouldImmediatelyStopOnTaskError(t *testing.T) {
	testSubject := &InterruptibleTask{
		IsCancelled: func() bool {
			return false
		},
		Task: func(cancelCh <-chan struct{}) error {
			return fmt.Errorf("boom")
		},
	}

	result := testSubject.Run()
	if result.IsCancelled != false {
		t.Errorf("Expected the task to *not* be cancelled, but it was.")
	}

	if result.Err == nil {
		t.Errorf("Expected the task to return an error, but it did not.")
	}
}

func TestInterruptibleTaskShouldProvideLiveChannel(t *testing.T) {
	testSubject := &InterruptibleTask{
		IsCancelled: func() bool {
			return false
		},
		Task: func(cancelCh <-chan struct{}) error {
			isOpen := false

			select {
			case _, ok := <-cancelCh:
				isOpen = !ok
				if !isOpen {
					t.Errorf("Expected the channel to open, but it was closed.")
				}
			default:
				isOpen = true
				break
			}

			if !isOpen {
				t.Errorf("Check for openness failed.")
			}

			return nil
		},
	}

	testSubject.Run()
}