Skip to content

Commit

Permalink
add test for context.Done
Browse files Browse the repository at this point in the history
  • Loading branch information
catatsuy committed Feb 20, 2021
1 parent 38ded5d commit 4e64a34
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions throttle/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,95 @@ func TestRun_pipeClose(t *testing.T) {
t.Errorf("It will be written %q; but %q", expected, b)
}
}

func TestRun_contextDone(t *testing.T) {
pr, pw := io.Pipe()

output := new(bytes.Buffer)

ex := NewExec(pr)

ctx, cancel := context.WithCancel(context.Background())
testC := make(chan time.Time)
count := 0
fc := make(chan struct{})

flushCallback := func(s string) error {
defer func() {
fc <- struct{}{}
// to random fail from Go 1.12 or later
time.Sleep(2 * time.Millisecond)
}()

count++

output.WriteString(s)

return nil
}

doneCount := 0

doneCallback := func(s string) error {
defer func() {
go func() {
fc <- struct{}{}
}()
}()

doneCount++

output.WriteString(s)

return nil
}

exitC := make(chan struct{})
go func() {
ex.Start(ctx, testC, flushCallback, doneCallback)
close(exitC)
}()

testC <- time.Time{}
<-fc

if count != 1 {
t.Error("the flushCallback function has not been called")
}

expected := []byte("abcd\nefgh\n")
pw.Write(expected)

if b := output.Bytes(); b != nil {
t.Errorf("will not be written if it is not flushed %s", b)
}

testC <- time.Time{}
<-fc

if count != 2 {
t.Errorf("the flushCallback function has not been called")
}

if b := output.Bytes(); !bytes.Equal(b, expected) {
t.Errorf("It will be written %q; but %q", expected, b)
}

output.Reset()

expected = []byte("ijk\nlmn\n")
pw.Write(expected)

cancel()
<-exitC

<-fc

if doneCount != 1 {
t.Errorf("the doneCallback function has not been called")
}

if b := output.Bytes(); !bytes.Equal(b, expected) {
t.Errorf("It will be written %q; but %q", expected, b)
}
}

0 comments on commit 4e64a34

Please sign in to comment.