package handler import ( "bytes" "encoding/xml" "testing" "time" "github.com/stretchr/testify/require" ) func TestPeriodicWriter(t *testing.T) { const dur = 100 * time.Millisecond const whitespaces = 8 expected := []byte(xml.Header) for i := 0; i < whitespaces; i++ { expected = append(expected, []byte(" ")...) } t.Run("writes data", func(t *testing.T) { buf := bytes.NewBuffer(nil) stop := periodicXMLWriter(buf, dur) // N number of whitespaces + half durations to guarantee at least N writes in buffer time.Sleep(whitespaces*dur + dur/2) require.True(t, stop()) require.Equal(t, expected, buf.Bytes()) t.Run("no additional data after stop", func(t *testing.T) { time.Sleep(2 * dur) require.Equal(t, expected, buf.Bytes()) }) }) t.Run("does not write data", func(t *testing.T) { buf := bytes.NewBuffer(nil) stop := periodicXMLWriter(buf, dur) time.Sleep(dur / 2) require.False(t, stop()) require.Empty(t, buf.Bytes()) t.Run("disabled", func(t *testing.T) { stop = periodicXMLWriter(buf, 0) require.False(t, stop()) require.Empty(t, buf.Bytes()) }) }) }