From 05226985c748c5acf565179fb2dc65fba12f0932 Mon Sep 17 00:00:00 2001 From: vinchent Date: Tue, 17 Sep 2024 21:43:48 +0200 Subject: [PATCH] ***countdown: add configurableSleeper abstraction --- countdown/countdown.go | 19 ++++++++++++++++--- countdown/countdown_test.go | 21 +++++++++++++++++++++ main.go | 4 +++- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/countdown/countdown.go b/countdown/countdown.go index 89bc546..2f39383 100644 --- a/countdown/countdown.go +++ b/countdown/countdown.go @@ -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) { diff --git a/countdown/countdown_test.go b/countdown/countdown_test.go index 1663184..3214fd5 100644 --- a/countdown/countdown_test.go +++ b/countdown/countdown_test.go @@ -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) + } +} diff --git a/main.go b/main.go index 2841216..5aaaa7e 100644 --- a/main.go +++ b/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) }