github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/command/ui_input_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package command 5 6 import ( 7 "bytes" 8 "context" 9 "fmt" 10 "io" 11 "sync/atomic" 12 "testing" 13 "time" 14 15 "github.com/terramate-io/tf/terraform" 16 ) 17 18 func TestUIInput_impl(t *testing.T) { 19 var _ terraform.UIInput = new(UIInput) 20 } 21 22 func TestUIInputInput(t *testing.T) { 23 i := &UIInput{ 24 Reader: bytes.NewBufferString("foo\n"), 25 Writer: bytes.NewBuffer(nil), 26 } 27 28 v, err := i.Input(context.Background(), &terraform.InputOpts{}) 29 if err != nil { 30 t.Fatalf("unexpected error: %v", err) 31 } 32 33 if v != "foo" { 34 t.Fatalf("unexpected input: %s", v) 35 } 36 } 37 38 func TestUIInputInput_canceled(t *testing.T) { 39 r, w := io.Pipe() 40 i := &UIInput{ 41 Reader: r, 42 Writer: bytes.NewBuffer(nil), 43 } 44 45 // Make a context that can be canceled. 46 ctx, cancel := context.WithCancel(context.Background()) 47 48 go func() { 49 // Cancel the context after 2 seconds. 50 time.Sleep(2 * time.Second) 51 cancel() 52 }() 53 54 // Get input until the context is canceled. 55 v, err := i.Input(ctx, &terraform.InputOpts{}) 56 if err != context.Canceled { 57 t.Fatalf("expected a context.Canceled error, got: %v", err) 58 } 59 60 // As the context was canceled v should be empty. 61 if v != "" { 62 t.Fatalf("unexpected input: %s", v) 63 } 64 65 // As the context was canceled we should still be listening. 66 listening := atomic.LoadInt32(&i.listening) 67 if listening != 1 { 68 t.Fatalf("expected listening to be 1, got: %d", listening) 69 } 70 71 go func() { 72 // Fake input is given after 1 second. 73 time.Sleep(time.Second) 74 fmt.Fprint(w, "foo\n") 75 w.Close() 76 }() 77 78 v, err = i.Input(context.Background(), &terraform.InputOpts{}) 79 if err != nil { 80 t.Fatalf("unexpected error: %v", err) 81 } 82 83 if v != "foo" { 84 t.Fatalf("unexpected input: %s", v) 85 } 86 } 87 88 func TestUIInputInput_spaces(t *testing.T) { 89 i := &UIInput{ 90 Reader: bytes.NewBufferString("foo bar\n"), 91 Writer: bytes.NewBuffer(nil), 92 } 93 94 v, err := i.Input(context.Background(), &terraform.InputOpts{}) 95 if err != nil { 96 t.Fatalf("unexpected error: %v", err) 97 } 98 99 if v != "foo bar" { 100 t.Fatalf("unexpected input: %s", v) 101 } 102 } 103 104 func TestUIInputInput_Error(t *testing.T) { 105 i := &UIInput{ 106 Reader: bytes.NewBuffer(nil), 107 Writer: bytes.NewBuffer(nil), 108 } 109 110 v, err := i.Input(context.Background(), &terraform.InputOpts{}) 111 if err == nil { 112 t.Fatalf("Error is not 'nil'") 113 } 114 115 if err.Error() != "EOF" { 116 t.Fatalf("unexpected error: %v", err) 117 } 118 119 if v != "" { 120 t.Fatalf("input must be empty") 121 } 122 }