Skip to content

Instantly share code, notes, and snippets.

@cmdrkeene
Created October 16, 2014 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmdrkeene/11427aa40f94908fc64d to your computer and use it in GitHub Desktop.
Save cmdrkeene/11427aa40f94908fc64d to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"time"
)
var realError = errors.New("real")
var timeoutError = errors.New("timeout")
type repo struct {
timeout time.Duration
fetcher fetcher
}
func (r repo) DoFetch() error {
result := make(chan error)
go func() {
result <- r.fetcher.Fetch()
}()
select {
case res := <-result:
return res
case <-time.After(r.timeout):
fmt.Println("timed out!")
return timeoutError
}
return r.fetcher.Fetch()
}
type fetcher interface {
Fetch() error
}
type realFetcher struct{}
func (realFetcher) Fetch() error {
fmt.Println("real fetcher")
time.Sleep(1 * time.Millisecond)
return realError
}
type testFetcher struct {
sleepFor time.Duration
}
func (t testFetcher) Fetch() error {
fmt.Println("test fetcher sleeping")
time.Sleep(t.sleepFor)
fmt.Println("test fetcher done")
return nil
}
func main() {
}
func TestTimeout(t *testing.T) {
r := repo{timeout: 1 * time.Millisecond}
r.fetcher = testFetcher{sleepFor: 2 * time.Millisecond}
var err error
go func() {
err = r.DoFetch()
}()
<-time.After(3 * time.Millisecond)
if !reflect.DeepEqual(err, timeoutError) {
t.Error("want", timeoutError)
t.Error("got ", err)
}
}
func TestReal(t *testing.T) {
r := repo{timeout: 2 * time.Millisecond}
r.fetcher = realFetcher{}
var err error
go func() {
err = r.DoFetch()
}()
<-time.After(3 * time.Millisecond)
if !reflect.DeepEqual(err, realError) {
t.Error("want", realError)
t.Error("got ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment