github.com/Cloud-Foundations/Dominator@v0.3.4/lib/goroutine/impl_test.go (about)

     1  package goroutine
     2  
     3  import (
     4  	"runtime"
     5  	"syscall"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestQuitAndRun(t *testing.T) {
    11  	g := New()
    12  	g.Quit()
    13  	defer func() { recover() }()
    14  	g.Run(func() {})
    15  	t.Fatal("Run-after-Quit did not panic")
    16  }
    17  
    18  func TestRun(t *testing.T) {
    19  	g := New()
    20  	defer g.Quit()
    21  	var finished, started bool
    22  	g.Run(func() {
    23  		started = true
    24  		time.Sleep(time.Millisecond * 10)
    25  		finished = true
    26  	})
    27  	runtime.Gosched()
    28  	if !started {
    29  		t.Fatal("Function not started")
    30  	}
    31  	if !finished {
    32  		t.Fatal("Function not finished")
    33  	}
    34  }
    35  
    36  func TestStart(t *testing.T) {
    37  	g := New()
    38  	defer g.Quit()
    39  	var firstFinished, firstStarted bool
    40  	g.Start(func() {
    41  		firstStarted = true
    42  		time.Sleep(time.Millisecond * 10)
    43  		firstFinished = true
    44  	})
    45  	runtime.Gosched()
    46  	if !firstStarted {
    47  		t.Fatal("First function not started")
    48  	}
    49  	if firstFinished {
    50  		t.Fatal("First function finished")
    51  	}
    52  	secondStarted := false
    53  	g.Start(func() {
    54  		secondStarted = true
    55  	})
    56  	if !firstFinished {
    57  		t.Fatal("First function not finished")
    58  	}
    59  	runtime.Gosched()
    60  	if !secondStarted {
    61  		t.Fatal("Second function not started")
    62  	}
    63  }
    64  
    65  func TestStartQuit(t *testing.T) {
    66  	g := New()
    67  	g.Start(func() { time.Sleep(time.Second) })
    68  	g.Quit()
    69  }
    70  
    71  func TestWait(t *testing.T) {
    72  	g := New()
    73  	defer g.Quit()
    74  	var finished, started bool
    75  	g.Start(func() {
    76  		started = true
    77  		time.Sleep(time.Millisecond * 10)
    78  		finished = true
    79  	})
    80  	runtime.Gosched()
    81  	if !started {
    82  		t.Fatal("Function not started")
    83  	}
    84  	if finished {
    85  		t.Fatal("Function finished")
    86  	}
    87  	g.Wait()
    88  	if !finished {
    89  		t.Fatal("Function not finished")
    90  	}
    91  }
    92  
    93  func TestWithThreadLocking(t *testing.T) {
    94  	g := New()
    95  	defer g.Quit()
    96  	g.Run(runtime.LockOSThread)
    97  	var gTid int
    98  	g.Run(func() { gTid = syscall.Gettid() })
    99  	callerTid := syscall.Gettid()
   100  	if gTid == callerTid {
   101  		t.Fatal("Caller and goroutine threads are the same")
   102  	}
   103  }