Files
coder/console/test_console.go
Bryan 6009c90d1d refactor: Rename 'expect' package to 'console' (#297)
Fixes #291 - renames the `expect` go package to `console`, and changes the api from `expect.NewTestConsole` to `console.New`, and a few other small changes to support the linter (ie, `ConsoleOpts` -> `Opts`)
2022-02-15 16:47:33 -08:00

46 lines
1.0 KiB
Go

package console
import (
"bufio"
"io"
"regexp"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
var (
// Used to ensure terminal output doesn't have anything crazy!
// See: https://stackoverflow.com/a/29497680
stripAnsi = regexp.MustCompile("[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))")
)
// New creates a new TTY bound to the command provided.
// All ANSI escape codes are stripped to provide clean output.
func New(t *testing.T, cmd *cobra.Command) *Console {
reader, writer := io.Pipe()
scanner := bufio.NewScanner(reader)
t.Cleanup(func() {
_ = reader.Close()
_ = writer.Close()
})
go func() {
for scanner.Scan() {
if scanner.Err() != nil {
return
}
t.Log(stripAnsi.ReplaceAllString(scanner.Text(), ""))
}
}()
console, err := NewConsole(WithStdout(writer))
require.NoError(t, err)
t.Cleanup(func() {
console.Close()
})
cmd.SetIn(console.InTty())
cmd.SetOut(console.OutTty())
return console
}