github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/azure/common/interruptible_task_test.go (about)

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