diff --git a/libs/cmdio/capabilities.go b/libs/cmdio/capabilities.go index f48c72a006a..60974014947 100644 --- a/libs/cmdio/capabilities.go +++ b/libs/cmdio/capabilities.go @@ -28,16 +28,23 @@ type Capabilities struct { // newCapabilities detects terminal capabilities from context and I/O streams. func newCapabilities(ctx context.Context, in io.Reader, out, err io.Writer) Capabilities { + noColor, dumb := colorFromEnv(ctx) return Capabilities{ stdinIsTTY: isTTY(in), stdoutIsTTY: isTTY(out), stderrIsTTY: isTTY(err), - noColor: env.Get(ctx, "NO_COLOR") != "", - dumb: env.Get(ctx, "TERM") == "dumb", + noColor: noColor, + dumb: dumb, stdinIsMSYSPipe: isMSYSPipe(in), } } +// colorFromEnv reads the color preferences from ctx: whether NO_COLOR is set, +// and whether TERM is "dumb". They are reported separately, see Capabilities. +func colorFromEnv(ctx context.Context) (noColor, dumb bool) { + return env.Get(ctx, "NO_COLOR") != "", env.Get(ctx, "TERM") == "dumb" +} + // SupportsInteractive returns true if stderr can show output that redraws // in place (spinners, prompts). NO_COLOR does not affect this; it only // removes color from that output. diff --git a/libs/cmdio/cmdiotest/pin_color_test.go b/libs/cmdio/cmdiotest/pin_color_test.go new file mode 100644 index 00000000000..dff15b742bb --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_color_test.go @@ -0,0 +1,119 @@ +package cmdiotest_test + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" + "github.com/stretchr/testify/require" +) + +// TestColorPin_Swatch pins, for each environment of the color matrix, the +// color helpers and a renderer-minted style, and whether the renderer reports +// color for the screen. The color capability comes from the environment, as in +// a real command. +// +// Two limits. The screen is a pipe, so the renderer always reports no color +// here; a real-terminal renderer (depth, profile names) is not pinned. And +// cmdio reads only NO_COLOR and TERM=dumb, so the environments other than +// no-color and term-dumb produce identical goldens. That is deliberate: it +// fails if cmdio starts reading a variable that a row sets (TERM, CI, +// CLICOLOR, COLORTERM or NO_COLOR). +func TestColorPin_Swatch(t *testing.T) { + t.Parallel() + for _, ce := range colorEnvs() { + t.Run(ce.name, func(t *testing.T) { + t.Parallel() + tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true, MapNewline: true}, func(ctx context.Context) (struct{}, error) { + _, screen := termtest.Streams(ctx) + r, color := cmdio.NewRenderer(ctx, screen) + cmdio.LogString(ctx, fmt.Sprintf("renderer color: %t", color)) + cmdio.LogString(ctx, "helpers: "+cmdio.Red(ctx, "red")+" "+cmdio.Green(ctx, "green")+" "+cmdio.Blue(ctx, "blue")+" "+ + cmdio.HiBlack(ctx, "hiblack")+" "+cmdio.HiBlue(ctx, "hiblue")+" "+cmdio.Bold(ctx, "bold")+" "+cmdio.Faint(ctx, "faint")) + cmdio.LogString(ctx, "renderer: "+r.NewStyle().Bold(true).Render("bold")+" "+r.NewStyle().Reverse(true).Render("reverse")) + return struct{}{}, nil + }) + _, err := tm.Result() + require.NoError(t, err) + tm.GoldenStyled("01-swatch") + }) + } +} + +// TestColorPin_Select pins the styled screen of a select prompt for each +// environment of the color matrix. +func TestColorPin_Select(t *testing.T) { + t.Parallel() + for _, ce := range colorEnvs() { + t.Run(ce.name, func(t *testing.T) { + t.Parallel() + tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true}, func(ctx context.Context) (string, error) { + return cmdio.SelectOrdered(ctx, pinItems(), "Pick an item") + }) + if !tm.WaitForOrExit("gamma") { + _, err := tm.Result() + termtest.GoldenText(t, "01-not-shown", fmt.Sprintf("err: %v", err)) + return + } + tm.GoldenStyled("01-initial") + tm.Type(termtest.KeyEnter) + _, err := tm.Result() + require.NoError(t, err) + }) + } +} + +// TestColorPin_Prompt pins the styled screen of a text prompt for each +// environment of the color matrix. +func TestColorPin_Prompt(t *testing.T) { + t.Parallel() + for _, ce := range colorEnvs() { + t.Run(ce.name, func(t *testing.T) { + t.Parallel() + tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true}, func(ctx context.Context) (string, error) { + return cmdio.RunPrompt(ctx, cmdio.PromptOptions{Label: "Workspace name"}) + }) + if !tm.WaitForOrExit("Workspace name") { + _, err := tm.Result() + termtest.GoldenText(t, "01-not-shown", fmt.Sprintf("err: %v", err)) + return + } + typeKeys(tm, "dev") + tm.GoldenStyled("01-typed") + tm.Type(termtest.KeyEnter) + _, err := tm.Result() + require.NoError(t, err) + }) + } +} + +// TestColorPin_Spinner pins the styled screen of a running spinner for each +// environment of the color matrix. Only TERM=dumb gets no spinner; NO_COLOR +// keeps it, uncolored. +func TestColorPin_Spinner(t *testing.T) { + t.Parallel() + for _, ce := range colorEnvs() { + t.Run(ce.name, func(t *testing.T) { + t.Parallel() + stop := make(chan struct{}) + stopOnce := sync.OnceFunc(func() { close(stop) }) + t.Cleanup(stopOnce) + tm := termtest.RunWith(t, termtest.Options{Env: ce.env, ColorFromEnv: true, MapNewline: true, Normalize: blankSpinnerFrames}, func(ctx context.Context) (struct{}, error) { + sp := cmdio.NewSpinner(ctx) + sp.Update("Working") + cmdio.LogString(ctx, "spinner started") + <-stop + sp.Close() + return struct{}{}, nil + }) + tm.WaitFor("spinner started") + tm.GoldenStyled("01-running") + stopOnce() + _, err := tm.Result() + require.NoError(t, err) + }) + } +} diff --git a/libs/cmdio/cmdiotest/pin_helpers_test.go b/libs/cmdio/cmdiotest/pin_helpers_test.go new file mode 100644 index 00000000000..f42f30fc7db --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_helpers_test.go @@ -0,0 +1,123 @@ +package cmdiotest_test + +import ( + "fmt" + "maps" + "strings" + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" +) + +// The pin tests record what the interactive components do today, including +// behavior that is accidental, so that a change of the TUI libraries shows +// up as golden diffs. They pin; they don't judge. + +// spinnerFrames are the braille frames cmdio's spinners cycle through. +const spinnerFrames = "⣾⣽⣻⢿⡿⣟⣯⣷" + +// blankSpinnerFrames replaces every spinner frame with "*", so a golden of a +// running spinner doesn't depend on which frame was on screen. +func blankSpinnerFrames(s string) string { + return strings.Map(func(r rune) rune { + if strings.ContainsRune(spinnerFrames, r) { + return '*' + } + return r + }, s) +} + +// countSpinnerFrames returns how many distinct spinner frames appear in s. +func countSpinnerFrames(s string) int { + seen := map[rune]bool{} + for _, r := range s { + if strings.ContainsRune(spinnerFrames, r) { + seen[r] = true + } + } + return len(seen) +} + +// colorEnv is one environment of the color matrix. cmdio itself reads only +// NO_COLOR and TERM. The map also sets CI, CLICOLOR, CLICOLOR_FORCE, COLORTERM +// and TERM_PROGRAM, so the TUI libraries see a fixed environment (an empty +// value reads as unset). TestColorPin_Swatch explains why the rows are kept. +type colorEnv struct { + name string + env map[string]string +} + +func colorEnvs() []colorEnv { + base := map[string]string{ + "TERM": "xterm-256color", + "COLORTERM": "", + "NO_COLOR": "", + "CLICOLOR": "", + "CLICOLOR_FORCE": "", + "CI": "", + "TERM_PROGRAM": "", + } + with := func(overrides map[string]string) map[string]string { + m := maps.Clone(base) + maps.Copy(m, overrides) + return m + } + return []colorEnv{ + {"term-unset", with(map[string]string{"TERM": ""})}, + {"term-xterm-256color", with(nil)}, + {"term-screen", with(map[string]string{"TERM": "screen"})}, + {"term-vt100", with(map[string]string{"TERM": "vt100"})}, + {"term-dumb", with(map[string]string{"TERM": "dumb"})}, + {"ci", with(map[string]string{"CI": "1"})}, + {"clicolor-0", with(map[string]string{"CLICOLOR": "0"})}, + {"no-color", with(map[string]string{"NO_COLOR": "1"})}, + {"tmux-truecolor", with(map[string]string{"TERM": "tmux-256color", "COLORTERM": "truecolor"})}, + {"colorterm-yes", with(map[string]string{"COLORTERM": "yes"})}, + } +} + +// colorEnvNamed returns the environment of the color matrix called name. +func colorEnvNamed(name string) map[string]string { + for _, ce := range colorEnvs() { + if ce.name == name { + return ce.env + } + } + panic("no color env " + name) +} + +// pinItems is the item list the select pins use. +func pinItems() []cmdio.Tuple { + return []cmdio.Tuple{ + {Name: "alpha", Id: "id-01"}, + {Name: "beta", Id: "id-02"}, + {Name: "gamma", Id: "id-03"}, + } +} + +// failWithRaw fails the test with msg and the raw output, so a missed wait +// shows what the program actually wrote. +func failWithRaw[T any](t *testing.T, tm *termtest.Term[T], format string, args ...any) { + t.Helper() + t.Fatalf("%s\n--- raw output ---\n%q", fmt.Sprintf(format, args...), tm.Raw()) +} + +// quoted renders bytes as one escaped Go string, so goldens of raw +// input or output stay readable. +func quoted(b []byte) string { + if len(b) == 0 { + return "(none)" + } + return fmt.Sprintf("%q", b) +} + +// typeKeys writes each key as its own read: it waits for the program to +// settle after every write, so two keys never reach it as one burst. Use +// [termtest.Term.TypeBurst] to test a burst on purpose. +func typeKeys[T any](tm *termtest.Term[T], keys ...string) { + for _, k := range keys { + tm.Type(k) + tm.Settle() + } +} diff --git a/libs/cmdio/cmdiotest/pin_keys_test.go b/libs/cmdio/cmdiotest/pin_keys_test.go new file mode 100644 index 00000000000..32375f72a24 --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_keys_test.go @@ -0,0 +1,162 @@ +package cmdiotest_test + +import ( + "fmt" + "testing" + "time" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" +) + +// pinPromptResult pins a prompt's outcome: the value, or the error. +func pinPromptResult(t *testing.T, tm *termtest.Term[string], step string) { + t.Helper() + v, err := tm.Result() + termtest.GoldenText(t, step, fmt.Sprintf("value: %q\nerr: %v", v, err)) +} + +func newPinPrompt(t *testing.T) *termtest.Term[string] { + t.Helper() + tm := termtest.NewPrompt(t, cmdio.PromptOptions{Label: "Value"}) + tm.WaitFor("Value") + return tm +} + +// TestKeysPin_PromptBurstKeyName pins what a prompt does with text that is +// also a key name ("enter") when it arrives in one read, as it does when +// typed fast over a slow link. +func TestKeysPin_PromptBurstKeyName(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "a") + tm.TypeBurst("enter") + tm.Settle() + typeKeys(tm, "b") + tm.Golden("01-after-burst") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") +} + +// TestKeysPin_SelectFilterBurstKeyName pins what select's search does with a +// burst of "down", a key name, typed as text. +func TestKeysPin_SelectFilterBurstKeyName(t *testing.T) { + t.Parallel() + tm := termtest.NewSelectOrdered(t, []cmdio.Tuple{ + {Name: "edown", Id: "id-01"}, + {Name: "elephant", Id: "id-02"}, + {Name: "eagle", Id: "id-03"}, + }, "Pick one") + tm.WaitFor("eagle") + typeKeys(tm, "e") + tm.TypeBurst("down") + tm.Settle() + tm.Golden("01-after-burst") + tm.Type(termtest.KeyEnter) + id, err := tm.Result() + termtest.GoldenText(t, "02-result", fmt.Sprintf("id: %q\nerr: %v", id, err)) +} + +// keyExitGrace is how long a test waits for a key that may quit the prompt, +// before typing more. Typing sooner races the quit: the next key can be queued +// ahead of the quit and land in the value. The wait returns as soon as the +// prompt exits, so the grace is only spent when the key is ignored or the exit +// is slow. A slow exit within the grace is not a failure of its own; the +// golden after the wait then shows it. +const keyExitGrace = 5 * time.Second + +// TestKeysPin_PromptAltEnter pins Alt+Enter (Esc CR) in a prompt. +func TestKeysPin_PromptAltEnter(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "ab", termtest.KeyAltEnter) + tm.WaitForExit(keyExitGrace) + typeKeys(tm, "c") + tm.Golden("01-after-alt-enter") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") +} + +// TestKeysPin_SelectAltEnter pins Alt+Enter in a select. +func TestKeysPin_SelectAltEnter(t *testing.T) { + t.Parallel() + tm := termtest.NewSelectOrdered(t, pinItems(), "Pick one") + tm.WaitFor("gamma") + typeKeys(tm, termtest.KeyDown, termtest.KeyAltEnter) + tm.Golden("01-after-alt-enter") + tm.Type(termtest.KeyEnter) + id, err := tm.Result() + termtest.GoldenText(t, "02-result", fmt.Sprintf("id: %q\nerr: %v", id, err)) +} + +// TestKeysPin_PromptAltLeft pins Alt+Left (CSI 1;3D) in the middle of a word. +func TestKeysPin_PromptAltLeft(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "abc", termtest.KeyAltLeft, "X") + tm.Golden("01-after-alt-left") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") +} + +// TestKeysPin_PromptShiftEnter pins Shift+Enter in the two encodings +// terminals use once the program enables an extended keyboard protocol. +func TestKeysPin_PromptShiftEnter(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ name, key string }{ + {"kitty", termtest.KeyShiftEnterKitty}, + {"modifyOtherKeys", termtest.KeyShiftEnterModifyOtherKey}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "xy", tc.key) + tm.WaitForExit(keyExitGrace) + typeKeys(tm, "z") + tm.Golden("01-after-shift-enter") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") + }) + } +} + +// TestKeysPin_SelectShiftEnter pins Shift+Enter in a select. +func TestKeysPin_SelectShiftEnter(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ name, key string }{ + {"kitty", termtest.KeyShiftEnterKitty}, + {"modifyOtherKeys", termtest.KeyShiftEnterModifyOtherKey}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tm := termtest.NewSelectOrdered(t, pinItems(), "Pick one") + tm.WaitFor("gamma") + typeKeys(tm, termtest.KeyDown, tc.key) + tm.Golden("01-after-shift-enter") + tm.Type(termtest.KeyEnter) + id, err := tm.Result() + termtest.GoldenText(t, "02-result", fmt.Sprintf("id: %q\nerr: %v", id, err)) + }) + } +} + +// TestKeysPin_PromptKittyEsc pins Esc in its kitty keyboard encoding. +func TestKeysPin_PromptKittyEsc(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "ab", termtest.KeyEscKitty) + tm.Golden("01-after-kitty-esc") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") +} + +// TestKeysPin_PromptBracketedPasteWithNewline pins a bracketed paste that +// contains a newline. +func TestKeysPin_PromptBracketedPasteWithNewline(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, termtest.Paste("a\r\nb")) + tm.Golden("01-after-paste") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") +} diff --git a/libs/cmdio/cmdiotest/pin_modes_test.go b/libs/cmdio/cmdiotest/pin_modes_test.go new file mode 100644 index 00000000000..c66cff8c9f6 --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_modes_test.go @@ -0,0 +1,114 @@ +package cmdiotest_test + +import ( + "context" + "strings" + "sync" + "testing" + "time" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" +) + +// The modes pins record which terminal modes each component switches +// (cursor visibility, bracketed paste, keyboard protocols, ...) and which are +// still on when it returns. A mode left on after exit changes how the +// user's shell behaves. + +// TestModesPin_Prompt pins the modes of a prompt on submit and on Ctrl+C. +func TestModesPin_Prompt(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ name, key string }{ + {"enter", termtest.KeyEnter}, + {"ctrl-c", termtest.KeyCtrlC}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "ab") + tm.Type(tc.key) + _, _ = tm.Result() + tm.GoldenModes("01-modes") + }) + } +} + +// TestModesPin_Select pins the modes of a select on submit and on Ctrl+C. +func TestModesPin_Select(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ name, key string }{ + {"enter", termtest.KeyEnter}, + {"ctrl-c", termtest.KeyCtrlC}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tm := termtest.NewSelectOrdered(t, pinItems(), "Pick one") + tm.WaitFor("gamma") + // The select's Init and bubbletea's renderer each write a cursor + // hide. A fast key can quit before the second one, which changes the + // mode log, so wait for both. This wait is deliberately tolerant: + // a version that hides once (the Charm v2 swap) must still reach + // its golden, so the diff shows the change instead of a timeout. + waitForRawCountOrGrace(t, tm, "\x1b[?25l", 2, 2*time.Second) + tm.Type(tc.key) + _, _ = tm.Result() + tm.GoldenModes("01-modes") + }) + } +} + +// TestModesPin_Spinner pins the modes of a spinner that is closed normally. +// A spinner has no input, so there is no Ctrl+C case. +func TestModesPin_Spinner(t *testing.T) { + t.Parallel() + stop := make(chan struct{}) + stopOnce := sync.OnceFunc(func() { close(stop) }) + t.Cleanup(stopOnce) + tm := termtest.Run(t, func(ctx context.Context) (struct{}, error) { + sp := cmdio.NewSpinner(ctx) + sp.Update("Working") + <-stop + sp.Close() + return struct{}{}, nil + }) + tm.WaitFor("Working") + stopOnce() + _, _ = tm.Result() + tm.GoldenModes("01-modes") +} + +// TestModesPin_Pager pins the modes of the pager when it drains the list +// and when the user quits at the prompt between pages. +func TestModesPin_Pager(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ name, key string }{ + {"enter-drains", termtest.KeyEnter}, + {"ctrl-c", termtest.KeyCtrlC}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + it := newPinIterator(120, -1, 0) + tm := runPinPager(t, it) + loadPage(tm, it) + tm.WaitForScreen(pagerPrompt) + tm.Type(tc.key) + _, _ = tm.Result() + tm.GoldenModes("01-modes") + }) + } +} + +// waitForRawCountOrGrace waits until the program has written want copies of seq, or +// grace elapses. It never fails: the caller decides what a missing sequence +// means. +func waitForRawCountOrGrace(t *testing.T, tm *termtest.Term[string], seq string, want int, grace time.Duration) { + t.Helper() + deadline := time.Now().Add(grace) + for strings.Count(tm.Raw(), seq) < want && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if got := strings.Count(tm.Raw(), seq); got < want { + t.Logf("waited %s for %d×%q, saw %d; a missing mode line below may come from this", grace, want, seq, got) + } +} diff --git a/libs/cmdio/cmdiotest/pin_pager_test.go b/libs/cmdio/cmdiotest/pin_pager_test.go new file mode 100644 index 00000000000..c4ba984c2bf --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_pager_test.go @@ -0,0 +1,258 @@ +package cmdiotest_test + +import ( + "context" + "errors" + "fmt" + "regexp" + "sync" + "testing" + "time" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" +) + +// pagerPrompt is the text the pager shows between pages. +const pagerPrompt = "[space] more" + +// waitForOutputPast waits until the program has written more than n bytes of +// any output. A missed wait fails the test rather than letting a golden after +// it depend on timing. +func waitForOutputPast(t *testing.T, tm *termtest.Term[struct{}], n int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for len(tm.Raw()) <= n && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if len(tm.Raw()) <= n { + failWithRaw(t, tm, "no output within 5s after input was read") + } +} + +// pinRow is the element type the pager pins list. +type pinRow struct { + Name string + State string +} + +// pinIterator is a listing.Iterator over n rows that stops before each row +// index in holds until the test calls release, so a test can look at the +// pager while a page is loading. With failAt >= 0 it returns an error +// instead of row failAt. +type pinIterator struct { + n, failAt int + holds []int + gates []chan struct{} + + mu sync.Mutex + i int + released int +} + +// pinPageSize is the pager's page size in tests: without a window size it +// uses its fallback of 50 rows. Only that fallback is pinned. RenderIterator +// starts its own program and gets no window size, so the path that sizes the +// page from the terminal height is not reached by these pins. +const pinPageSize = 50 + +func newPinIterator(n, failAt int, holds ...int) *pinIterator { + it := &pinIterator{n: n, failAt: failAt, holds: holds} + for range holds { + it.gates = append(it.gates, make(chan struct{})) + } + return it +} + +// release lets the iterator past its next hold. +func (it *pinIterator) release() { + it.mu.Lock() + defer it.mu.Unlock() + close(it.gates[it.released]) + it.released++ +} + +func (it *pinIterator) HasNext(ctx context.Context) bool { + it.mu.Lock() + i := it.i + it.mu.Unlock() + for h, at := range it.holds { + if at == i { + select { + case <-it.gates[h]: + case <-ctx.Done(): + return false + } + } + } + it.mu.Lock() + defer it.mu.Unlock() + return it.i < it.n || it.i == it.failAt +} + +func (it *pinIterator) Next(ctx context.Context) (pinRow, error) { + it.mu.Lock() + defer it.mu.Unlock() + if it.i == it.failAt { + return pinRow{}, errors.New("injected iterator error") + } + it.i++ + return pinRow{Name: fmt.Sprintf("item-%03d", it.i), State: "ready"}, nil +} + +// loadPage waits until the pager shows its loading spinner and then lets the +// iterator past its next hold, so every page lands after the spinner has +// been painted. Whether it was painted decides which characters a printed +// row leaves behind, so this keeps the screens deterministic. +func loadPage(tm *termtest.Term[struct{}], it *pinIterator) { + tm.WaitForScreen("loading...") + it.release() +} + +// runPinPager renders it through cmdio.RenderIterator with a row template, +// so the production pager gate pages it. Screens keep only the printed rows +// on their lines; see onlyPagerRows. +func runPinPager(t *testing.T, it *pinIterator) *termtest.Term[struct{}] { + t.Helper() + tm := termtest.RunWith(t, termtest.Options{ + CaptureStdout: true, + HeaderTemplate: "NAME\tSTATE", + Template: "{{range .}}{{.Name}}\t{{.State}}\n{{end}}", + ScreenRows: 200, + Normalize: onlyPagerRows, + }, func(ctx context.Context) (struct{}, error) { + return struct{}{}, cmdio.RenderIterator(ctx, it) + }) + tm.LogRawOnFailure() + return tm +} + +// pagerRowLine matches a header or data row the pager printed, ignoring +// what follows it on the same screen line. +var pagerRowLine = regexp.MustCompile(`(?m)^(NAME +STATE|item-\d{3} +ready).*$`) + +// onlyPagerRows keeps just the printed row on each line that starts with one. +// Part of the spinner or prompt line may or may not survive next to a +// printed row, depending on whether the renderer painted its view before or +// after the rows were flushed. That leftover is timing, not behavior, so the +// pager pins drop it. +func onlyPagerRows(s string) string { + return pagerRowLine.ReplaceAllString(s, "$1") +} + +func pinPagerResult(t *testing.T, tm *termtest.Term[struct{}], step string) { + t.Helper() + _, err := tm.Result() + termtest.GoldenText(t, step, fmt.Sprintf("err: %v", err)) +} + +// observeSpinnerFrames waits up to d for want distinct spinner frames and +// describes what it saw. Falling short is not a test failure: the count is +// the behaviour being pinned, so a spinner that stops animating shows up as a +// golden diff. The wait is bounded by d. +func observeSpinnerFrames(tm *termtest.Term[struct{}], want int, d time.Duration) string { + deadline := time.Now().Add(d) + for { + n := countSpinnerFrames(tm.Raw()) + if n >= want { + return fmt.Sprintf("distinct spinner frames: at least %d", want) + } + if time.Now().After(deadline) { + return fmt.Sprintf("distinct spinner frames: %d (fewer than %d within %s)", n, want, d) + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestPagerPin_SpinnerDuringFirstPage pins whether the spinner animates +// while the first page loads, and the screen once it has landed. +func TestPagerPin_SpinnerDuringFirstPage(t *testing.T) { + t.Parallel() + it := newPinIterator(120, -1, 0) + tm := runPinPager(t, it) + termtest.GoldenText(t, "01-first-page-loading", observeSpinnerFrames(tm, 3, 3*time.Second)) + loadPage(tm, it) + tm.WaitForScreen(pagerPrompt) + tm.Golden("02-first-page") + tm.Type("q") + pinPagerResult(t, tm, "03-result") +} + +// TestPagerPin_EnterWhileFirstPageLoads pins Enter pressed before the first +// page has landed: whether the spinner animates and what ends up on screen +// once everything has been drained. +func TestPagerPin_EnterWhileFirstPageLoads(t *testing.T) { + t.Parallel() + it := newPinIterator(120, -1, 0) + tm := runPinPager(t, it) + termtest.GoldenText(t, "01-first-page-loading", observeSpinnerFrames(tm, 2, 3*time.Second)) + tm.Type(termtest.KeyEnter) + before := len(tm.Raw()) + waitForOutputPast(t, tm, before) + loadPage(tm, it) + pinPagerResult(t, tm, "02-result") + tm.Golden("03-final") +} + +// TestPagerPin_SpaceLoadsNextPage pins one more page on space. +// +// Settle keeps space from arriving while a render of the first page is still +// in flight. On failure the test logs the raw output stream for diagnosis. +func TestPagerPin_SpaceLoadsNextPage(t *testing.T) { + t.Parallel() + it := newPinIterator(120, -1, 0, pinPageSize) + tm := runPinPager(t, it) + loadPage(tm, it) + tm.WaitForScreen(pagerPrompt) + tm.Settle() + tm.Type(" ") + loadPage(tm, it) + tm.WaitForScreen("item-100") + tm.WaitForScreen(pagerPrompt) + tm.Golden("01-second-page") + tm.Type("q") + pinPagerResult(t, tm, "02-result") +} + +// TestPagerPin_ErrorOnFirstPage pins an iterator error before any row. +func TestPagerPin_ErrorOnFirstPage(t *testing.T) { + t.Parallel() + it := newPinIterator(120, 0, 0) + tm := runPinPager(t, it) + loadPage(tm, it) + pinPagerResult(t, tm, "01-result") + tm.Golden("02-final") +} + +// TestPagerPin_ErrorOnLaterPage pins an iterator error on the second page. +func TestPagerPin_ErrorOnLaterPage(t *testing.T) { + t.Parallel() + it := newPinIterator(120, 60, 0, pinPageSize) + tm := runPinPager(t, it) + loadPage(tm, it) + tm.WaitForScreen(pagerPrompt) + tm.Type(" ") + loadPage(tm, it) + pinPagerResult(t, tm, "01-result") + tm.Golden("02-final") +} + +// TestPagerPin_EmptyResult pins a list with no rows. +func TestPagerPin_EmptyResult(t *testing.T) { + t.Parallel() + it := newPinIterator(0, -1, 0) + tm := runPinPager(t, it) + loadPage(tm, it) + pinPagerResult(t, tm, "01-result") + tm.Golden("02-final") +} + +// TestPagerPin_FitsOnePage pins a list shorter than a page. +func TestPagerPin_FitsOnePage(t *testing.T) { + t.Parallel() + it := newPinIterator(5, -1, 0) + tm := runPinPager(t, it) + loadPage(tm, it) + pinPagerResult(t, tm, "01-result") + tm.Golden("02-final") +} diff --git a/libs/cmdio/cmdiotest/pin_queries_test.go b/libs/cmdio/cmdiotest/pin_queries_test.go new file mode 100644 index 00000000000..b1ae51b8b55 --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_queries_test.go @@ -0,0 +1,100 @@ +package cmdiotest_test + +import ( + "context" + "runtime" + "testing" + "time" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" +) + +// slowTerminal answers every query, but only after the program has had +// time to quit, the way a terminal over a slow link does. +var slowTerminal = &termtest.Responder{Delay: 300 * time.Millisecond} + +func skipLeftoverOnWindows(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("reading leftover input needs pipe read deadlines, which Windows lacks") + } +} + +// TestQueriesPin_PromptQuitBeforeReplies pins the terminal queries a prompt +// writes and the reply bytes left unread when it quits before a slow +// terminal answers. Those bytes are what the shell reads next. +func TestQueriesPin_PromptQuitBeforeReplies(t *testing.T) { + t.Parallel() + skipLeftoverOnWindows(t) + tm := termtest.RunWith(t, termtest.Options{Responder: slowTerminal, CaptureLeftover: true}, func(ctx context.Context) (string, error) { + return cmdio.RunPrompt(ctx, cmdio.PromptOptions{Label: "Value"}) + }) + tm.WaitFor("Value") + typeKeys(tm, "ab") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "01-result") + tm.GoldenQueries("02-queries") + leftover, err := tm.Leftover() + if err != nil { + t.Fatal(err) + } + termtest.GoldenText(t, "03-leftover", quoted(leftover)) +} + +// TestQueriesPin_SelectQuitBeforeReplies is the select counterpart of +// TestQueriesPin_PromptQuitBeforeReplies. +func TestQueriesPin_SelectQuitBeforeReplies(t *testing.T) { + t.Parallel() + skipLeftoverOnWindows(t) + tm := termtest.RunWith(t, termtest.Options{Responder: slowTerminal, CaptureLeftover: true}, func(ctx context.Context) (string, error) { + return cmdio.SelectOrdered(ctx, pinItems(), "Pick one") + }) + tm.WaitFor("gamma") + tm.Type(termtest.KeyEnter) + _, _ = tm.Result() + tm.GoldenQueries("01-queries") + leftover, err := tm.Leftover() + if err != nil { + t.Fatal(err) + } + termtest.GoldenText(t, "02-leftover", quoted(leftover)) +} + +// TestQueriesPin_PromptTerminalAnswersAtOnce pins the queries and leftover +// when the terminal answers at once, before the user quits. +func TestQueriesPin_PromptTerminalAnswersAtOnce(t *testing.T) { + t.Parallel() + skipLeftoverOnWindows(t) + tm := termtest.RunWith(t, termtest.Options{Responder: &termtest.Responder{}, CaptureLeftover: true}, func(ctx context.Context) (string, error) { + return cmdio.RunPrompt(ctx, cmdio.PromptOptions{Label: "Value"}) + }) + tm.WaitFor("Value") + // Replies are written on a poll, so without this they could land between + // the typed keys. The golden is the same either way, but the wait keeps + // the reply and the key from racing. + tm.WaitForReplies() + typeKeys(tm, "ab") + tm.Golden("01-typed") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") + tm.GoldenQueries("03-queries") + leftover, err := tm.Leftover() + if err != nil { + t.Fatal(err) + } + termtest.GoldenText(t, "04-leftover", quoted(leftover)) +} + +// TestQueriesPin_PromptUnsolicitedBackgroundReply pins what a prompt does +// with an OSC 11 (background color) reply that arrives on its input without +// it having asked, e.g. a late answer to a query written before the prompt +// started. +func TestQueriesPin_PromptUnsolicitedBackgroundReply(t *testing.T) { + t.Parallel() + tm := newPinPrompt(t) + typeKeys(tm, "ab", termtest.DefaultReply("OSC 11")) + tm.Golden("01-after-reply") + tm.Type(termtest.KeyEnter) + pinPromptResult(t, tm, "02-result") +} diff --git a/libs/cmdio/cmdiotest/pin_stderr_test.go b/libs/cmdio/cmdiotest/pin_stderr_test.go new file mode 100644 index 00000000000..8750240b8f8 --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_stderr_test.go @@ -0,0 +1,45 @@ +package cmdiotest_test + +import ( + "context" + "fmt" + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" + "github.com/stretchr/testify/require" +) + +// TestStderrPin_LogStringStyles pins the bytes cmdio.LogString writes to +// stderr for strings styled by the color helpers (which check stdout) and by +// a renderer bound to stderr. The cases vary which streams are terminals and +// whether NO_COLOR is set. The renderer's color is always plain here, because +// the screen is a pipe, so only the helper's styling varies in the goldens. +func TestStderrPin_LogStringStyles(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + opts termtest.Options + }{ + {"stdout-tty-stderr-redirected", termtest.Options{StderrNotTTY: true}}, + {"stdout-redirected-stderr-tty", termtest.Options{StdoutNotTTY: true}}, + // NO_COLOR with both streams on a terminal: the helpers and the + // renderer bound to stderr are plain. + {"no-color-both-tty", termtest.Options{Env: colorEnvNamed("no-color"), ColorFromEnv: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tm := termtest.RunWith(t, tc.opts, func(ctx context.Context) (struct{}, error) { + _, stderr := termtest.Streams(ctx) + r, color := cmdio.NewRenderer(ctx, stderr) + cmdio.LogString(ctx, fmt.Sprintf("renderer color: %t", color)) + cmdio.LogString(ctx, "helper: "+cmdio.Red(ctx, "red")) + cmdio.LogString(ctx, "renderer: "+r.NewStyle().Bold(true).Render("bold")) + return struct{}{}, nil + }) + _, err := tm.Result() + require.NoError(t, err) + termtest.GoldenText(t, "01-stderr-bytes", quoted([]byte(tm.Raw()))) + }) + } +} diff --git a/libs/cmdio/cmdiotest/pin_tableview_test.go b/libs/cmdio/cmdiotest/pin_tableview_test.go new file mode 100644 index 00000000000..16ae743774e --- /dev/null +++ b/libs/cmdio/cmdiotest/pin_tableview_test.go @@ -0,0 +1,38 @@ +package cmdiotest_test + +import ( + "context" + "fmt" + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/cmdio/cmdiotest/termtest" + "github.com/databricks/cli/libs/tableview" +) + +// TestTableviewPin_SearchInput pins what tableview's search input does with +// Alt+f and a bracketed paste, and the styled screen around it. +func TestTableviewPin_SearchInput(t *testing.T) { + t.Parallel() + rows := make([][]string, 0, 20) + for i := 1; i <= 20; i++ { + rows = append(rows, []string{fmt.Sprintf("item-%02d", i), "ready"}) + } + tm := termtest.Run(t, func(ctx context.Context) (struct{}, error) { + in, out := termtest.Streams(ctx) + return struct{}{}, tableview.RunWithOptions(ctx, out, []string{"NAME", "STATE"}, rows, tableview.RunOptions{ + Input: in, + Width: cmdio.TestTerminalWidth, + Height: cmdio.TestTerminalHeight, + }) + }) + tm.WaitFor("item-01") + tm.GoldenStyled("01-initial") + typeKeys(tm, "/", "it", termtest.KeyAltF, termtest.Paste("em-1")) + tm.Golden("02-search-input") + tm.Type(termtest.KeyEnter) + tm.GoldenStyled("03-after-search") + tm.Type("q") + _, err := tm.Result() + termtest.GoldenText(t, "04-result", fmt.Sprintf("err: %v", err)) +} diff --git a/libs/cmdio/cmdiotest/termtest/emulator.go b/libs/cmdio/cmdiotest/termtest/emulator.go index 1072ff6e691..9b3b22efe7a 100644 --- a/libs/cmdio/cmdiotest/termtest/emulator.go +++ b/libs/cmdio/cmdiotest/termtest/emulator.go @@ -13,10 +13,15 @@ import ( // Scope is deliberately narrow: bubbletea's stock renderer (which is what // the cmdio prompt/select models run through) emits a small subset of CSI // sequences — cursor moves, erase-line, set/reset-mode for cursor -// visibility — plus printable runes, CR, LF, and BS. SGR styling, alt-screen -// switches, scroll regions, charsets, OSC, DCS, and friends are recognised -// by the underlying ansi parser but intentionally ignored: they do not -// affect cell text. +// visibility — plus printable runes, CR, LF, and BS. Alt-screen switches, +// scroll regions, charsets, DCS, and friends are recognised by the +// underlying ansi parser but intentionally ignored: they do not affect cell +// text. SGR styling, DEC private modes, keyboard protocol switches and +// terminal queries are recorded alongside the text for the styled, modes +// and queries goldens (see observe.go), without changing what String +// returns. Cursor movement covers the usual CUU/CUD/CUP family and the +// unprefixed SCO save/restore pair (CSI s and CSI u); prefixed forms such as +// the kitty keyboard CSI ? u and CSI > n u do not move the cursor. type emulator struct { width, height int grid [][]rune @@ -25,6 +30,20 @@ type emulator struct { // Saved cursor (DECSC/DECRC; ESC 7 / ESC 8). savedRow, savedCol int + // mapNewline makes LF also return to column 0, like a cooked tty's + // ONLCR. Off by default: bubbletea v1 writes CRLF itself. + mapNewline bool + + // Observation state for the styled, modes and queries goldens. None of + // it affects cell text (see observe.go). + styles [][]cellStyle + pen cellStyle + privateModes map[int]bool + modeEvents []modeEvent + kittyStack []int + modifyOtherKeys int + queries []string + parser *ansi.Parser } @@ -37,19 +56,25 @@ func newEmulator(width, height int) *emulator { Execute: e.handleControl, HandleCsi: e.handleCsi, HandleEsc: e.handleEsc, + HandleOsc: e.handleOsc, }) return e } -// reset clears the screen and homes the cursor. +// reset clears the screen, homes the cursor, and resets the pen and the +// private modes. func (e *emulator) reset() { e.grid = make([][]rune, e.height) + e.styles = make([][]cellStyle, e.height) for i := range e.grid { e.grid[i] = make([]rune, e.width) + e.styles[i] = make([]cellStyle, e.width) for j := range e.grid[i] { e.grid[i][j] = ' ' } } + e.pen = cellStyle{} + e.privateModes = map[int]bool{} e.row, e.col = 0, 0 e.savedRow, e.savedCol = 0, 0 } @@ -83,6 +108,7 @@ func (e *emulator) handlePrint(r rune) { } if e.inBounds() { e.grid[e.row][e.col] = r + e.styles[e.row][e.col] = e.pen } e.col++ } @@ -101,15 +127,20 @@ func (e *emulator) handleControl(b byte) { if e.row+1 < e.height { e.row++ } + if e.mapNewline { + e.col = 0 + } case 0x0d: // CR: start of line. e.col = 0 } } // handleCsi handles the CSI sequences emitted by bubbletea's renderer. -// Only commands that affect cell positions or contents matter. SGR (colors, -// 'm') and DEC private modes ('h'/'l' with '?' prefix) are no-ops. +// Only commands that affect cell positions or contents matter. SGR ('m') and +// the mode and query sequences do not move the cursor or change cell text; +// observeCsi records the ones the goldens pin. func (e *emulator) handleCsi(cmd ansi.Cmd, params ansi.Params) { + e.observeCsi(cmd, params) n, _, _ := params.Param(0, 1) switch cmd.Final() { case 'A': // CUU: cursor up @@ -142,9 +173,13 @@ func (e *emulator) handleCsi(cmd ansi.Cmd, params ansi.Params) { n, _, _ := params.Param(0, 0) e.eraseLine(n) case 's': // SCO save cursor - e.savedRow, e.savedCol = e.row, e.col - case 'u': // SCO restore cursor - e.row, e.col = e.savedRow, e.savedCol + if cmd.Prefix() == 0 { + e.savedRow, e.savedCol = e.row, e.col + } + case 'u': // SCO restore cursor; prefixed forms are kitty keyboard sequences. + if cmd.Prefix() == 0 { + e.row, e.col = e.savedRow, e.savedCol + } // All other CSI commands (SGR 'm', mode set/reset 'h'/'l', cursor // show/hide '?25h/l', etc.) are no-ops for cell text. } @@ -171,15 +206,15 @@ func (e *emulator) eraseLine(n int) { switch n { case 0: for i := e.col; i < e.width; i++ { - line[i] = ' ' + e.clearCell(e.row, i) } case 1: for i := 0; i <= e.col && i < e.width; i++ { - line[i] = ' ' + e.clearCell(e.row, i) } case 2: for i := range line { - line[i] = ' ' + e.clearCell(e.row, i) } } } @@ -192,25 +227,34 @@ func (e *emulator) eraseDisplay(n int) { e.eraseLine(0) for r := e.row + 1; r < e.height; r++ { for c := range e.grid[r] { - e.grid[r][c] = ' ' + e.clearCell(r, c) } } case 1: for r := range e.row { for c := range e.grid[r] { - e.grid[r][c] = ' ' + e.clearCell(r, c) } } e.eraseLine(1) case 2, 3: for r := range e.grid { for c := range e.grid[r] { - e.grid[r][c] = ' ' + e.clearCell(r, c) } } } } +// clearCell blanks one cell and resets its style. Erased cells take the +// default style rather than the pen's background. The pins do not cover an +// erase under a colored background, so this is a modelling choice, not a +// measured property of bubbletea. +func (e *emulator) clearCell(r, c int) { + e.grid[r][c] = ' ' + e.styles[r][c] = cellStyle{} +} + func (e *emulator) inBounds() bool { return e.row >= 0 && e.row < e.height && e.col >= 0 && e.col < e.width } diff --git a/libs/cmdio/cmdiotest/termtest/observe.go b/libs/cmdio/cmdiotest/termtest/observe.go new file mode 100644 index 00000000000..70c901a8def --- /dev/null +++ b/libs/cmdio/cmdiotest/termtest/observe.go @@ -0,0 +1,413 @@ +package termtest + +import ( + "fmt" + "slices" + "strconv" + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// cellStyle is the SGR state of one screen cell. The zero value is the +// terminal's default style. Colors keep the form they were sent in: a 16-color +// index as a number, a 256-color index with an `@` prefix, or truecolor as +// `#rrggbb`. The color depth a program picks is part of what the styled +// goldens pin. +type cellStyle struct { + fg, bg string + bold bool + faint bool + italic bool + underline string // "", "single", "double", "curly", "dotted" or "dashed" + blink bool + reverse bool + strikethrough bool + overline bool +} + +// marker renders the style as the space-separated attribute list used inside +// a `{...}` marker, in a fixed order. +func (s cellStyle) marker() string { + var parts []string + if s.fg != "" { + parts = append(parts, "fg="+s.fg) + } + if s.bg != "" { + parts = append(parts, "bg="+s.bg) + } + for _, a := range []struct { + on bool + name string + }{ + {s.bold, "bold"}, + {s.faint, "faint"}, + {s.italic, "italic"}, + {s.underline != "" && s.underline != "single", s.underline + "-underline"}, + {s.underline == "single", "underline"}, + {s.blink, "blink"}, + {s.reverse, "reverse"}, + {s.strikethrough, "strikethrough"}, + {s.overline, "overline"}, + } { + if a.on { + parts = append(parts, a.name) + } + } + return strings.Join(parts, " ") +} + +// underlineStyles maps the subparameter of SGR 4:n to an underline style. +var underlineStyles = map[int]string{1: "single", 2: "double", 3: "curly", 4: "dotted", 5: "dashed"} + +// applySGR updates the pen from the parameters of an SGR (CSI ... m) +// sequence. A colon group such as 4:3 or 38:2::r:g:b arrives as one group, +// with the sub-parameters packed with HasMore; semicolon forms such as +// 38;2;r;g;b arrive as separate single-value groups. +func (e *emulator) applySGR(params ansi.Params) { + if len(params) == 0 { + e.pen = cellStyle{} + return + } + groups := sgrGroups(params) + for i := 0; i < len(groups); i++ { + g := groups[i] + if len(g) > 1 { + e.applyColonSGR(g) + continue + } + switch v := g[0]; { + case v == 0: + e.pen = cellStyle{} + case v == 1: + e.pen.bold = true + case v == 2: + e.pen.faint = true + case v == 3: + e.pen.italic = true + case v == 4: + e.pen.underline = "single" + case v == 5: + e.pen.blink = true + case v == 7: + e.pen.reverse = true + case v == 9: + e.pen.strikethrough = true + case v == 21: + e.pen.underline = "double" + case v == 22: + e.pen.bold, e.pen.faint = false, false + case v == 23: + e.pen.italic = false + case v == 24: + e.pen.underline = "" + case v == 25: + e.pen.blink = false + case v == 27: + e.pen.reverse = false + case v == 29: + e.pen.strikethrough = false + case v >= 30 && v <= 37: + e.pen.fg = strconv.Itoa(v - 30) + case v == 39: + e.pen.fg = "" + case v >= 40 && v <= 47: + e.pen.bg = strconv.Itoa(v - 40) + case v == 49: + e.pen.bg = "" + case v >= 90 && v <= 97: + e.pen.fg = strconv.Itoa(v - 90 + 8) + case v >= 100 && v <= 107: + e.pen.bg = strconv.Itoa(v - 100 + 8) + case v == 53: + e.pen.overline = true + case v == 55: + e.pen.overline = false + case v == 38 || v == 48 || v == 58: + // The color follows as separate values: 38;5;n or 38;2;r;g;b. + // When they do not form a color, nothing is consumed and the + // following values apply as plain SGR codes, as in xterm. + if c, n, ok := extendedColor(singleValues(groups[i+1:])); ok { + i += n + e.setColor(v, c) + } + } + } +} + +// sgrGroups splits SGR parameters into groups: a group is one parameter +// followed by its colon sub-parameters, if any. +func sgrGroups(params ansi.Params) [][]int { + var groups [][]int + var cur []int + for _, p := range params { + cur = append(cur, p.Param(0)) + if !p.HasMore() { + groups = append(groups, cur) + cur = nil + } + } + if len(cur) > 0 { + groups = append(groups, cur) + } + return groups +} + +// singleValues returns the values of the leading single-value groups, which +// are the semicolon-separated parameters of an extended color. +func singleValues(groups [][]int) []int { + var vals []int + for _, g := range groups { + if len(g) != 1 { + break + } + vals = append(vals, g[0]) + } + return vals +} + +// applyColonSGR applies a colon group: 4:n sets the underline style, and +// 38/48/58 take an extended color in the colon form. +func (e *emulator) applyColonSGR(g []int) { + switch g[0] { + case 4: + if style, ok := underlineStyles[g[1]]; ok { + e.pen.underline = style + } else if g[1] == 0 { + e.pen.underline = "" + } + case 38, 48, 58: + if c, ok := colonColor(g[1:]); ok { + e.setColor(g[0], c) + } + } +} + +// setColor sets the foreground (38) or background (48). Underline colors (58) +// are not modelled; their values are skipped by the callers. +func (e *emulator) setColor(code int, c string) { + switch code { + case 38: + e.pen.fg = c + case 48: + e.pen.bg = c + } +} + +// extendedColor decodes the semicolon form of a 38, 48 or 58 SGR code, given +// the values after it. It returns the color, how many values it consumed, and +// false if the values do not form a color. +func extendedColor(rest []int) (string, int, bool) { + if len(rest) == 0 { + return "", 0, false + } + switch rest[0] { + case 5: + if len(rest) >= 2 { + return "@" + strconv.Itoa(rest[1]), 2, true + } + case 2: + if len(rest) >= 4 { + return rgbColor(rest[1], rest[2], rest[3]), 4, true + } + } + return "", 0, false +} + +// colonColor decodes the sub-parameters after 38, 48 or 58 in the colon form: +// 5:n, or 2:r:g:b and 2::r:g:b (with an optional color space id). It returns +// false if they do not form a color. +func colonColor(sub []int) (string, bool) { + if len(sub) == 0 { + return "", false + } + switch sub[0] { + case 5: + if len(sub) >= 2 { + return "@" + strconv.Itoa(sub[1]), true + } + case 2: + switch { + case len(sub) >= 5: + return rgbColor(sub[2], sub[3], sub[4]), true + case len(sub) >= 4: + return rgbColor(sub[1], sub[2], sub[3]), true + } + } + return "", false +} + +func rgbColor(r, g, b int) string { + return fmt.Sprintf("#%02x%02x%02x", r, g, b) +} + +// modeEvent is one terminal mode change seen in the output stream. +type modeEvent struct { + name string + value string +} + +func (m modeEvent) String() string { + if m.value == "" { + return m.name + } + return m.name + " " + m.value +} + +// observeCsi records the CSI sequences that do not move the cursor but that +// the modes, queries and styles goldens pin. It runs before the cell-level +// handling in handleCsi. +func (e *emulator) observeCsi(cmd ansi.Cmd, params ansi.Params) { + prefix, inter, final := cmd.Prefix(), cmd.Intermediate(), cmd.Final() + first, _, _ := params.Param(0, 0) + switch { + case prefix == 0 && inter == 0 && final == 'm': + e.applySGR(params) + case prefix == '?' && inter == 0 && (final == 'h' || final == 'l'): + for _, p := range params { + n := p.Param(0) + set := final == 'h' + e.privateModes[n] = set + e.recordMode(modeEvent{name: "?" + strconv.Itoa(n), value: setWord(set)}) + } + case prefix == '?' && inter == '$' && final == 'p': + e.recordQuery("DECRQM ?" + strconv.Itoa(first)) + case prefix == '?' && inter == 0 && final == 'u': + e.recordQuery("kitty-keyboard-flags") + case prefix == '>' && inter == 0 && final == 'u': + e.kittyStack = append(e.kittyStack, first) + e.recordMode(modeEvent{name: "kitty-keyboard", value: "push " + strconv.Itoa(first)}) + case prefix == '<' && inter == 0 && final == 'u': + n := max(first, 1) + e.kittyStack = e.kittyStack[:max(len(e.kittyStack)-n, 0)] + e.recordMode(modeEvent{name: "kitty-keyboard", value: "pop " + strconv.Itoa(n)}) + // The mode parameter (1 set, 2 OR, 3 AND-NOT) is not decoded: the log + // records the flags only. + case prefix == '=' && inter == 0 && final == 'u': + e.recordMode(modeEvent{name: "kitty-keyboard", value: "set " + strconv.Itoa(first)}) + case prefix == '>' && inter == 0 && final == 'm': + if first == 4 { + level, _, _ := params.Param(1, 0) + e.modifyOtherKeys = level + e.recordMode(modeEvent{name: "modifyOtherKeys", value: strconv.Itoa(level)}) + } + case prefix == '?' && inter == 0 && final == 'W' && first == 5: + e.recordMode(modeEvent{name: "DECST8C"}) + case prefix == 0 && inter == 0 && final == 'n' && first == 6: + e.recordQuery("CPR") + case prefix == 0 && inter == 0 && final == 'c': + e.recordQuery("DA1") + case prefix == '>' && inter == 0 && final == 'c': + e.recordQuery("DA2") + case prefix == '>' && inter == 0 && final == 'q': + e.recordQuery("XTVERSION") + } +} + +// handleOsc records OSC queries (a "?" argument) such as OSC 11, the +// background color query. +func (e *emulator) handleOsc(cmd int, data []byte) { + if strings.HasSuffix(string(data), ";?") { + e.recordQuery("OSC " + strconv.Itoa(cmd)) + } +} + +// recordMode keeps every change, including an immediate repeat, so a program +// that writes the same mode twice shows up in the golden. +func (e *emulator) recordMode(ev modeEvent) { + e.modeEvents = append(e.modeEvents, ev) +} + +func (e *emulator) recordQuery(q string) { + e.queries = append(e.queries, q) +} + +// styledString renders the screen like String but with inline style +// markers: `{attrs}` opens a styled span, `{/}` returns to the default style, +// and a change between two non-default styles emits a single new opening +// marker. Every line closes its span before the newline. A literal `{` is +// written as `{{`. Trailing default-styled blanks are trimmed and trailing +// empty lines dropped, matching Snapshot. +func (e *emulator) styledString() string { + lines := make([]string, len(e.grid)) + for r, row := range e.grid { + end := len(row) + for end > 0 && (row[end-1] == ' ' || row[end-1] == '\t') && e.styles[r][end-1] == (cellStyle{}) { + end-- + } + var b strings.Builder + cur := cellStyle{} + for c := range end { + st := e.styles[r][c] + if st != cur { + if st == (cellStyle{}) { + b.WriteString("{/}") + } else { + b.WriteString("{" + st.marker() + "}") + } + cur = st + } + if row[c] == '{' { + b.WriteString("{{") + } else { + b.WriteRune(row[c]) + } + } + if cur != (cellStyle{}) { + b.WriteString("{/}") + } + lines[r] = b.String() + } + for len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + return strings.Join(lines, "\n") +} + +// modesString renders the mode-change log and the modes still active, i.e. +// differing from a terminal's power-on state (cursor visible, everything else +// off). +func (e *emulator) modesString() string { + var b strings.Builder + b.WriteString("-- changes --\n") + for _, ev := range e.modeEvents { + b.WriteString(ev.String() + "\n") + } + b.WriteString("-- active at end --\n") + keys := make([]int, 0, len(e.privateModes)) + for k := range e.privateModes { + keys = append(keys, k) + } + slices.Sort(keys) + for _, k := range keys { + set := e.privateModes[k] + // The cursor (?25) is visible by default; every other mode is off. + if (k == 25 && !set) || (k != 25 && set) { + fmt.Fprintf(&b, "?%d %s\n", k, setWord(set)) + } + } + if len(e.kittyStack) > 0 { + fmt.Fprintf(&b, "kitty-keyboard stack %v\n", e.kittyStack) + } + if e.modifyOtherKeys != 0 { + fmt.Fprintf(&b, "modifyOtherKeys %d\n", e.modifyOtherKeys) + } + return b.String() +} + +// queriesString renders the queries seen in the output stream, one per line. +func (e *emulator) queriesString() string { + var b strings.Builder + for _, q := range e.queries { + b.WriteString(q + "\n") + } + return b.String() +} + +// setWord is how a mode change is written in the mode log. +func setWord(set bool) string { + if set { + return "set" + } + return "reset" +} diff --git a/libs/cmdio/cmdiotest/termtest/observe_test.go b/libs/cmdio/cmdiotest/termtest/observe_test.go new file mode 100644 index 00000000000..b13fed50c22 --- /dev/null +++ b/libs/cmdio/cmdiotest/termtest/observe_test.go @@ -0,0 +1,199 @@ +package termtest + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestStyled_PlainScreenMatchesString(t *testing.T) { + e := feed("hello\r\nworld") + assert.Equal(t, "hello\nworld", e.styledString()) +} + +func TestStyled_SixteenColorAndReset(t *testing.T) { + e := feed("\x1b[34m?\x1b[0m Pick") + assert.Equal(t, "{fg=4}?{/} Pick", e.styledString()) +} + +func TestStyled_BrightColorsAreEightToFifteen(t *testing.T) { + e := feed("\x1b[92ma\x1b[0m\x1b[101mb\x1b[0m") + assert.Equal(t, "{fg=10}a{bg=9}b{/}", e.styledString()) +} + +func TestStyled_ExtendedColorsKeepTheirForm(t *testing.T) { + e := feed("\x1b[38;5;208ma\x1b[38;2;143;179;220mb\x1b[48;5;57mc\x1b[0m") + assert.Equal(t, "{fg=@208}a{fg=#8fb3dc}b{fg=#8fb3dc bg=@57}c{/}", e.styledString()) +} + +func TestStyled_ColonSeparatedExtendedColor(t *testing.T) { + e := feed("\x1b[38:5:10mx\x1b[m") + assert.Equal(t, "{fg=@10}x{/}", e.styledString()) +} + +func TestStyled_AttributesInFixedOrder(t *testing.T) { + e := feed("\x1b[7;4;3;2;1;32mx\x1b[m") + assert.Equal(t, "{fg=2 bold faint italic underline reverse}x{/}", e.styledString()) +} + +func TestStyled_AttributeResets(t *testing.T) { + e := feed("\x1b[1;3;4;7;31;42ma\x1b[22;23;24;27;39;49mb") + assert.Equal(t, "{fg=1 bg=2 bold italic underline reverse}a{/}b", e.styledString()) +} + +func TestStyled_BlinkStrikeDoubleUnderlineOverline(t *testing.T) { + e := feed("\x1b[5;9;21;53mx\x1b[0my") + assert.Equal(t, "{double-underline blink strikethrough overline}x{/}y", e.styledString()) +} + +func TestStyled_BlinkStrikeDoubleUnderlineOverlineResets(t *testing.T) { + e := feed("\x1b[5;9;21;53ma\x1b[25mb\x1b[29mc\x1b[24md\x1b[55me") + assert.Equal(t, "{double-underline blink strikethrough overline}a"+ + "{double-underline strikethrough overline}b"+ + "{double-underline overline}c"+ + "{overline}d{/}e", e.styledString()) +} + +func TestStyled_UnderlineStylesFromColonSubparameter(t *testing.T) { + e := feed("\x1b[4:1ma\x1b[4:2mb\x1b[4:3mc\x1b[4:4md\x1b[4:5me\x1b[4:0mf") + assert.Equal(t, "{underline}a{double-underline}b{curly-underline}c{dotted-underline}d{dashed-underline}e{/}f", e.styledString()) +} + +func TestStyled_ColonUnderlineDoesNotSwallowNextParameter(t *testing.T) { + e := feed("\x1b[4:3;1mx\x1b[0m") + assert.Equal(t, "{bold curly-underline}x{/}", e.styledString()) +} + +func TestStyled_ColonTrueColorWithAndWithoutColorSpace(t *testing.T) { + e := feed("\x1b[38:2::143:179:220mx\x1b[38:2:143:179:220my\x1b[48:2::1:2:3mz\x1b[48:5:57mw\x1b[0m") + assert.Equal(t, "{fg=#8fb3dc}xy{fg=#8fb3dc bg=#010203}z{fg=#8fb3dc bg=@57}w{/}", e.styledString()) +} + +func TestStyled_InvalidExtendedColorConsumesNothing(t *testing.T) { + // 38 with an unknown sub-mode is ignored, so 9 and 1 apply as plain codes. + e := feed("\x1b[31;38;9;1mx\x1b[0m") + assert.Equal(t, "{fg=1 bold strikethrough}x{/}", e.styledString()) +} + +func TestStyled_InvalidColonColorKeepsPen(t *testing.T) { + e := feed("\x1b[31m\x1b[38:9:1mx\x1b[0m") + assert.Equal(t, "{fg=1}x{/}", e.styledString()) +} + +func TestStyled_UnderlineColorIsSkipped(t *testing.T) { + // 58 is not modelled, but both its colon and semicolon forms must consume + // their values so the attributes after them still apply. + e := feed("\x1b[58:2::1:2:3;4mx\x1b[58;5;1;1mw\x1b[0m") + assert.Equal(t, "{underline}x{bold underline}w{/}", e.styledString()) +} + +func TestStyled_StyleChangeEmitsOneMarker(t *testing.T) { + e := feed("\x1b[1ma\x1b[32mb\x1b[0mc") + assert.Equal(t, "{bold}a{fg=2 bold}b{/}c", e.styledString()) +} + +func TestStyled_SpacesStayInsideSpan(t *testing.T) { + e := feed("\x1b[1ma b\x1b[0m") + assert.Equal(t, "{bold}a b{/}", e.styledString()) +} + +func TestStyled_SpanClosesAtLineEndAndReopens(t *testing.T) { + e := feed("\x1b[1mab\r\ncd\x1b[0m") + assert.Equal(t, "{bold}ab{/}\n{bold}cd{/}", e.styledString()) +} + +func TestStyled_TrailingStyledBlanksAreKept(t *testing.T) { + e := feed("a\x1b[44m \x1b[0m ") + assert.Equal(t, "a{bg=4} {/}", e.styledString()) +} + +func TestStyled_LiteralBraceIsEscaped(t *testing.T) { + e := feed("{x} \x1b[1m{\x1b[0m") + assert.Equal(t, "{{x} {bold}{{{/}", e.styledString()) +} + +func TestStyled_EraseResetsCellStyle(t *testing.T) { + e := feed("\x1b[31mred\x1b[0m\r\x1b[K") + assert.Empty(t, e.styledString()) +} + +func TestStyled_OverwriteTakesNewStyle(t *testing.T) { + e := feed("\x1b[31mab\x1b[0m\rX") + assert.Equal(t, "X{fg=1}b{/}", e.styledString()) +} + +func TestModes_PrivateModesAndActiveAtEnd(t *testing.T) { + e := feed("\x1b[?25l\x1b[?2004h\x1b[?2004l\x1b[?1049h") + assert.Equal(t, "-- changes --\n"+ + "?25 reset\n"+ + "?2004 set\n"+ + "?2004 reset\n"+ + "?1049 set\n"+ + "-- active at end --\n"+ + "?25 reset\n"+ + "?1049 set\n", e.modesString()) +} + +func TestModes_CursorShownAgainIsNotActive(t *testing.T) { + e := feed("\x1b[?25l\x1b[?25h") + assert.Equal(t, "-- changes --\n?25 reset\n?25 set\n-- active at end --\n", e.modesString()) +} + +func TestModes_RepeatsAreKept(t *testing.T) { + e := feed("\x1b[?25l\x1b[?25l\x1b[?25l") + assert.Equal(t, "-- changes --\n?25 reset\n?25 reset\n?25 reset\n-- active at end --\n?25 reset\n", e.modesString()) +} + +func TestModes_KittyKeyboardAndModifyOtherKeys(t *testing.T) { + e := feed("\x1b[>4;2m\x1b[>1u\x1b[=3;1u\x1b[?5W") + assert.Equal(t, "-- changes --\n"+ + "modifyOtherKeys 2\n"+ + "kitty-keyboard push 1\n"+ + "kitty-keyboard set 3\n"+ + "DECST8C\n"+ + "-- active at end --\n"+ + "kitty-keyboard stack [1]\n"+ + "modifyOtherKeys 2\n", e.modesString()) +} + +func TestModes_KittyPopAndModifyOtherKeysReset(t *testing.T) { + e := feed("\x1b[>1u\x1b[>4;2m\x1b[<1u\x1b[>4m") + assert.Equal(t, "-- changes --\n"+ + "kitty-keyboard push 1\n"+ + "modifyOtherKeys 2\n"+ + "kitty-keyboard pop 1\n"+ + "modifyOtherKeys 0\n"+ + "-- active at end --\n", e.modesString()) +} + +func TestModes_PrefixedUDoesNotRestoreCursor(t *testing.T) { + // "CSI > 1 u" is a kitty keyboard push, not SCO restore-cursor. + e := feed("\x1b[sab\x1b[>1ucd") + assert.Equal(t, "abcd", line(e, 0)) + pos(t, e, 0, 4) +} + +func TestQueries_Logged(t *testing.T) { + e := feed("\x1b[?2026$p\x1b[?2027$p\x1b[?u\x1b]11;?\x1b\\\x1b[6n\x1b[c\x1b[>c\x1b[>q") + assert.Equal(t, "DECRQM ?2026\n"+ + "DECRQM ?2027\n"+ + "kitty-keyboard-flags\n"+ + "OSC 11\n"+ + "CPR\n"+ + "DA1\n"+ + "DA2\n"+ + "XTVERSION\n", e.queriesString()) +} + +func TestQueries_QueriesDoNotChangeText(t *testing.T) { + e := feed("a\x1b[?2026$p\x1b]11;?\x07b") + assert.Equal(t, "ab", line(e, 0)) +} + +func TestDefaultReply(t *testing.T) { + assert.Equal(t, "\x1b[?2026;2$y", DefaultReply("DECRQM ?2026")) + assert.Equal(t, "\x1b[?0u", DefaultReply("kitty-keyboard-flags")) + assert.Equal(t, "\x1b]11;rgb:0000/0000/0000\x1b\\", DefaultReply("OSC 11")) + assert.Equal(t, "\x1b[1;1R", DefaultReply("CPR")) + assert.Empty(t, DefaultReply("XTVERSION")) +} diff --git a/libs/cmdio/cmdiotest/termtest/screen_rows_test.go b/libs/cmdio/cmdiotest/termtest/screen_rows_test.go new file mode 100644 index 00000000000..278fd93dcb9 --- /dev/null +++ b/libs/cmdio/cmdiotest/termtest/screen_rows_test.go @@ -0,0 +1,20 @@ +package termtest + +import ( + "testing" + + "github.com/databricks/cli/libs/cmdio" + "github.com/stretchr/testify/assert" +) + +func TestScreenRows_NonPositiveUsesDefault(t *testing.T) { + assert.Equal(t, cmdio.TestTerminalHeight, screenRows(0)) + assert.Equal(t, cmdio.TestTerminalHeight, screenRows(-1)) + assert.Equal(t, 200, screenRows(200)) +} + +func TestScreenRows_NegativeDoesNotPanic(t *testing.T) { + assert.NotPanics(t, func() { + _ = newEmulator(cmdio.TestTerminalWidth, screenRows(-5)) + }) +} diff --git a/libs/cmdio/cmdiotest/termtest/termtest.go b/libs/cmdio/cmdiotest/termtest/termtest.go index 034ac35a0f8..4940bfc6640 100644 --- a/libs/cmdio/cmdiotest/termtest/termtest.go +++ b/libs/cmdio/cmdiotest/termtest/termtest.go @@ -1,6 +1,7 @@ // Package termtest drives cmdio's interactive prompts as a black box: it -// wires a [cmdio.NewTestIO] up to a pair of pipes, calls the public entry -// points ([cmdio.RunPrompt], [cmdio.Secret], [cmdio.SelectOrdered], …) in a +// wires a [cmdio.NewTestIOWithOptions] up to an OS pipe for input and +// in-memory buffers for output, calls the public entry points +// ([cmdio.RunPrompt], [cmdio.Secret], [cmdio.SelectOrdered], …) in a // goroutine, and exposes the rendered screen via an in-process VT emulator. // // Tests neither construct the underlying tea.Model nor reach into cmdio's @@ -22,8 +23,9 @@ // Golden(step) compares the rendered screen against // testdata//.golden. The screen comes from the emulator — // what the user would see — not the raw escape-sequence stream, so the -// goldens are stable across rendering changes as long as the visible UI -// matches. To create or refresh goldens, pass -update to `go test` +// goldens are stable across changes to escape sequences as long as the +// visible UI matches. The styled, modes and queries goldens record those +// sequences on purpose. To create or refresh goldens, pass -update to `go test` // (the flag is registered by [testdiff.OverwriteMode]). package termtest @@ -40,6 +42,7 @@ import ( "unicode/utf8" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/testdiff" "github.com/stretchr/testify/require" ) @@ -72,8 +75,24 @@ const ( KeyCtrlP = "\x10" KeyCtrlU = "\x15" KeyCtrlW = "\x17" + + // Modified keys in the encodings terminals send for them. Legacy + // terminals prefix Alt combinations with Esc; terminals with the kitty + // keyboard protocol or xterm's modifyOtherKeys enabled send CSI forms. + KeyAltEnter = "\x1b\r" + KeyAltLeft = "\x1b[1;3D" + KeyAltF = "\x1bf" + KeyShiftEnterKitty = "\x1b[13;2u" + KeyShiftEnterModifyOtherKey = "\x1b[27;2;13~" + KeyEscKitty = "\x1b[27u" ) +// Paste wraps text in bracketed-paste markers, the way a terminal delivers a +// paste when the program has enabled bracketed paste mode. +func Paste(text string) string { + return "\x1b[200~" + text + "\x1b[201~" +} + const ( // defaultTimeout bounds how long any single wait (Golden, // WaitFor, Close, Result) blocks before declaring failure. Generous @@ -93,12 +112,18 @@ const ( // follow-up Type can land in the same bubbletea Read and the buffer // "\x1ba" gets parsed as Alt+a (bubbletea key.go: any "\x1b" with a // trailing byte is an Alt-modifier; only a buffer of exactly "\x1b" - // becomes KeyEscape). Other Key* constants are either single non-Esc - // bytes or complete "\x1b[..." CSI sequences whose terminator commits - // the parse before any follow-up byte matters, so they don't need this. + // becomes KeyEscape). KeyAltEnter and KeyAltF are Esc-prefixed too, but + // they are written in one Type call, so the Esc is never alone in a read. + // Other Key* constants are single non-Esc bytes or complete "\x1b[..." + // CSI sequences, whose terminator commits the parse before any follow-up + // byte matters. // 20 ms matches the ESC-disambiguation timeouts neovim and tmux use // for the same problem. escDisambiguationDelay = 20 * time.Millisecond + + // settleQuiet is how long [Term.Settle] waits for output to stop. A + // keystroke's redraw lands well within it. + settleQuiet = 50 * time.Millisecond ) // resultMsg carries the (value, err) the goroutine running the cmdio entry @@ -115,7 +140,8 @@ type resultMsg[T any] struct { // input goroutine); cmdio's stderr (where the TUI renders) is a // synchronized buffer we drain into the VT emulator on demand. type Term[T any] struct { - t *testing.T + t *testing.T + opts Options inW *os.File inR *os.File @@ -128,6 +154,120 @@ type Term[T any] struct { term *emulator raw bytes.Buffer pending []byte + + // Query responder state; see [Responder]. + answered int + replies sync.WaitGroup + replyMu sync.Mutex + lastReply chan struct{} + inWMu sync.Mutex + + // leftover holds the input bytes the program left unread on exit, when + // [Options.CaptureLeftover] is set. + leftover []byte + leftoverErr error +} + +// Options adjusts [RunWith]. The zero value gives the same harness as [Run]. +type Options struct { + // Env sets environment variables in the command's context (see + // libs/env). An empty value reads as unset to cmdio's color checks. + Env map[string]string + + // ColorFromEnv derives cmdio's color capability from NO_COLOR and TERM + // in Env, the way a real command does, instead of forcing it on. + ColorFromEnv bool + + // StdoutNotTTY and StderrNotTTY make cmdio treat the stream as + // redirected. + StdoutNotTTY bool + StderrNotTTY bool + + // CaptureStdout feeds cmdio's stdout into the emulator as well, for + // programs that render there through cmdio (the pager). Both streams then + // share one screen, as on a real terminal. Streams gives a program that + // takes its streams as arguments (tableview) the emulator directly. + CaptureStdout bool + + // HeaderTemplate and Template are the command's text templates; + // [cmdio.RenderIterator] only pages when Template is set. + HeaderTemplate string + Template string + + // Responder, when non-nil, answers terminal queries the program writes. + Responder *Responder + + // CaptureLeftover reads the input bytes still unread after the program + // returns; see [Term.Leftover]. Unsupported on Windows. + CaptureLeftover bool + + // MapNewline makes the emulator treat LF as CR LF, the way a terminal in + // cooked mode shows plain lines written to it (cmdio.LogString output). + MapNewline bool + + // ScreenRows, when positive, replaces the emulator's height of + // [cmdio.TestTerminalHeight] rows. The emulator does not scroll, so + // programs that print more lines than that (the pager draining several + // pages) need a taller screen to keep every line. The window size the + // program is told about is unchanged. + ScreenRows int + + // Normalize, when non-nil, rewrites every screen snapshot (Snapshot and + // SnapshotStyled, and the goldens made from them) before it is compared or + // written, e.g. to blank out a spinner frame that changes over time. The + // modes and queries logs are not rewritten. + Normalize func(string) string +} + +// Responder answers the terminal queries a program writes (see +// [Term.SnapshotQueries] for their names) by writing replies to its input, +// after Delay. A real terminal answers within milliseconds locally and much +// later over a slow link; a long Delay models the latter. +type Responder struct { + Delay time.Duration + + // Replies overrides the reply for a query name. Queries without an + // entry get [DefaultReply]. + Replies map[string]string +} + +// DefaultReply returns the reply a typical xterm-compatible terminal sends +// for a query name, or "" for an unknown one: DECRQM modes are reported as +// "reset", the kitty keyboard flags as 0, the foreground as white, the +// background as black and the cursor position as the top-left corner. +func DefaultReply(query string) string { + if mode, ok := strings.CutPrefix(query, "DECRQM ?"); ok { + return "\x1b[?" + mode + ";2$y" + } + switch query { + case "kitty-keyboard-flags": + return "\x1b[?0u" + // OSC 10 and OSC 11 are the foreground and background color queries. + case "OSC 10": + return "\x1b]10;rgb:ffff/ffff/ffff\x1b\\" + case "OSC 11": + return "\x1b]11;rgb:0000/0000/0000\x1b\\" + case "CPR": + return "\x1b[1;1R" + case "DA1": + return "\x1b[?62;22c" + } + return "" +} + +type streamsKey struct{} + +type streams struct { + in io.Reader + out io.Writer +} + +// Streams returns the input and output the harness wired into ctx, for +// programs that take their streams as arguments instead of reading them from +// cmdio (e.g. libs/tableview). Output goes to the emulator. +func Streams(ctx context.Context) (io.Reader, io.Writer) { + s := ctx.Value(streamsKey{}).(streams) + return s.in, s.out } // NewPrompt runs [cmdio.RunPrompt] in a goroutine and returns a harness for @@ -167,21 +307,53 @@ func NewSelectOrdered(t *testing.T, items []cmdio.Tuple, label string) *Term[str // Run drives an interactive command through the same terminal harness as the prompts. func Run[T any](t *testing.T, fn func(ctx context.Context) (T, error)) *Term[T] { + t.Helper() + return RunWith(t, Options{}, fn) +} + +// RunWith is [Run] with the adjustments in opts. +func RunWith[T any](t *testing.T, opts Options, fn func(ctx context.Context) (T, error)) *Term[T] { t.Helper() inR, inW, err := os.Pipe() require.NoError(t, err, "open input pipe") tt := &Term[T]{ t: t, + opts: opts, inW: inW, inR: inR, done: make(chan resultMsg[T], 1), finished: make(chan struct{}), - term: newEmulator(cmdio.TestTerminalWidth, cmdio.TestTerminalHeight), + term: newEmulator(cmdio.TestTerminalWidth, screenRows(opts.ScreenRows)), + } + tt.term.mapNewline = opts.MapNewline + ctx := t.Context() + for k, v := range opts.Env { + ctx = env.Set(ctx, k, v) //nolint:fatcontext // one value per variable, set once before the run + } + screen := &syncWriter{mu: &tt.mu, buf: &tt.out} + var stdout io.Writer + if opts.CaptureStdout { + stdout = screen + } else { + stdout = io.Discard + } + cio := cmdio.NewTestIOWithOptions(ctx, inR, stdout, screen, cmdio.TestIOOptions{ + HeaderTemplate: opts.HeaderTemplate, + Template: opts.Template, + ColorFromEnv: opts.ColorFromEnv, + StdoutNotTTY: opts.StdoutNotTTY, + StderrNotTTY: opts.StderrNotTTY, + }) + ctx = cmdio.InContext(ctx, cio) + ctx = context.WithValue(ctx, streamsKey{}, streams{in: inR, out: screen}) + if opts.Responder != nil { + go tt.respondLoop() } - io := cmdio.NewTestIO(inR, io.Discard, &syncWriter{mu: &tt.mu, buf: &tt.out}) - ctx := cmdio.InContext(t.Context(), io) go func() { v, err := fn(ctx) + if opts.CaptureLeftover { + tt.captureLeftover() + } tt.done <- resultMsg[T]{value: v, err: err} // Deliver the result before closing inR: on Windows bubbletea cannot // cancel a read on a pipe, so its read loop can stay blocked in @@ -194,6 +366,15 @@ func Run[T any](t *testing.T, fn func(ctx context.Context) (T, error)) *Term[T] return tt } +// screenRows returns the emulator height for ScreenRows: the default unless +// the value is positive, so a negative value cannot size a grid. +func screenRows(n int) int { + if n > 0 { + return n + } + return cmdio.TestTerminalHeight +} + // syncWriter is the io.Writer cmdio gives bubbletea as stderr. Writes from // the program goroutine race with our drain calls, so the buffer is mutex- // guarded. @@ -208,6 +389,34 @@ func (w *syncWriter) Write(p []byte) (int, error) { return w.buf.Write(p) } +// TypeBurst writes keys into the program's stdin in a single write, the way +// input arrives when the user types faster than the program reads (over a +// slow link, from an IME commit, or from an unbracketed paste). +func (tt *Term[T]) TypeBurst(keys ...string) { + tt.t.Helper() + tt.write(strings.Join(keys, "")) +} + +func (tt *Term[T]) write(s string) { + tt.t.Helper() + tt.inWMu.Lock() + defer tt.inWMu.Unlock() + _, err := tt.inW.Write([]byte(s)) + if err == nil { + return + } + // A write fails once the program has returned and its end of the pipe is + // closed. The keys are lost, as on a real terminal, and the goldens that + // follow show the early exit. The pipe is closed just before finished, + // so wait for it. + select { + case <-tt.finished: + return + case <-time.After(defaultTimeout): + } + require.NoError(tt.t, err, "write to stdin pipe") +} + // Type writes a string into the program's stdin. The string can be ordinary // text or one of the Key* constants — they're all just bytes the user would // have typed on a real terminal. After a lone Esc the call sleeps for @@ -215,13 +424,107 @@ func (w *syncWriter) Write(p []byte) (int, error) { // Read; see the constant's comment for why that matters. func (tt *Term[T]) Type(s string) { tt.t.Helper() - _, err := tt.inW.Write([]byte(s)) - require.NoError(tt.t, err, "write to stdin pipe") + tt.write(s) if s == KeyEsc { time.Sleep(escDisambiguationDelay) } } +// Settle waits until the program has written nothing for settleQuiet, or has +// returned. Call it between writes whose meaning changes when the program +// reads them together, e.g. "/" and the search text after it, which a single +// read would deliver as one "/it" key. +func (tt *Term[T]) Settle() { + tt.t.Helper() + deadline := time.Now().Add(defaultTimeout) + last, quietSince := len(tt.Raw()), time.Now() + for time.Since(quietSince) < settleQuiet { + select { + case <-tt.finished: + return + case <-time.After(pollInterval): + } + if n := len(tt.Raw()); n != last { + last, quietSince = n, time.Now() + } + if time.Now().After(deadline) { + tt.t.Fatalf("Settle: program still writing or reading input after %s", defaultTimeout) + } + } +} + +// WaitForExit waits up to grace for the program to return and reports whether +// it did. It never fails, so it can wait on a key that a program may ignore. +func (tt *Term[T]) WaitForExit(grace time.Duration) bool { + select { + case <-tt.finished: + return true + case <-time.After(grace): + return false + } +} + +// WaitForReplies blocks until every query the program has written so far has +// been answered and the replies have been read. Call it before typing when +// the test must not interleave keys with replies. It needs Options.Responder. +func (tt *Term[T]) WaitForReplies() { + tt.t.Helper() + tt.drainPending() + tt.scheduleReplies() + tt.replyMu.Lock() + last := tt.lastReply + tt.replyMu.Unlock() + if last != nil { + select { + case <-last: + case <-time.After(defaultTimeout): + tt.t.Fatalf("WaitForReplies: replies not written within %s", defaultTimeout) + } + } +} + +// WaitForScreen blocks until substr is visible on the rendered screen, or +// the default timeout elapses. Unlike [Term.WaitFor], which matches anything +// ever written, it only matches what is on screen now, e.g. a spinner that +// replaced a prompt. +func (tt *Term[T]) WaitForScreen(substr string) { + tt.t.Helper() + deadline := time.Now().Add(defaultTimeout) + for { + got := tt.Snapshot() + if strings.Contains(got, substr) { + return + } + if time.Now().After(deadline) { + tt.t.Fatalf("WaitForScreen(%q) timed out after %s\n--- current screen ---\n%s", substr, defaultTimeout, got) + } + time.Sleep(pollInterval) + } +} + +// WaitForOrExit is [Term.WaitFor] for programs that may return before +// rendering anything, e.g. a prompt that is not supported in the current +// environment. It reports whether substr appeared; false means the program +// returned first. +func (tt *Term[T]) WaitForOrExit(substr string) bool { + tt.t.Helper() + deadline := time.Now().Add(defaultTimeout) + for { + if strings.Contains(tt.Raw(), substr) { + return true + } + select { + case <-tt.finished: + return strings.Contains(tt.Raw(), substr) + default: + } + if time.Now().After(deadline) { + tt.t.Fatalf("WaitForOrExit(%q) timed out after %s\n--- captured raw output ---\n%s", substr, defaultTimeout, tt.Raw()) + } + time.Sleep(pollInterval) + } +} + // WaitFor blocks until substr appears in the raw output stream, or the // default timeout elapses. Returns the captured output for use in failure // messages. @@ -253,7 +556,51 @@ func (tt *Term[T]) Snapshot() string { for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } - return strings.Join(lines, "\n") + return tt.normalize(strings.Join(lines, "\n")) +} + +// SnapshotStyled returns the screen like [Term.Snapshot], with the cell +// styles as inline markers: `{fg=4 bold}text{/}`. `{attrs}` opens a styled +// span and `{/}` returns to the default style; a change between two styles +// emits just the new opening marker. Spans never cross a newline, and a +// literal `{` is written as `{{`. Attributes come in a fixed order (fg, bg, +// bold, faint, italic, underline, blink, reverse, strikethrough, overline), +// and colors keep the form the program sent: `4` (16-color index, bright +// colors as 8-15), `@208` (256-color) or `#8fb3dc` (truecolor). A screen +// without styles renders the same as Snapshot. +func (tt *Term[T]) SnapshotStyled() string { + tt.drainPending() + tt.mu.Lock() + defer tt.mu.Unlock() + return tt.normalize(tt.term.styledString()) +} + +// SnapshotModes returns the terminal mode changes the program has written so +// far (DEC private modes, kitty keyboard protocol pushes and pops, +// modifyOtherKeys, tab-stop resets), followed by the modes still active +// relative to a terminal's default state. +func (tt *Term[T]) SnapshotModes() string { + tt.drainPending() + tt.mu.Lock() + defer tt.mu.Unlock() + return strings.TrimSuffix(tt.term.modesString(), "\n") +} + +// SnapshotQueries returns the terminal queries the program has written, one +// per line: "DECRQM ?", "kitty-keyboard-flags", "OSC " (e.g. OSC 11, +// the background color), "CPR" (cursor position), "DA1", "DA2", "XTVERSION". +func (tt *Term[T]) SnapshotQueries() string { + tt.drainPending() + tt.mu.Lock() + defer tt.mu.Unlock() + return strings.TrimSuffix(tt.term.queriesString(), "\n") +} + +func (tt *Term[T]) normalize(s string) string { + if tt.opts.Normalize == nil { + return s + } + return tt.opts.Normalize(s) } // Raw returns the raw byte stream captured from the program, including all @@ -265,6 +612,17 @@ func (tt *Term[T]) Raw() string { return tt.raw.String() } +// LogRawOnFailure logs the raw output stream when the test fails, so a flake +// shows the exact escape sequences that produced the screen. The log is only +// printed on failure. +func (tt *Term[T]) LogRawOnFailure() { + tt.t.Cleanup(func() { + if tt.t.Failed() { + tt.t.Logf("raw output:\n%q", tt.Raw()) + } + }) +} + // Golden waits for the rendered screen to match // testdata//.golden, then asserts they're equal. With // the testdiff -update flag set ([testdiff.OverwriteMode]) the golden @@ -272,13 +630,39 @@ func (tt *Term[T]) Raw() string { // used verbatim as filenames; prefer "01-", "02-", … to keep listings // in checkpoint order. func (tt *Term[T]) Golden(step string) { + tt.t.Helper() + tt.golden(step+".golden", tt.Snapshot) +} + +// GoldenStyled is [Term.Golden] for [Term.SnapshotStyled], stored as +// .styled.golden. +func (tt *Term[T]) GoldenStyled(step string) { + tt.t.Helper() + tt.golden(step+".styled.golden", tt.SnapshotStyled) +} + +// GoldenModes is [Term.Golden] for [Term.SnapshotModes], stored as +// .modes.golden. +func (tt *Term[T]) GoldenModes(step string) { + tt.t.Helper() + tt.golden(step+".modes.golden", tt.SnapshotModes) +} + +// GoldenQueries is [Term.Golden] for [Term.SnapshotQueries], stored as +// .queries.golden. +func (tt *Term[T]) GoldenQueries(step string) { + tt.t.Helper() + tt.golden(step+".queries.golden", tt.SnapshotQueries) +} + +func (tt *Term[T]) golden(file string, snapshot func() string) { tt.t.Helper() safeName := strings.ReplaceAll(tt.t.Name(), "/", "_") - path := filepath.Join("testdata", safeName, step+".golden") + path := filepath.Join("testdata", safeName, file) if testdiff.OverwriteMode { time.Sleep(updateSettleWait) - got := tt.Snapshot() + "\n" + got := snapshot() + "\n" require.NoError(tt.t, os.MkdirAll(filepath.Dir(path), 0o755)) require.NoError(tt.t, os.WriteFile(path, []byte(got), 0o644)) return @@ -286,22 +670,44 @@ func (tt *Term[T]) Golden(step string) { wantBytes, err := os.ReadFile(path) if err != nil { - tt.t.Fatalf("read golden %s: %v\nrun with -update to create it\n--- current screen ---\n%s", path, err, tt.Snapshot()) + tt.t.Fatalf("read golden %s: %v\nrun with -update to create it\n--- current screen ---\n%s", path, err, snapshot()) } want := string(wantBytes) - got := tt.waitForMatch(want) + "\n" + got := tt.waitForMatch(want, snapshot) + "\n" testdiff.AssertEqualTexts(tt.t, path, "actual", want, got) } -// waitForMatch polls the rendered screen until it (with a trailing -// newline appended, matching how goldens are stored on disk) equals -// want, then returns. If defaultTimeout elapses without a match, returns the -// last snapshot seen so the caller can produce a diff against it. -func (tt *Term[T]) waitForMatch(want string) string { +// GoldenText compares text against testdata//.golden, or +// writes it there with -update. Use it to pin values that are not a screen, +// such as a prompt's result or the input left unread. +func GoldenText(t *testing.T, step, text string) { + t.Helper() + safeName := strings.ReplaceAll(t.Name(), "/", "_") + path := filepath.Join("testdata", safeName, step+".golden") + if !strings.HasSuffix(text, "\n") { + text += "\n" + } + if testdiff.OverwriteMode { + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(text), 0o644)) + return + } + want, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read golden %s: %v\nrun with -update to create it\n--- actual ---\n%s", path, err, text) + } + testdiff.AssertEqualTexts(t, path, "actual", string(want), text) +} + +// waitForMatch polls snapshot until it (with a trailing newline appended, +// matching how goldens are stored on disk) equals want, then returns. If +// defaultTimeout elapses without a match, returns the last snapshot seen so +// the caller can produce a diff against it. +func (tt *Term[T]) waitForMatch(want string, snapshot func() string) string { tt.t.Helper() deadline := time.Now().Add(defaultTimeout) for { - got := tt.Snapshot() + got := snapshot() if got+"\n" == want { return got } @@ -312,6 +718,90 @@ func (tt *Term[T]) waitForMatch(want string) string { } } +// Leftover returns the input bytes the program left unread when it +// returned, i.e. what a shell would read next. It requires +// [Options.CaptureLeftover] and waits for the program to finish. Replies +// the [Responder] still had scheduled are written before the read. +func (tt *Term[T]) Leftover() ([]byte, error) { + tt.t.Helper() + require.True(tt.t, tt.opts.CaptureLeftover, "Leftover requires Options.CaptureLeftover") + select { + case <-tt.finished: + case <-time.After(defaultTimeout): + tt.t.Fatalf("cmdio call did not finish in %s", defaultTimeout) + } + return tt.leftover, tt.leftoverErr +} + +// captureLeftover runs on the program goroutine after the program returns +// and before the input pipe is closed. +func (tt *Term[T]) captureLeftover() { + tt.drainPending() + tt.scheduleReplies() + tt.replies.Wait() + // Closing the write end makes ReadAll stop at the end of the buffered + // bytes instead of blocking on the still-open pipe. + tt.inWMu.Lock() + _ = tt.inW.Close() + tt.inWMu.Unlock() + tt.leftover, tt.leftoverErr = io.ReadAll(tt.inR) +} + +// respondLoop answers queries while the program runs. +func (tt *Term[T]) respondLoop() { + for { + select { + case <-tt.finished: + return + case <-time.After(pollInterval): + tt.drainPending() + tt.scheduleReplies() + } + } +} + +// scheduleReplies queues the replies to every query not yet answered. They +// are written after the responder's delay, in the order the queries were +// written, as a terminal answers them. +func (tt *Term[T]) scheduleReplies() { + r := tt.opts.Responder + if r == nil { + return + } + tt.replyMu.Lock() + defer tt.replyMu.Unlock() + tt.mu.Lock() + queries := tt.term.queries[tt.answered:] + tt.answered = len(tt.term.queries) + tt.mu.Unlock() + var batch strings.Builder + for _, q := range queries { + reply, ok := r.Replies[q] + if !ok { + reply = DefaultReply(q) + } + batch.WriteString(reply) + } + if batch.Len() == 0 { + return + } + // Each batch waits for the one before it, so replies never overtake + // each other even when their timers fire together. + prev, done := tt.lastReply, make(chan struct{}) + tt.lastReply = done + tt.replies.Add(1) + time.AfterFunc(r.Delay, func() { + defer tt.replies.Done() + defer close(done) + if prev != nil { + <-prev + } + tt.inWMu.Lock() + defer tt.inWMu.Unlock() + _, _ = tt.inW.Write([]byte(batch.String())) + }) +} + // Close releases the input pipe and waits for the goroutine running the // cmdio entry point to finish. Safe to call after Result has already drained // the return value, and safe to call repeatedly. diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_ci/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_ci/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_ci/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_clicolor-0/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_clicolor-0/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_clicolor-0/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_colorterm-yes/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_colorterm-yes/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_colorterm-yes/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_no-color/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_no-color/01-typed.styled.golden new file mode 100644 index 00000000000..cfff2255f0e --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_no-color/01-typed.styled.golden @@ -0,0 +1 @@ +{bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-dumb/01-not-shown.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-dumb/01-not-shown.golden new file mode 100644 index 00000000000..ae19a50450e --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-dumb/01-not-shown.golden @@ -0,0 +1 @@ +err: expected to have Workspace name diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-screen/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-screen/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-screen/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-unset/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-unset/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-unset/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-vt100/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-vt100/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-vt100/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-xterm-256color/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-xterm-256color/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_term-xterm-256color/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_tmux-truecolor/01-typed.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_tmux-truecolor/01-typed.styled.golden new file mode 100644 index 00000000000..11e3ea3fc56 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Prompt_tmux-truecolor/01-typed.styled.golden @@ -0,0 +1 @@ +{fg=2 bold}✔{/} {bold}Workspace name:{/} dev█ diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_ci/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_ci/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_ci/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_clicolor-0/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_clicolor-0/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_clicolor-0/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_colorterm-yes/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_colorterm-yes/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_colorterm-yes/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_no-color/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_no-color/01-initial.styled.golden new file mode 100644 index 00000000000..ad6441dde6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_no-color/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +? Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-dumb/01-not-shown.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-dumb/01-not-shown.golden new file mode 100644 index 00000000000..d09ab2a5f47 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-dumb/01-not-shown.golden @@ -0,0 +1 @@ +err: expected to have Pick an item diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-screen/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-screen/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-screen/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-unset/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-unset/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-unset/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-vt100/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-vt100/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-vt100/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-xterm-256color/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-xterm-256color/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_term-xterm-256color/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_tmux-truecolor/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_tmux-truecolor/01-initial.styled.golden new file mode 100644 index 00000000000..f8d2212a170 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Select_tmux-truecolor/01-initial.styled.golden @@ -0,0 +1,5 @@ +Search: █ +{fg=4}?{/} Pick an item: + {bold}alpha{/} ({faint}id-01{/}) + beta + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_ci/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_ci/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_ci/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_clicolor-0/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_clicolor-0/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_clicolor-0/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_colorterm-yes/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_colorterm-yes/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_colorterm-yes/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_no-color/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_no-color/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_no-color/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-dumb/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-dumb/01-running.styled.golden new file mode 100644 index 00000000000..34a2a3d3c2d --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-dumb/01-running.styled.golden @@ -0,0 +1 @@ +spinner started diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-screen/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-screen/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-screen/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-unset/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-unset/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-unset/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-vt100/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-vt100/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-vt100/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-xterm-256color/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-xterm-256color/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_term-xterm-256color/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_tmux-truecolor/01-running.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_tmux-truecolor/01-running.styled.golden new file mode 100644 index 00000000000..ed573c796c3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Spinner_tmux-truecolor/01-running.styled.golden @@ -0,0 +1,2 @@ +spinner started +* Working diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_ci/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_ci/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_ci/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_clicolor-0/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_clicolor-0/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_clicolor-0/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_colorterm-yes/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_colorterm-yes/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_colorterm-yes/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_no-color/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_no-color/01-swatch.styled.golden new file mode 100644 index 00000000000..94b6b2bd0ff --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_no-color/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: red green blue hiblack hiblue bold faint +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-dumb/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-dumb/01-swatch.styled.golden new file mode 100644 index 00000000000..94b6b2bd0ff --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-dumb/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: red green blue hiblack hiblue bold faint +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-screen/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-screen/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-screen/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-unset/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-unset/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-unset/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-vt100/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-vt100/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-vt100/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-xterm-256color/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-xterm-256color/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_term-xterm-256color/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_tmux-truecolor/01-swatch.styled.golden b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_tmux-truecolor/01-swatch.styled.golden new file mode 100644 index 00000000000..9bed9ae1f6f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestColorPin_Swatch_tmux-truecolor/01-swatch.styled.golden @@ -0,0 +1,3 @@ +renderer color: false +helpers: {fg=1}red{/} {fg=2}green{/} {fg=4}blue{/} {fg=8}hiblack{/} {fg=12}hiblue{/} {bold}bold{/} {faint}faint{/} +renderer: bold reverse diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltEnter/01-after-alt-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltEnter/01-after-alt-enter.golden new file mode 100644 index 00000000000..fb674f6cc35 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltEnter/01-after-alt-enter.golden @@ -0,0 +1 @@ +Value: ab diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltEnter/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltEnter/02-result.golden new file mode 100644 index 00000000000..679aaf570a0 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltEnter/02-result.golden @@ -0,0 +1,2 @@ +value: "ab" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltLeft/01-after-alt-left.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltLeft/01-after-alt-left.golden new file mode 100644 index 00000000000..c8782899a3c --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltLeft/01-after-alt-left.golden @@ -0,0 +1 @@ +✔ Value: abX█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltLeft/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltLeft/02-result.golden new file mode 100644 index 00000000000..73479308a89 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptAltLeft/02-result.golden @@ -0,0 +1,2 @@ +value: "abXc" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden new file mode 100644 index 00000000000..749db6320e6 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/01-after-paste.golden @@ -0,0 +1,2 @@ + +b█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/02-result.golden new file mode 100644 index 00000000000..52736f686ed --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBracketedPasteWithNewline/02-result.golden @@ -0,0 +1,2 @@ +value: "a\r\nb" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBurstKeyName/01-after-burst.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBurstKeyName/01-after-burst.golden new file mode 100644 index 00000000000..d2c1ef31891 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBurstKeyName/01-after-burst.golden @@ -0,0 +1 @@ +✔ Value: aenterb█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBurstKeyName/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBurstKeyName/02-result.golden new file mode 100644 index 00000000000..88a3fbbc666 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptBurstKeyName/02-result.golden @@ -0,0 +1,2 @@ +value: "aenterb" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptKittyEsc/01-after-kitty-esc.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptKittyEsc/01-after-kitty-esc.golden new file mode 100644 index 00000000000..b479798fc86 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptKittyEsc/01-after-kitty-esc.golden @@ -0,0 +1 @@ +✔ Value: ab█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptKittyEsc/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptKittyEsc/02-result.golden new file mode 100644 index 00000000000..679aaf570a0 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptKittyEsc/02-result.golden @@ -0,0 +1,2 @@ +value: "ab" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden new file mode 100644 index 00000000000..e9385f6a7fa --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/01-after-shift-enter.golden @@ -0,0 +1 @@ +✔ Value: xyz█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden new file mode 100644 index 00000000000..1b113f0f236 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_kitty/02-result.golden @@ -0,0 +1,2 @@ +value: "xyz" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden new file mode 100644 index 00000000000..e9385f6a7fa --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/01-after-shift-enter.golden @@ -0,0 +1 @@ +✔ Value: xyz█ diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden new file mode 100644 index 00000000000..1b113f0f236 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_PromptShiftEnter_modifyOtherKeys/02-result.golden @@ -0,0 +1,2 @@ +value: "xyz" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectAltEnter/01-after-alt-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectAltEnter/01-after-alt-enter.golden new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectAltEnter/01-after-alt-enter.golden @@ -0,0 +1 @@ + diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectAltEnter/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectAltEnter/02-result.golden new file mode 100644 index 00000000000..7e767ba474f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectAltEnter/02-result.golden @@ -0,0 +1,2 @@ +id: "id-02" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectFilterBurstKeyName/01-after-burst.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectFilterBurstKeyName/01-after-burst.golden new file mode 100644 index 00000000000..40ed623139d --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectFilterBurstKeyName/01-after-burst.golden @@ -0,0 +1,3 @@ +Search: edown█ +? Pick one: + edown (id-01) diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectFilterBurstKeyName/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectFilterBurstKeyName/02-result.golden new file mode 100644 index 00000000000..6549bf0c3ae --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectFilterBurstKeyName/02-result.golden @@ -0,0 +1,2 @@ +id: "id-01" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden new file mode 100644 index 00000000000..b5462b0e045 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/01-after-shift-enter.golden @@ -0,0 +1,5 @@ +Search: █ +? Pick one: + alpha + beta (id-02) + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/02-result.golden new file mode 100644 index 00000000000..7e767ba474f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_kitty/02-result.golden @@ -0,0 +1,2 @@ +id: "id-02" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden new file mode 100644 index 00000000000..b5462b0e045 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/01-after-shift-enter.golden @@ -0,0 +1,5 @@ +Search: █ +? Pick one: + alpha + beta (id-02) + gamma diff --git a/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/02-result.golden new file mode 100644 index 00000000000..7e767ba474f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestKeysPin_SelectShiftEnter_modifyOtherKeys/02-result.golden @@ -0,0 +1,2 @@ +id: "id-02" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden new file mode 100644 index 00000000000..29572cb66d7 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_ctrl-c/01-modes.modes.golden @@ -0,0 +1,9 @@ +-- changes -- +?25 reset +?2004 set +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden new file mode 100644 index 00000000000..29572cb66d7 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Pager_enter-drains/01-modes.modes.golden @@ -0,0 +1,9 @@ +-- changes -- +?25 reset +?2004 set +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden new file mode 100644 index 00000000000..29572cb66d7 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_ctrl-c/01-modes.modes.golden @@ -0,0 +1,9 @@ +-- changes -- +?25 reset +?2004 set +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden new file mode 100644 index 00000000000..29572cb66d7 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Prompt_enter/01-modes.modes.golden @@ -0,0 +1,9 @@ +-- changes -- +?25 reset +?2004 set +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden new file mode 100644 index 00000000000..4fa7141e5dc --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_ctrl-c/01-modes.modes.golden @@ -0,0 +1,10 @@ +-- changes -- +?25 reset +?2004 set +?25 reset +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden new file mode 100644 index 00000000000..4fa7141e5dc --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Select_enter/01-modes.modes.golden @@ -0,0 +1,10 @@ +-- changes -- +?25 reset +?2004 set +?25 reset +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden b/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden new file mode 100644 index 00000000000..29572cb66d7 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestModesPin_Spinner/01-modes.modes.golden @@ -0,0 +1,9 @@ +-- changes -- +?25 reset +?2004 set +?2004 reset +?25 set +?1002 reset +?1003 reset +?1006 reset +-- active at end -- diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_EmptyResult/01-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EmptyResult/01-result.golden new file mode 100644 index 00000000000..d46f028b745 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EmptyResult/01-result.golden @@ -0,0 +1 @@ +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_EmptyResult/02-final.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EmptyResult/02-final.golden new file mode 100644 index 00000000000..06db3728ec4 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EmptyResult/02-final.golden @@ -0,0 +1 @@ +NAME STATE diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/01-first-page-loading.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/01-first-page-loading.golden new file mode 100644 index 00000000000..8ad588dbd4c --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/01-first-page-loading.golden @@ -0,0 +1 @@ +distinct spinner frames: at least 2 diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/02-result.golden new file mode 100644 index 00000000000..d46f028b745 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/02-result.golden @@ -0,0 +1 @@ +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/03-final.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/03-final.golden new file mode 100644 index 00000000000..a6135dbf2b0 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_EnterWhileFirstPageLoads/03-final.golden @@ -0,0 +1,121 @@ +NAME STATE +item-001 ready +item-002 ready +item-003 ready +item-004 ready +item-005 ready +item-006 ready +item-007 ready +item-008 ready +item-009 ready +item-010 ready +item-011 ready +item-012 ready +item-013 ready +item-014 ready +item-015 ready +item-016 ready +item-017 ready +item-018 ready +item-019 ready +item-020 ready +item-021 ready +item-022 ready +item-023 ready +item-024 ready +item-025 ready +item-026 ready +item-027 ready +item-028 ready +item-029 ready +item-030 ready +item-031 ready +item-032 ready +item-033 ready +item-034 ready +item-035 ready +item-036 ready +item-037 ready +item-038 ready +item-039 ready +item-040 ready +item-041 ready +item-042 ready +item-043 ready +item-044 ready +item-045 ready +item-046 ready +item-047 ready +item-048 ready +item-049 ready +item-050 ready +item-051 ready +item-052 ready +item-053 ready +item-054 ready +item-055 ready +item-056 ready +item-057 ready +item-058 ready +item-059 ready +item-060 ready +item-061 ready +item-062 ready +item-063 ready +item-064 ready +item-065 ready +item-066 ready +item-067 ready +item-068 ready +item-069 ready +item-070 ready +item-071 ready +item-072 ready +item-073 ready +item-074 ready +item-075 ready +item-076 ready +item-077 ready +item-078 ready +item-079 ready +item-080 ready +item-081 ready +item-082 ready +item-083 ready +item-084 ready +item-085 ready +item-086 ready +item-087 ready +item-088 ready +item-089 ready +item-090 ready +item-091 ready +item-092 ready +item-093 ready +item-094 ready +item-095 ready +item-096 ready +item-097 ready +item-098 ready +item-099 ready +item-100 ready +item-101 ready +item-102 ready +item-103 ready +item-104 ready +item-105 ready +item-106 ready +item-107 ready +item-108 ready +item-109 ready +item-110 ready +item-111 ready +item-112 ready +item-113 ready +item-114 ready +item-115 ready +item-116 ready +item-117 ready +item-118 ready +item-119 ready +item-120 ready diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnFirstPage/01-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnFirstPage/01-result.golden new file mode 100644 index 00000000000..3c7f061b1ec --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnFirstPage/01-result.golden @@ -0,0 +1 @@ +err: injected iterator error diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnFirstPage/02-final.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnFirstPage/02-final.golden new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnFirstPage/02-final.golden @@ -0,0 +1 @@ + diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnLaterPage/01-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnLaterPage/01-result.golden new file mode 100644 index 00000000000..3c7f061b1ec --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnLaterPage/01-result.golden @@ -0,0 +1 @@ +err: injected iterator error diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnLaterPage/02-final.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnLaterPage/02-final.golden new file mode 100644 index 00000000000..6f0ce3a5f9a --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_ErrorOnLaterPage/02-final.golden @@ -0,0 +1,51 @@ +NAME STATE +item-001 ready +item-002 ready +item-003 ready +item-004 ready +item-005 ready +item-006 ready +item-007 ready +item-008 ready +item-009 ready +item-010 ready +item-011 ready +item-012 ready +item-013 ready +item-014 ready +item-015 ready +item-016 ready +item-017 ready +item-018 ready +item-019 ready +item-020 ready +item-021 ready +item-022 ready +item-023 ready +item-024 ready +item-025 ready +item-026 ready +item-027 ready +item-028 ready +item-029 ready +item-030 ready +item-031 ready +item-032 ready +item-033 ready +item-034 ready +item-035 ready +item-036 ready +item-037 ready +item-038 ready +item-039 ready +item-040 ready +item-041 ready +item-042 ready +item-043 ready +item-044 ready +item-045 ready +item-046 ready +item-047 ready +item-048 ready +item-049 ready +item-050 ready diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_FitsOnePage/01-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_FitsOnePage/01-result.golden new file mode 100644 index 00000000000..d46f028b745 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_FitsOnePage/01-result.golden @@ -0,0 +1 @@ +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_FitsOnePage/02-final.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_FitsOnePage/02-final.golden new file mode 100644 index 00000000000..8e93d62b59f --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_FitsOnePage/02-final.golden @@ -0,0 +1,6 @@ +NAME STATE +item-001 ready +item-002 ready +item-003 ready +item-004 ready +item-005 ready diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpaceLoadsNextPage/01-second-page.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpaceLoadsNextPage/01-second-page.golden new file mode 100644 index 00000000000..9616c08c9d9 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpaceLoadsNextPage/01-second-page.golden @@ -0,0 +1,102 @@ +NAME STATE +item-001 ready +item-002 ready +item-003 ready +item-004 ready +item-005 ready +item-006 ready +item-007 ready +item-008 ready +item-009 ready +item-010 ready +item-011 ready +item-012 ready +item-013 ready +item-014 ready +item-015 ready +item-016 ready +item-017 ready +item-018 ready +item-019 ready +item-020 ready +item-021 ready +item-022 ready +item-023 ready +item-024 ready +item-025 ready +item-026 ready +item-027 ready +item-028 ready +item-029 ready +item-030 ready +item-031 ready +item-032 ready +item-033 ready +item-034 ready +item-035 ready +item-036 ready +item-037 ready +item-038 ready +item-039 ready +item-040 ready +item-041 ready +item-042 ready +item-043 ready +item-044 ready +item-045 ready +item-046 ready +item-047 ready +item-048 ready +item-049 ready +item-050 ready +item-051 ready +item-052 ready +item-053 ready +item-054 ready +item-055 ready +item-056 ready +item-057 ready +item-058 ready +item-059 ready +item-060 ready +item-061 ready +item-062 ready +item-063 ready +item-064 ready +item-065 ready +item-066 ready +item-067 ready +item-068 ready +item-069 ready +item-070 ready +item-071 ready +item-072 ready +item-073 ready +item-074 ready +item-075 ready +item-076 ready +item-077 ready +item-078 ready +item-079 ready +item-080 ready +item-081 ready +item-082 ready +item-083 ready +item-084 ready +item-085 ready +item-086 ready +item-087 ready +item-088 ready +item-089 ready +item-090 ready +item-091 ready +item-092 ready +item-093 ready +item-094 ready +item-095 ready +item-096 ready +item-097 ready +item-098 ready +item-099 ready +item-100 ready +[space] more [enter] all [q|esc] quit diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpaceLoadsNextPage/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpaceLoadsNextPage/02-result.golden new file mode 100644 index 00000000000..d46f028b745 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpaceLoadsNextPage/02-result.golden @@ -0,0 +1 @@ +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/01-first-page-loading.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/01-first-page-loading.golden new file mode 100644 index 00000000000..4fddb0f9969 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/01-first-page-loading.golden @@ -0,0 +1 @@ +distinct spinner frames: at least 3 diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/02-first-page.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/02-first-page.golden new file mode 100644 index 00000000000..ce332e19ff3 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/02-first-page.golden @@ -0,0 +1,52 @@ +NAME STATE +item-001 ready +item-002 ready +item-003 ready +item-004 ready +item-005 ready +item-006 ready +item-007 ready +item-008 ready +item-009 ready +item-010 ready +item-011 ready +item-012 ready +item-013 ready +item-014 ready +item-015 ready +item-016 ready +item-017 ready +item-018 ready +item-019 ready +item-020 ready +item-021 ready +item-022 ready +item-023 ready +item-024 ready +item-025 ready +item-026 ready +item-027 ready +item-028 ready +item-029 ready +item-030 ready +item-031 ready +item-032 ready +item-033 ready +item-034 ready +item-035 ready +item-036 ready +item-037 ready +item-038 ready +item-039 ready +item-040 ready +item-041 ready +item-042 ready +item-043 ready +item-044 ready +item-045 ready +item-046 ready +item-047 ready +item-048 ready +item-049 ready +item-050 ready +[space] more [enter] all [q|esc] quit diff --git a/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/03-result.golden b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/03-result.golden new file mode 100644 index 00000000000..d46f028b745 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestPagerPin_SpinnerDuringFirstPage/03-result.golden @@ -0,0 +1 @@ +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/01-result.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/01-result.golden new file mode 100644 index 00000000000..679aaf570a0 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/01-result.golden @@ -0,0 +1,2 @@ +value: "ab" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/02-queries.queries.golden @@ -0,0 +1 @@ + diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden new file mode 100644 index 00000000000..870cc2bdd10 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptQuitBeforeReplies/03-leftover.golden @@ -0,0 +1 @@ +(none) diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/01-typed.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/01-typed.golden new file mode 100644 index 00000000000..b479798fc86 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/01-typed.golden @@ -0,0 +1 @@ +✔ Value: ab█ diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/02-result.golden new file mode 100644 index 00000000000..679aaf570a0 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/02-result.golden @@ -0,0 +1,2 @@ +value: "ab" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/03-queries.queries.golden @@ -0,0 +1 @@ + diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/04-leftover.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/04-leftover.golden new file mode 100644 index 00000000000..870cc2bdd10 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptTerminalAnswersAtOnce/04-leftover.golden @@ -0,0 +1 @@ +(none) diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden new file mode 100644 index 00000000000..f3193c834b9 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/01-after-reply.golden @@ -0,0 +1 @@ +✔ Value: ab11;rgb:0000/0000/0000█ diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden new file mode 100644 index 00000000000..52037450272 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_PromptUnsolicitedBackgroundReply/02-result.golden @@ -0,0 +1,2 @@ +value: "ab11;rgb:0000/0000/0000" +err: diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/01-queries.queries.golden @@ -0,0 +1 @@ + diff --git a/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden new file mode 100644 index 00000000000..870cc2bdd10 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestQueriesPin_SelectQuitBeforeReplies/02-leftover.golden @@ -0,0 +1 @@ +(none) diff --git a/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_no-color-both-tty/01-stderr-bytes.golden b/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_no-color-both-tty/01-stderr-bytes.golden new file mode 100644 index 00000000000..33f150e17a6 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_no-color-both-tty/01-stderr-bytes.golden @@ -0,0 +1 @@ +"renderer color: false\nhelper: red\nrenderer: bold\n" diff --git a/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_stdout-redirected-stderr-tty/01-stderr-bytes.golden b/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_stdout-redirected-stderr-tty/01-stderr-bytes.golden new file mode 100644 index 00000000000..33f150e17a6 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_stdout-redirected-stderr-tty/01-stderr-bytes.golden @@ -0,0 +1 @@ +"renderer color: false\nhelper: red\nrenderer: bold\n" diff --git a/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_stdout-tty-stderr-redirected/01-stderr-bytes.golden b/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_stdout-tty-stderr-redirected/01-stderr-bytes.golden new file mode 100644 index 00000000000..b7e667488c9 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestStderrPin_LogStringStyles_stdout-tty-stderr-redirected/01-stderr-bytes.golden @@ -0,0 +1 @@ +"renderer color: false\nhelper: \x1b[31mred\x1b[0m\nrenderer: bold\n" diff --git a/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/01-initial.styled.golden b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/01-initial.styled.golden new file mode 100644 index 00000000000..ca8819b67fa --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/01-initial.styled.golden @@ -0,0 +1,40 @@ +NAME STATE +─────── ───── +item-01 ready +item-02 ready +item-03 ready +item-04 ready +item-05 ready +item-06 ready +item-07 ready +item-08 ready +item-09 ready +item-10 ready +item-11 ready +item-12 ready +item-13 ready +item-14 ready +item-15 ready +item-16 ready +item-17 ready +item-18 ready +item-19 ready +item-20 ready + + + + + + + + + + + + + + + + + +20 rows | ←→↑↓ scroll | g/G top/bottom | / search | q quit | 100% diff --git a/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/02-search-input.golden b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/02-search-input.golden new file mode 100644 index 00000000000..4e5c432cf9a --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/02-search-input.golden @@ -0,0 +1,40 @@ +NAME STATE +─────── ───── +item-01 ready +item-02 ready +item-03 ready +item-04 ready +item-05 ready +item-06 ready +item-07 ready +item-08 ready +item-09 ready +item-10 ready +item-11 ready +item-12 ready +item-13 ready +item-14 ready +item-15 ready +item-16 ready +item-17 ready +item-18 ready +item-19 ready +item-20 ready + + + + + + + + + + + + + + + + +20 rows +/ italt+f[em-1]█ diff --git a/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/03-after-search.styled.golden b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/03-after-search.styled.golden new file mode 100644 index 00000000000..2ca2de8e891 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/03-after-search.styled.golden @@ -0,0 +1,40 @@ +NAME STATE +─────── ───── +item-01 ready +item-02 ready +item-03 ready +item-04 ready +item-05 ready +item-06 ready +item-07 ready +item-08 ready +item-09 ready +item-10 ready +item-11 ready +item-12 ready +item-13 ready +item-14 ready +item-15 ready +item-16 ready +item-17 ready +item-18 ready +item-19 ready +item-20 ready + + + + + + + + + + + + + + + + + +20 rows | no matches | ←→↑↓ scroll | g/G top/bottom | / search | q quit | 100% diff --git a/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/04-result.golden b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/04-result.golden new file mode 100644 index 00000000000..d46f028b745 --- /dev/null +++ b/libs/cmdio/cmdiotest/testdata/TestTableviewPin_SearchInput/04-result.golden @@ -0,0 +1 @@ +err: diff --git a/libs/cmdio/testing.go b/libs/cmdio/testing.go index c1141f7d1e3..76a65420797 100644 --- a/libs/cmdio/testing.go +++ b/libs/cmdio/testing.go @@ -44,6 +44,47 @@ func NewTestIO(in io.Reader, out, err io.Writer) *cmdIO { } } +// TestIOOptions adjusts [NewTestIOWithOptions]. The zero value gives the same +// cmdIO as [NewTestIO]. +type TestIOOptions struct { + // HeaderTemplate and Template are the command's text templates, as + // cmd/root sets them from command annotations. [RenderIterator] pages + // only when Template is set and a pager is supported: stdin, stderr and + // stdout are terminals (StdoutNotTTY and StderrNotTTY turn the last two + // off) and the output is text. + HeaderTemplate string + Template string + + // ColorFromEnv derives NoColor and Dumb from NO_COLOR and TERM in ctx, + // the way [NewIO] does, instead of leaving them off. + ColorFromEnv bool + + // NoColor and Dumb set the color capabilities directly. They are + // independent: NoColor keeps prompts and the pager, Dumb refuses them. + NoColor bool + Dumb bool + + // StdoutNotTTY and StderrNotTTY report the stream as redirected. + StdoutNotTTY bool + StderrNotTTY bool +} + +// NewTestIOWithOptions is [NewTestIO] with the adjustments in opts. ctx is +// only read when opts.ColorFromEnv is set. +func NewTestIOWithOptions(ctx context.Context, in io.Reader, out, err io.Writer, opts TestIOOptions) *cmdIO { + c := NewTestIO(in, out, err) + c.headerTemplate = opts.HeaderTemplate + c.template = opts.Template + if opts.ColorFromEnv { + c.capabilities.noColor, c.capabilities.dumb = colorFromEnv(ctx) + } + c.capabilities.noColor = c.capabilities.noColor || opts.NoColor + c.capabilities.dumb = c.capabilities.dumb || opts.Dumb + c.capabilities.stdoutIsTTY = !opts.StdoutNotTTY + c.capabilities.stderrIsTTY = !opts.StderrNotTTY + return c +} + type Test struct { Done context.CancelFunc diff --git a/libs/cmdio/testing_options_test.go b/libs/cmdio/testing_options_test.go new file mode 100644 index 00000000000..fdb5de2ef4a --- /dev/null +++ b/libs/cmdio/testing_options_test.go @@ -0,0 +1,18 @@ +package cmdio + +import ( + "io" + "testing" + + "github.com/stretchr/testify/assert" +) + +// The zero TestIOOptions must build the same cmdIO as NewTestIO, or the +// termtest harness would pin behaviour that no caller of NewTestIO sees. +func TestNewTestIOWithOptionsZeroValueMatchesNewTestIO(t *testing.T) { + want := NewTestIO(nil, io.Discard, io.Discard) + got := NewTestIOWithOptions(t.Context(), nil, io.Discard, io.Discard, TestIOOptions{}) + assert.Equal(t, want.capabilities, got.capabilities) + assert.Equal(t, want.headerTemplate, got.headerTemplate) + assert.Equal(t, want.template, got.template) +} diff --git a/libs/tableview/tableview.go b/libs/tableview/tableview.go index 7d8e7b292d4..d85ca1cb52c 100644 --- a/libs/tableview/tableview.go +++ b/libs/tableview/tableview.go @@ -27,6 +27,23 @@ const ( // Run displays tabular data in an interactive browser. // Writes to w (typically stdout). Blocks until user quits. func Run(ctx context.Context, w io.Writer, columns []string, rows [][]string) error { + return RunWithOptions(ctx, w, columns, rows, RunOptions{}) +} + +// RunOptions adjusts [RunWithOptions]. The zero value behaves like [Run]. +type RunOptions struct { + // Input replaces the program's default input (os.Stdin) when non-nil. + Input io.Reader + + // Width and Height, when both positive, are delivered as the initial + // window size. Bubble Tea only detects the size of a terminal writer, so + // tests that render into a buffer need them. + Width, Height int +} + +// RunWithOptions is [Run] with the adjustments in opts. It exists so tests can +// drive the browser through pipes. +func RunWithOptions(ctx context.Context, w io.Writer, columns []string, rows [][]string, opts RunOptions) error { all := renderTableLines(columns, rows) header := all[:headerLines] dataLines := all[headerLines:] @@ -42,7 +59,14 @@ func Run(ctx context.Context, w io.Writer, columns []string, rows [][]string) er searchStyle: r.NewStyle().Foreground(lipgloss.Color("229")), } - p := tea.NewProgram(m, tea.WithOutput(w)) + teaOpts := []tea.ProgramOption{tea.WithOutput(w)} + if opts.Input != nil { + teaOpts = append(teaOpts, tea.WithInput(opts.Input)) + } + p := tea.NewProgram(m, teaOpts...) + if opts.Width > 0 && opts.Height > 0 { + go p.Send(tea.WindowSizeMsg{Width: opts.Width, Height: opts.Height}) + } _, err := p.Run() return err }