constellation/cli/internal/cmd/spinner_test.go

117 lines
2.4 KiB
Go
Raw Normal View History

/*
Copyright (c) Edgeless Systems GmbH
SPDX-License-Identifier: AGPL-3.0-only
*/
package cmd
import (
"bytes"
"fmt"
"strings"
"testing"
"time"
2022-10-07 13:35:07 -04:00
"github.com/stretchr/testify/assert"
)
const (
baseWait = 100
baseText = "Loading"
)
func TestSpinnerInitialState(t *testing.T) {
2022-10-07 13:35:07 -04:00
assert := assert.New(t)
out := &bytes.Buffer{}
s := newSpinner(out)
s.delay = time.Millisecond * 10
s.spinFunc = spinTTY
2022-10-07 13:35:07 -04:00
s.Start(baseText, true)
time.Sleep(baseWait * time.Millisecond)
s.Stop()
assert.Greater(out.Len(), 0)
outStr := out.String()
assert.True(strings.HasPrefix(outStr, hideCursor+generateAllStatesAsString(t, baseText, true)))
}
func TestSpinnerFinalState(t *testing.T) {
2022-10-07 13:35:07 -04:00
assert := assert.New(t)
out := &bytes.Buffer{}
2022-10-07 13:35:07 -04:00
s := newSpinner(out)
s.delay = time.Millisecond * 10
s.spinFunc = spinTTY
2022-10-07 13:35:07 -04:00
s.Start(baseText, true)
time.Sleep(baseWait * time.Millisecond)
s.Stop()
assert.Greater(out.Len(), 0)
outStr := out.String()
assert.True(strings.HasSuffix(outStr, baseText+"... \n"+showCursor))
}
func TestSpinnerDisabledShowDotsFlag(t *testing.T) {
2022-10-07 13:35:07 -04:00
assert := assert.New(t)
out := &bytes.Buffer{}
2022-10-07 13:35:07 -04:00
s := newSpinner(out)
s.delay = time.Millisecond * 10
s.spinFunc = spinTTY
2022-10-07 13:35:07 -04:00
s.Start(baseText, false)
time.Sleep(baseWait * time.Millisecond)
s.Stop()
2022-10-07 13:35:07 -04:00
assert.True(out.Len() > 0)
outStr := out.String()
assert.True(strings.HasPrefix(outStr, hideCursor+generateAllStatesAsString(t, baseText, false)))
assert.True(strings.HasSuffix(outStr, baseText+" \n"+showCursor))
2022-10-07 13:35:07 -04:00
}
func TestSpinnerInterruptWriter(t *testing.T) {
assert := assert.New(t)
out := &bytes.Buffer{}
2022-10-07 13:35:07 -04:00
s := newSpinner(out)
s.spinFunc = spinTTY
2022-10-07 13:35:07 -04:00
s.Start(baseText, false)
time.Sleep(200 * time.Millisecond)
_, err := s.Write([]byte("test"))
2022-10-07 13:35:07 -04:00
assert.NoError(err)
assert.True(strings.HasSuffix(out.String(), "test"))
}
func TestSpinNoTTY(t *testing.T) {
assert := assert.New(t)
out := &bytes.Buffer{}
s := newSpinner(out)
s.spinFunc = spinNoTTY
s.Start(baseText, true)
time.Sleep(baseWait * time.Millisecond)
s.Stop()
assert.Greater(out.Len(), 0)
assert.Equal(baseText+"...\n", out.String())
}
func generateAllStatesAsString(t *testing.T, text string, showDots bool) string {
t.Helper()
var builder strings.Builder
for i := 0; i < len(spinnerStates); i++ {
dotsState := ""
if showDots {
dotsState = dotsStates[i%len(dotsStates)]
}
builder.WriteString(fmt.Sprintf("\r%s %s%s", spinnerStates[i], text, dotsState))
}
return builder.String()
}