github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/kbfssync/repeated_wait_group_test.go (about)

     1  // Copyright 2016 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package kbfssync
     6  
     7  import (
     8  	"sync"
     9  	"testing"
    10  
    11  	"golang.org/x/net/context"
    12  )
    13  
    14  func testRepeatedWaitGroupSimpleWait(t *testing.T, rwg *RepeatedWaitGroup) {
    15  	// Start 10 tasks, wait for them all to complete
    16  	rwg.Add(10)
    17  	errChan := make(chan error)
    18  	go func() {
    19  		errChan <- rwg.Wait(context.Background())
    20  	}()
    21  	for i := 0; i < 10; i++ {
    22  		rwg.Done()
    23  	}
    24  	err := <-errChan
    25  	if err != nil {
    26  		t.Fatalf("Error on wait: %v", err)
    27  	}
    28  }
    29  
    30  func TestRepeatedWaitGroupSimpleWait(t *testing.T) {
    31  	var rwg RepeatedWaitGroup
    32  	testRepeatedWaitGroupSimpleWait(t, &rwg)
    33  }
    34  
    35  func TestRepeatedWaitGroupCanceledWait(t *testing.T) {
    36  	// Start 10 tasks, wait for them all to complete
    37  	var rwg RepeatedWaitGroup
    38  	rwg.Add(10)
    39  	errChan := make(chan error)
    40  	ctx, cancel := context.WithCancel(context.Background())
    41  	go func() {
    42  		errChan <- rwg.Wait(ctx)
    43  	}()
    44  	// Only finish half the tasks
    45  	for i := 0; i < 5; i++ {
    46  		rwg.Done()
    47  	}
    48  	cancel()
    49  	err := <-errChan
    50  	if err != context.Canceled {
    51  		t.Fatalf("Unexpected error on wait: %v", err)
    52  	}
    53  }
    54  
    55  func TestRepeatedWaitGroupMultiWait(t *testing.T) {
    56  	var rwg RepeatedWaitGroup
    57  	// Three in serial
    58  	for i := 0; i < 3; i++ {
    59  		testRepeatedWaitGroupSimpleWait(t, &rwg)
    60  	}
    61  
    62  	// Three in parallel!
    63  	var wg sync.WaitGroup
    64  	for i := 0; i < 3; i++ {
    65  		wg.Add(1)
    66  		go func() {
    67  			defer wg.Done()
    68  			testRepeatedWaitGroupSimpleWait(t, &rwg)
    69  		}()
    70  	}
    71  	wg.Wait()
    72  }