go-by-test/countdown/countdown_test.go

78 lines
1.4 KiB
Go
Raw Normal View History

2024-09-17 19:10:09 +00:00
package countdown
import (
"bytes"
2024-09-17 19:30:53 +00:00
"reflect"
2024-09-17 19:10:09 +00:00
"testing"
"time"
2024-09-17 19:10:09 +00:00
)
2024-09-17 19:30:53 +00:00
const (
write = "write"
sleep = "sleep"
)
type SpyCountdownOperations struct {
Calls []string
2024-09-17 19:20:33 +00:00
}
2024-09-17 19:30:53 +00:00
func (s *SpyCountdownOperations) Sleep() {
s.Calls = append(s.Calls, sleep)
2024-09-17 19:20:33 +00:00
}
2024-09-17 19:30:53 +00:00
func (s *SpyCountdownOperations) Write(p []byte) (n int, err error) {
s.Calls = append(s.Calls, write)
return 0, nil
}
2024-09-17 19:10:09 +00:00
type SpyTime struct {
durationSlept time.Duration
}
func (s *SpyTime) Sleep(duration time.Duration) {
s.durationSlept = duration
}
2024-09-17 19:30:53 +00:00
func TestCountdown(t *testing.T) {
t.Run("print 3 to Go!", func(t *testing.T) {
buffer := &bytes.Buffer{}
Countdown(buffer, &SpyCountdownOperations{})
2024-09-17 19:10:09 +00:00
2024-09-17 19:30:53 +00:00
got := buffer.String()
want := `3
2024-09-17 19:10:09 +00:00
2
1
Go!`
2024-09-17 19:30:53 +00:00
if got != want {
t.Errorf("got %q want %q", got, want)
}
})
t.Run("sleep before every print", func(t *testing.T) {
spySleepPrinter := &SpyCountdownOperations{}
Countdown(spySleepPrinter, spySleepPrinter)
want := []string{
write, sleep, write, sleep, write, sleep, write,
}
2024-09-17 19:20:33 +00:00
2024-09-17 19:30:53 +00:00
if !reflect.DeepEqual(want, spySleepPrinter.Calls) {
t.Errorf("wanted %v got %v", want, spySleepPrinter.Calls)
}
})
2024-09-17 19:10:09 +00:00
}
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)
}
}