Created
October 16, 2014 19:21
-
-
Save cmdrkeene/11427aa40f94908fc64d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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