Permalink
Browse files

add TimeoutAfter test helper

  • Loading branch information...
jpittis committed Apr 4, 2017
1 parent f7154cc commit d9e6d26da82603ed57ae97640f580867d4602303
Showing with 54 additions and 28 deletions.
  1. +5 −9 link_test.go
  2. +20 −0 testhelper/testhelper.go
  3. +20 −0 testhelper/testhelper_test.go
  4. +9 −19 toxics/timeout_test.go
View
@@ -7,6 +7,7 @@ import (
"time"
"github.com/Shopify/toxiproxy/stream"
"github.com/Shopify/toxiproxy/testhelper"
"github.com/Shopify/toxiproxy/toxics"
)
@@ -191,9 +192,7 @@ func TestToxicity(t *testing.T) {
toxic.Toxic.(*toxics.TimeoutToxic).Timeout = 100
collection.chainUpdateToxic(toxic)
// Toxic should timeout after 100ms
done := make(chan struct{})
go func() {
err = testhelper.TimeoutAfter(150*time.Millisecond, func() {
n, err = link.input.Write([]byte{42})
if n != 1 || err != nil {
t.Fatalf("Write failed: %d %v", n, err)
@@ -202,12 +201,9 @@ func TestToxicity(t *testing.T) {
if n != 0 || err != io.EOF {
t.Fatalf("Read did not get EOF: %d %v", n, err)
}
close(done)
}()
select {
case <-done:
case <-time.After(150 * time.Millisecond):
t.Fatalf("Expected timeout after 100ms")
})
if err != nil {
t.Fatal(err)
}
}
View
@@ -0,0 +1,20 @@
package testhelper
import (
"time"
"fmt"
)
func TimeoutAfter(after time.Duration, f func()) error {
success := make(chan struct{})
go func() {
f()
close(success)
}()
select {
case <-success:
return nil
case <-time.After(after):
return fmt.Errorf("timed out after %s", after)
}
}
@@ -0,0 +1,20 @@
package testhelper
import (
"testing"
"time"
)
func TestTimeoutAfter(t *testing.T) {
err := TimeoutAfter(5*time.Millisecond, func() {})
if err != nil {
t.Fatal("Non blocking function should not timeout.")
}
err = TimeoutAfter(5*time.Millisecond, func() {
time.Sleep(time.Second)
})
if err == nil {
t.Fatal("Blocking function should timeout.")
}
}
View
@@ -6,6 +6,7 @@ import (
"testing"
"time"
"github.com/Shopify/toxiproxy/testhelper"
"github.com/Shopify/toxiproxy/toxics"
)
@@ -47,16 +48,11 @@ func TestTimeoutToxicDoesNotCauseHang(t *testing.T) {
time.Sleep(1 * time.Second) // Shitty sync waiting for latency toxi to get data.
done := make(chan struct{})
go func() {
err = testhelper.TimeoutAfter(time.Second, func() {
proxy.Toxics.RemoveToxic("might_block")
close(done)
}()
select {
case <-done:
case <-time.After(1 * time.Second):
t.Fatal("timeout toxic is causing latency toxic to block")
})
if err != nil {
t.Fatal(err)
}
}
@@ -98,20 +94,14 @@ func TestTimeoutToxicClosesConnectionOnRemove(t *testing.T) {
proxy.Toxics.RemoveToxic("to_delete")
closed := make(chan error)
go func() {
err = testhelper.TimeoutAfter(time.Second, func() {
buf = make([]byte, 1)
_, err = conn.Read(buf)
closed <- err
}()
select {
case err := <-closed:
if err != io.EOF {
t.Fatal("expected EOF from closed connetion")
}
case <-time.After(1 * time.Second):
t.Fatal("connection was not closed in time")
})
if err != nil {
t.Fatal(err)
}
}

0 comments on commit d9e6d26

Please sign in to comment.