github.com/bdwilliams/libcompose@v0.3.1-0.20160826154243-d81a9bdacff0/utils/util_inparallel_test.go (about)

     1  // +build !race
     2  
     3  package utils
     4  
     5  import (
     6  	"fmt"
     7  	"sync"
     8  	"testing"
     9  )
    10  
    11  type safeMap struct {
    12  	mu sync.RWMutex
    13  	m  map[int]bool
    14  }
    15  
    16  func (s *safeMap) Add(index int, ok bool) {
    17  	s.mu.Lock()
    18  	defer s.mu.Unlock()
    19  	s.m[index] = ok
    20  }
    21  
    22  func (s *safeMap) Read() map[int]bool {
    23  	s.mu.RLock()
    24  	defer s.mu.RUnlock()
    25  	return s.m
    26  }
    27  
    28  func TestInParallel(t *testing.T) {
    29  	size := 5
    30  	booleanMap := safeMap{
    31  		m: make(map[int]bool, size+1),
    32  	}
    33  	tasks := InParallel{}
    34  	for i := 0; i < size; i++ {
    35  		task := func(index int) func() error {
    36  			return func() error {
    37  				booleanMap.Add(index, true)
    38  				return nil
    39  			}
    40  		}(i)
    41  		tasks.Add(task)
    42  	}
    43  	err := tasks.Wait()
    44  	if err != nil {
    45  		t.Fatal(err)
    46  	}
    47  	// Make sure every value is true
    48  	for _, value := range booleanMap.Read() {
    49  		if !value {
    50  			t.Fatalf("booleanMap expected to contain only true values, got at least one false")
    51  		}
    52  	}
    53  }
    54  
    55  func TestInParallelError(t *testing.T) {
    56  	size := 5
    57  	booleanMap := safeMap{
    58  		m: make(map[int]bool, size+1),
    59  	}
    60  	tasks := InParallel{}
    61  	for i := 0; i < size; i++ {
    62  		task := func(index int) func() error {
    63  			return func() error {
    64  				booleanMap.Add(index, false)
    65  				t.Log("index", index)
    66  				if index%2 == 0 {
    67  					t.Log("return an error for", index)
    68  					return fmt.Errorf("Error with %v", index)
    69  				}
    70  				booleanMap.Add(index, true)
    71  				return nil
    72  			}
    73  		}(i)
    74  		tasks.Add(task)
    75  	}
    76  	err := tasks.Wait()
    77  	if err == nil {
    78  		t.Fatalf("Expected an error on Wait, got nothing.")
    79  	}
    80  	for key, value := range booleanMap.Read() {
    81  		if key%2 != 0 && !value {
    82  			t.Fatalf("booleanMap expected to contain true values on odd number, got %v", booleanMap)
    83  		}
    84  	}
    85  }