1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
|
package cli_test
import (
"errors"
"io"
"strings"
"syscall"
"testing"
"time"
. "src.elv.sh/pkg/cli"
. "src.elv.sh/pkg/cli/clitest"
"src.elv.sh/pkg/cli/term"
"src.elv.sh/pkg/cli/tk"
"src.elv.sh/pkg/sys"
"src.elv.sh/pkg/testutil"
"src.elv.sh/pkg/ui"
)
// Lifecycle aspects.
func TestReadCode_AbortsWhenTTYSetupReturnsError(t *testing.T) {
ttySetupErr := errors.New("a fake error")
f := Setup(WithTTY(func(tty TTYCtrl) {
tty.SetSetup(func() {}, ttySetupErr)
}))
_, err := f.Wait()
if err != ttySetupErr {
t.Errorf("ReadCode returns error %v, want %v", err, ttySetupErr)
}
}
func TestReadCode_RestoresTTYBeforeReturning(t *testing.T) {
restoreCalled := 0
f := Setup(WithTTY(func(tty TTYCtrl) {
tty.SetSetup(func() { restoreCalled++ }, nil)
}))
f.Stop()
if restoreCalled != 1 {
t.Errorf("Restore callback called %d times, want once", restoreCalled)
}
}
func TestReadCode_ResetsStateBeforeReturning(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.CodeAreaState.Buffer.Content = "some code"
}))
f.Stop()
if code := f.App.ActiveWidget().(tk.CodeArea).CopyState().Buffer; code != (tk.CodeBuffer{}) {
t.Errorf("Editor state has CodeBuffer %v, want empty", code)
}
}
func TestReadCode_CallsBeforeReadline(t *testing.T) {
callCh := make(chan bool, 1)
f := Setup(WithSpec(func(spec *AppSpec) {
spec.BeforeReadline = []func(){func() { callCh <- true }}
}))
defer f.Stop()
select {
case <-callCh:
// OK, do nothing.
case <-time.After(time.Second):
t.Errorf("BeforeReadline not called")
}
}
func TestReadCode_CallsBeforeReadlineBeforePromptTrigger(t *testing.T) {
callCh := make(chan string, 2)
f := Setup(WithSpec(func(spec *AppSpec) {
spec.BeforeReadline = []func(){func() { callCh <- "hook" }}
spec.Prompt = testPrompt{trigger: func(bool) { callCh <- "prompt" }}
}))
defer f.Stop()
if first := <-callCh; first != "hook" {
t.Errorf("BeforeReadline hook not called before prompt trigger")
}
}
func TestReadCode_CallsAfterReadline(t *testing.T) {
callCh := make(chan string, 1)
f := Setup(WithSpec(func(spec *AppSpec) {
spec.AfterReadline = []func(string){func(s string) { callCh <- s }}
}))
feedInput(f.TTY, "abc\n")
f.Wait()
select {
case calledWith := <-callCh:
wantCalledWith := "abc"
if calledWith != wantCalledWith {
t.Errorf("AfterReadline hook called with %v, want %v",
calledWith, wantCalledWith)
}
case <-time.After(time.Second):
t.Errorf("AfterReadline not called")
}
}
func TestReadCode_FinalRedraw(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.CodeAreaState.Buffer.Content = "code"
spec.State.Addons = []tk.Widget{tk.Label{Content: ui.T("addon")}}
}))
// Wait until the stable state.
wantBuf := bb().
Write("code").
Newline().SetDotHere().Write("addon").Buffer()
f.TTY.TestBuffer(t, wantBuf)
f.Stop()
// Final redraw hides the addon, and puts the cursor on a new line.
wantFinalBuf := bb().
Write("code").Newline().SetDotHere().Buffer()
f.TTY.TestBuffer(t, wantFinalBuf)
}
// Signals.
func TestReadCode_ReturnsEOFOnSIGHUP(t *testing.T) {
f := Setup()
f.TTY.Inject(term.K('a'))
// Wait until the initial redraw.
f.TTY.TestBuffer(t, bb().Write("a").SetDotHere().Buffer())
f.TTY.InjectSignal(syscall.SIGHUP)
_, err := f.Wait()
if err != io.EOF {
t.Errorf("want ReadCode to return io.EOF on SIGHUP, got %v", err)
}
}
func TestReadCode_ResetsStateOnSIGINT(t *testing.T) {
f := Setup()
defer f.Stop()
// Ensure that the terminal shows an non-empty state.
feedInput(f.TTY, "code")
f.TTY.TestBuffer(t, bb().Write("code").SetDotHere().Buffer())
f.TTY.InjectSignal(syscall.SIGINT)
// Verify that the state has now reset.
f.TTY.TestBuffer(t, bb().Buffer())
}
func TestReadCode_RedrawsOnSIGWINCH(t *testing.T) {
f := Setup()
defer f.Stop()
// Ensure that the terminal shows the input with the initial width.
feedInput(f.TTY, "1234567890")
f.TTY.TestBuffer(t, bb().Write("1234567890").SetDotHere().Buffer())
// Emulate a window size change.
f.TTY.SetSize(24, 4)
f.TTY.InjectSignal(sys.SIGWINCH)
// Test that the editor has redrawn using the new width.
f.TTY.TestBuffer(t, term.NewBufferBuilder(4).
Write("1234567890").SetDotHere().Buffer())
}
// Code area.
func TestReadCode_LetsCodeAreaHandleEvents(t *testing.T) {
f := Setup()
defer f.Stop()
feedInput(f.TTY, "code")
f.TTY.TestBuffer(t, bb().Write("code").SetDotHere().Buffer())
}
func TestReadCode_ShowsHighlightedCode(t *testing.T) {
f := Setup(withHighlighter(
testHighlighter{
get: func(code string) (ui.Text, []ui.Text) {
return ui.T(code, ui.FgRed), nil
},
}))
defer f.Stop()
feedInput(f.TTY, "code")
wantBuf := bb().Write("code", ui.FgRed).SetDotHere().Buffer()
f.TTY.TestBuffer(t, wantBuf)
}
func TestReadCode_ShowsErrorsFromHighlighter_ExceptInFinalRedraw(t *testing.T) {
f := Setup(withHighlighter(
testHighlighter{
get: func(code string) (ui.Text, []ui.Text) {
tips := []ui.Text{ui.T("ERR 1"), ui.T("ERR 2")}
return ui.T(code), tips
},
}))
defer f.Stop()
feedInput(f.TTY, "code")
wantBuf := bb().
Write("code").SetDotHere().Newline().
Write("ERR 1").Newline().
Write("ERR 2").Buffer()
f.TTY.TestBuffer(t, wantBuf)
feedInput(f.TTY, "\n")
f.TestTTY(t, "code", "\n", term.DotHere)
}
func TestReadCode_RedrawsOnLateUpdateFromHighlighter(t *testing.T) {
var styling ui.Styling
hl := testHighlighter{
get: func(code string) (ui.Text, []ui.Text) {
return ui.T(code, styling), nil
},
lateUpdates: make(chan struct{}),
}
f := Setup(withHighlighter(hl))
defer f.Stop()
feedInput(f.TTY, "code")
f.TTY.TestBuffer(t, bb().Write("code").SetDotHere().Buffer())
styling = ui.FgRed
hl.lateUpdates <- struct{}{}
f.TTY.TestBuffer(t, bb().Write("code", ui.FgRed).SetDotHere().Buffer())
}
func withHighlighter(hl Highlighter) func(*AppSpec, TTYCtrl) {
return WithSpec(func(spec *AppSpec) { spec.Highlighter = hl })
}
func TestReadCode_ShowsPrompt(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.Prompt = NewConstPrompt(ui.T("> "))
}))
defer f.Stop()
f.TTY.Inject(term.K('a'))
f.TTY.TestBuffer(t, bb().Write("> a").SetDotHere().Buffer())
}
func TestReadCode_CallsPromptTrigger(t *testing.T) {
triggerCh := make(chan bool, 1)
f := Setup(WithSpec(func(spec *AppSpec) {
spec.Prompt = testPrompt{trigger: func(bool) { triggerCh <- true }}
}))
defer f.Stop()
select {
case <-triggerCh:
// Good, test passes
case <-time.After(time.Second):
t.Errorf("Trigger not called within 1s")
}
}
func TestReadCode_RedrawsOnLateUpdateFromPrompt(t *testing.T) {
promptContent := "old"
prompt := testPrompt{
get: func() ui.Text { return ui.T(promptContent) },
lateUpdates: make(chan struct{}),
}
f := Setup(WithSpec(func(spec *AppSpec) { spec.Prompt = prompt }))
defer f.Stop()
// Wait until old prompt is rendered
f.TTY.TestBuffer(t, bb().Write("old").SetDotHere().Buffer())
promptContent = "new"
prompt.lateUpdates <- struct{}{}
f.TTY.TestBuffer(t, bb().Write("new").SetDotHere().Buffer())
}
func TestReadCode_ShowsRPrompt(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.RPrompt = NewConstPrompt(ui.T("R"))
}))
defer f.Stop()
f.TTY.Inject(term.K('a'))
wantBuf := bb().
Write("a").SetDotHere().
Write(strings.Repeat(" ", FakeTTYWidth-2)).
Write("R").Buffer()
f.TTY.TestBuffer(t, wantBuf)
}
func TestReadCode_ShowsRPromptInFinalRedrawIfPersistent(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.CodeAreaState.Buffer.Content = "code"
spec.RPrompt = NewConstPrompt(ui.T("R"))
spec.RPromptPersistent = func() bool { return true }
}))
defer f.Stop()
f.TTY.Inject(term.K('\n'))
wantBuf := bb().
Write("code" + strings.Repeat(" ", FakeTTYWidth-5) + "R").
Newline().SetDotHere(). // cursor on newline in final redraw
Buffer()
f.TTY.TestBuffer(t, wantBuf)
}
func TestReadCode_HidesRPromptInFinalRedrawIfNotPersistent(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.CodeAreaState.Buffer.Content = "code"
spec.RPrompt = NewConstPrompt(ui.T("R"))
spec.RPromptPersistent = func() bool { return false }
}))
defer f.Stop()
f.TTY.Inject(term.K('\n'))
wantBuf := bb().
Write("code"). // no rprompt
Newline().SetDotHere(). // cursor on newline in final redraw
Buffer()
f.TTY.TestBuffer(t, wantBuf)
}
// Addon.
func TestReadCode_LetsLastWidgetHandleEvents(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.State.Addons = []tk.Widget{
tk.NewCodeArea(tk.CodeAreaSpec{
Prompt: func() ui.Text { return ui.T("addon1> ") },
}),
tk.NewCodeArea(tk.CodeAreaSpec{
Prompt: func() ui.Text { return ui.T("addon2> ") },
}),
}
}))
defer f.Stop()
feedInput(f.TTY, "input")
wantBuf := bb().Newline(). // empty main code area
Write("addon1> ").Newline(). // addon1 did not handle inputs
Write("addon2> input").SetDotHere(). // addon2 handled inputs
Buffer()
f.TTY.TestBuffer(t, wantBuf)
}
func TestReadCode_PutsCursorOnLastWidgetWithFocus(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.State.Addons = []tk.Widget{
testAddon{tk.Label{Content: ui.T("addon1> ")}, true},
testAddon{tk.Label{Content: ui.T("addon2> ")}, false},
}
}))
defer f.Stop()
f.TestTTY(t, "\n", // main code area is empty
term.DotHere, "addon1> ", "\n", // addon 1 has focus
"addon2> ", // addon 2 has no focus
)
}
func TestPushAddonPopAddon(t *testing.T) {
f := Setup()
defer f.Stop()
f.TestTTY(t /* nothing */)
f.App.PushAddon(tk.Label{Content: ui.T("addon1> ")})
f.App.Redraw()
f.TestTTY(t, "\n",
term.DotHere, "addon1> ")
f.App.PushAddon(tk.Label{Content: ui.T("addon2> ")})
f.App.Redraw()
f.TestTTY(t, "\n",
"addon1> \n",
term.DotHere, "addon2> ")
f.App.PopAddon()
f.App.Redraw()
f.TestTTY(t, "\n",
term.DotHere, "addon1> ")
f.App.PopAddon()
f.App.Redraw()
f.TestTTY(t /* nothing */)
// Popping addon when there is no addon does nothing
f.App.PopAddon()
// Add something to the codearea to ensure that we're not just looking at
// the previous buffer
f.TTY.Inject(term.K(' '))
f.TestTTY(t, " ", term.DotHere)
}
func TestReadCode_HidesAddonsWhenNotEnoughSpace(t *testing.T) {
f := Setup(
func(spec *AppSpec, tty TTYCtrl) {
spec.State.Addons = []tk.Widget{
tk.Label{Content: ui.T("addon1> ")},
tk.Label{Content: ui.T("addon2> ")}, // no space for this
}
tty.SetSize(2, 40)
})
defer f.Stop()
f.TestTTY(t,
"addon1> \n",
term.DotHere, "addon2> ")
}
type testAddon struct {
tk.Label
focus bool
}
func (a testAddon) Focus() bool { return a.focus }
// Event handling.
func TestReadCode_UsesGlobalBindingsWithCodeAreaTarget(t *testing.T) {
testGlobalBindings(t, nil)
}
func TestReadCode_UsesGlobalBindingsWithAddonTarget(t *testing.T) {
testGlobalBindings(t, []tk.Widget{tk.Empty{}})
}
func testGlobalBindings(t *testing.T, addons []tk.Widget) {
gotWidgetCh := make(chan tk.Widget, 1)
f := Setup(WithSpec(func(spec *AppSpec) {
spec.GlobalBindings = tk.MapBindings{
term.K('X', ui.Ctrl): func(w tk.Widget) {
gotWidgetCh <- w
},
}
spec.State.Addons = addons
}))
defer f.Stop()
f.TTY.Inject(term.K('X', ui.Ctrl))
select {
case gotWidget := <-gotWidgetCh:
if gotWidget != f.App.ActiveWidget() {
t.Error("global binding not called with the active widget")
}
case <-time.After(testutil.Scaled(100 * time.Millisecond)):
t.Error("global binding not called")
}
}
func TestReadCode_DoesNotUseGlobalBindingsIfHandledByWidget(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) {
spec.GlobalBindings = tk.MapBindings{
term.K('a'): func(w tk.Widget) {},
}
}))
defer f.Stop()
f.TTY.Inject(term.K('a'))
// Still handled by code area instead of global binding
f.TestTTY(t, "a", term.DotHere)
}
func TestReadCode_NotifiesAboutUnboundKey(t *testing.T) {
f := Setup()
defer f.Stop()
f.TTY.Inject(term.K(ui.F1))
f.TestTTYNotes(t, "Unbound key: F1")
}
// Misc features.
func TestReadCode_TrimsBufferToMaxHeight(t *testing.T) {
f := Setup(func(spec *AppSpec, tty TTYCtrl) {
spec.MaxHeight = func() int { return 2 }
// The code needs 3 lines to completely show.
spec.CodeAreaState.Buffer.Content = strings.Repeat("a", 15)
tty.SetSize(10, 5) // Width = 5 to make it easy to test
})
defer f.Stop()
wantBuf := term.NewBufferBuilder(5).
Write(strings.Repeat("a", 10)). // Only show 2 lines due to MaxHeight.
Buffer()
f.TTY.TestBuffer(t, wantBuf)
}
func TestReadCode_ShowNotes(t *testing.T) {
// Set up with a binding where 'a' can block indefinitely. This is useful
// for testing the behavior of writing multiple notes.
inHandler := make(chan struct{})
unblock := make(chan struct{})
f := Setup(WithSpec(func(spec *AppSpec) {
spec.CodeAreaBindings = tk.MapBindings{
term.K('a'): func(tk.Widget) {
inHandler <- struct{}{}
<-unblock
},
}
}))
defer f.Stop()
// Wait until initial draw.
f.TTY.TestBuffer(t, bb().Buffer())
// Make sure that the app is blocked within an event handler.
f.TTY.Inject(term.K('a'))
<-inHandler
// Write two notes, and unblock the event handler
f.App.Notify(ui.T("note"))
f.App.Notify(ui.T("note 2"))
unblock <- struct{}{}
// Test that the note is rendered onto the notes buffer.
wantNotesBuf := bb().Write("note").Newline().Write("note 2").Buffer()
f.TTY.TestNotesBuffer(t, wantNotesBuf)
// Test that notes are flushed after being rendered.
if n := len(f.App.CopyState().Notes); n > 0 {
t.Errorf("State.Notes has %d elements after redrawing, want 0", n)
}
}
func TestReadCode_DoesNotCrashWithNilTTY(t *testing.T) {
f := Setup(WithSpec(func(spec *AppSpec) { spec.TTY = nil }))
defer f.Stop()
}
// Other properties.
func TestReadCode_DoesNotLockWithALotOfInputsWithNewlines(t *testing.T) {
// Regression test for #887
f := Setup(WithTTY(func(tty TTYCtrl) {
for i := 0; i < 1000; i++ {
tty.Inject(term.K('#'), term.K('\n'))
}
}))
terminated := make(chan struct{})
go func() {
f.Wait()
close(terminated)
}()
select {
case <-terminated:
// OK
case <-time.After(time.Second):
t.Errorf("ReadCode did not terminate within 1s")
}
}
func TestReadCode_DoesNotReadMoreEventsThanNeeded(t *testing.T) {
f := Setup()
defer f.Stop()
f.TTY.Inject(term.K('a'), term.K('\n'), term.K('b'))
code, err := f.Wait()
if code != "a" || err != nil {
t.Errorf("got (%q, %v), want (%q, nil)", code, err, "a")
}
if event := <-f.TTY.EventCh(); event != term.K('b') {
t.Errorf("got event %v, want %v", event, term.K('b'))
}
}
// Test utilities.
func bb() *term.BufferBuilder {
return term.NewBufferBuilder(FakeTTYWidth)
}
func feedInput(ttyCtrl TTYCtrl, input string) {
for _, r := range input {
ttyCtrl.Inject(term.K(r))
}
}
// A Highlighter implementation useful for testing.
type testHighlighter struct {
get func(code string) (ui.Text, []ui.Text)
lateUpdates chan struct{}
}
func (hl testHighlighter) Get(code string) (ui.Text, []ui.Text) {
return hl.get(code)
}
func (hl testHighlighter) LateUpdates() <-chan struct{} {
return hl.lateUpdates
}
// A Prompt implementation useful for testing.
type testPrompt struct {
trigger func(force bool)
get func() ui.Text
lateUpdates chan struct{}
}
func (p testPrompt) Trigger(force bool) {
if p.trigger != nil {
p.trigger(force)
}
}
func (p testPrompt) Get() ui.Text {
if p.get != nil {
return p.get()
}
return nil
}
func (p testPrompt) LateUpdates() <-chan struct{} {
return p.lateUpdates
}
|