github.com/yoctocloud/packer@v0.6.2-0.20160520224004-e11a0a18423f/builder/azure/common/interruptible_task_test.go (about) 1 // Copyright (c) Microsoft Corporation. All rights reserved. 2 // Licensed under the MIT License. See the LICENSE file in builder/azure for license information. 3 4 package common 5 6 import ( 7 "fmt" 8 "testing" 9 "time" 10 ) 11 12 func TestInterruptibleTaskShouldImmediatelyEndOnCancel(t *testing.T) { 13 testSubject := NewInterruptibleTask( 14 func() bool { return true }, 15 func(<-chan struct{}) error { 16 for { 17 time.Sleep(time.Second * 30) 18 } 19 }) 20 21 result := testSubject.Run() 22 if result.IsCancelled != true { 23 t.Fatalf("Expected the task to be cancelled, but it was not.") 24 } 25 } 26 27 func TestInterruptibleTaskShouldRunTaskUntilCompletion(t *testing.T) { 28 var count int 29 30 testSubject := &InterruptibleTask{ 31 IsCancelled: func() bool { 32 return false 33 }, 34 Task: func(<-chan struct{}) error { 35 for i := 0; i < 10; i++ { 36 count += 1 37 } 38 39 return nil 40 }, 41 } 42 43 result := testSubject.Run() 44 if result.IsCancelled != false { 45 t.Errorf("Expected the task to *not* be cancelled, but it was.") 46 } 47 48 if count != 10 { 49 t.Errorf("Expected the task to wait for completion, but it did not.") 50 } 51 52 if result.Err != nil { 53 t.Errorf("Expected the task to return a nil error, but got=%s", result.Err) 54 } 55 } 56 57 func TestInterruptibleTaskShouldImmediatelyStopOnTaskError(t *testing.T) { 58 testSubject := &InterruptibleTask{ 59 IsCancelled: func() bool { 60 return false 61 }, 62 Task: func(cancelCh <-chan struct{}) error { 63 return fmt.Errorf("boom") 64 }, 65 } 66 67 result := testSubject.Run() 68 if result.IsCancelled != false { 69 t.Errorf("Expected the task to *not* be cancelled, but it was.") 70 } 71 72 if result.Err == nil { 73 t.Errorf("Expected the task to return an error, but it did not.") 74 } 75 } 76 77 func TestInterruptibleTaskShouldProvideLiveChannel(t *testing.T) { 78 testSubject := &InterruptibleTask{ 79 IsCancelled: func() bool { 80 return false 81 }, 82 Task: func(cancelCh <-chan struct{}) error { 83 isOpen := false 84 85 select { 86 case _, ok := <-cancelCh: 87 isOpen = !ok 88 if !isOpen { 89 t.Errorf("Expected the channel to open, but it was closed.") 90 } 91 default: 92 isOpen = true 93 break 94 } 95 96 if !isOpen { 97 t.Errorf("Check for openness failed.") 98 } 99 100 return nil 101 }, 102 } 103 104 testSubject.Run() 105 }