***countdown: add configurableSleeper abstraction

This commit is contained in:
vinchent 2024-09-17 21:43:48 +02:00
parent 72e6ac9b77
commit 05226985c7
3 changed files with 40 additions and 4 deletions

View File

@ -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) {

View File

@ -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)
}
}

View File

@ -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)
}