|
| 1 | +/* |
| 2 | +Copyright 2021 Gravitational, Inc. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package prompt |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "io" |
| 22 | + "testing" |
| 23 | + |
| 24 | + "github.com/stretchr/testify/require" |
| 25 | +) |
| 26 | + |
| 27 | +func TestInput(t *testing.T) { |
| 28 | + t.Parallel() |
| 29 | + |
| 30 | + out, in := io.Pipe() |
| 31 | + defer out.Close() |
| 32 | + write := func(t *testing.T, s string) { |
| 33 | + _, err := in.Write([]byte(s)) |
| 34 | + require.NoError(t, err) |
| 35 | + } |
| 36 | + |
| 37 | + r := NewContextReader(out) |
| 38 | + ctx := context.Background() |
| 39 | + |
| 40 | + t.Run("no whitespace", func(t *testing.T) { |
| 41 | + go write(t, "hi") |
| 42 | + got, err := Input(ctx, io.Discard, r, "") |
| 43 | + require.NoError(t, err) |
| 44 | + require.Equal(t, got, "hi") |
| 45 | + }) |
| 46 | + |
| 47 | + t.Run("with whitespace", func(t *testing.T) { |
| 48 | + go write(t, "hey\n") |
| 49 | + got, err := Input(ctx, io.Discard, r, "") |
| 50 | + require.NoError(t, err) |
| 51 | + require.Equal(t, got, "hey") |
| 52 | + }) |
| 53 | + |
| 54 | + t.Run("closed input", func(t *testing.T) { |
| 55 | + require.NoError(t, in.Close()) |
| 56 | + got, err := Input(ctx, io.Discard, r, "") |
| 57 | + require.ErrorIs(t, err, io.EOF) |
| 58 | + require.Empty(t, got) |
| 59 | + }) |
| 60 | +} |
0 commit comments