***countdown: add configurableSleeper abstraction
This commit is contained in:
parent
72e6ac9b77
commit
05226985c7
@ -15,10 +15,23 @@ type Sleeper interface {
|
||||
Sleep()
|
||||
}
|
||||
|
||||
type DefaultSleeper struct{}
|
||||
type ConfigurableSleeper struct {
|
||||
duration time.Duration
|
||||
sleep func(time.Duration)
|
||||
}
|
||||
|
||||
func (d *DefaultSleeper) Sleep() {
|
||||
time.Sleep(1 * time.Second)
|
||||
func NewConfigurableSleeper(
|
||||
duration time.Duration,
|
||||
sleep func(time.Duration),
|
||||
) *ConfigurableSleeper {
|
||||
return &ConfigurableSleeper{
|
||||
duration: duration,
|
||||
sleep: sleep,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ConfigurableSleeper) Sleep() {
|
||||
s.sleep(s.duration)
|
||||
}
|
||||
|
||||
func Countdown(out io.Writer, sleeper Sleeper) {
|
||||
|
@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -24,6 +25,14 @@ func (s *SpyCountdownOperations) Write(p []byte) (n int, err error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
type SpyTime struct {
|
||||
durationSlept time.Duration
|
||||
}
|
||||
|
||||
func (s *SpyTime) Sleep(duration time.Duration) {
|
||||
s.durationSlept = duration
|
||||
}
|
||||
|
||||
func TestCountdown(t *testing.T) {
|
||||
t.Run("print 3 to Go!", func(t *testing.T) {
|
||||
buffer := &bytes.Buffer{}
|
||||
@ -54,3 +63,15 @@ Go!`
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfigurableSleeper(t *testing.T) {
|
||||
sleepTime := 5 * time.Second
|
||||
|
||||
spyTime := &SpyTime{}
|
||||
sleeper := NewConfigurableSleeper(sleepTime, spyTime.Sleep)
|
||||
sleeper.Sleep()
|
||||
|
||||
if spyTime.durationSlept != sleepTime {
|
||||
t.Errorf("should have slept for %v but slept for %v", sleepTime, spyTime.durationSlept)
|
||||
}
|
||||
}
|
||||
|
4
main.go
4
main.go
@ -3,10 +3,12 @@ package main
|
||||
import (
|
||||
"gobytest/countdown"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// greet.Greet(os.Stdout, "Elodie")
|
||||
sleeper := countdown.NewConfigurableSleeper(1*time.Second, time.Sleep)
|
||||
|
||||
countdown.Countdown(os.Stdout, &countdown.DefaultSleeper{})
|
||||
countdown.Countdown(os.Stdout, sleeper)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user