|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 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 util |
| 18 | + |
| 19 | +import ( |
| 20 | + "bufio" |
| 21 | + "os" |
| 22 | + "strings" |
| 23 | + |
| 24 | + . "github.com/onsi/ginkgo/v2" |
| 25 | + . "github.com/onsi/gomega" |
| 26 | +) |
| 27 | + |
| 28 | +var _ = Describe("stdin", func() { |
| 29 | + It("returns true for 'y'", func() { |
| 30 | + reader := bufio.NewReader(strings.NewReader("y\n")) |
| 31 | + Expect(YesNo(reader)).To(BeTrue()) |
| 32 | + }) |
| 33 | + |
| 34 | + It("returns true for 'yes'", func() { |
| 35 | + reader := bufio.NewReader(strings.NewReader("yes\n")) |
| 36 | + Expect(YesNo(reader)).To(BeTrue()) |
| 37 | + }) |
| 38 | + |
| 39 | + It("returns false for 'n'", func() { |
| 40 | + reader := bufio.NewReader(strings.NewReader("n\n")) |
| 41 | + Expect(YesNo(reader)).To(BeFalse()) |
| 42 | + }) |
| 43 | + |
| 44 | + It("returns false for 'no'", func() { |
| 45 | + reader := bufio.NewReader(strings.NewReader("no\n")) |
| 46 | + Expect(YesNo(reader)).To(BeFalse()) |
| 47 | + }) |
| 48 | + |
| 49 | + It("prompts again on invalid input", func() { |
| 50 | + // "maybe" is invalid, then "y" is valid |
| 51 | + input := "maybe\ny\n" |
| 52 | + reader := bufio.NewReader(strings.NewReader(input)) |
| 53 | + |
| 54 | + // Capture stdout to check for prompt |
| 55 | + oldStdout := os.Stdout |
| 56 | + _, w, _ := os.Pipe() |
| 57 | + os.Stdout = w |
| 58 | + |
| 59 | + // Call YesNo directly (no goroutine needed) |
| 60 | + Expect(YesNo(reader)).To(BeTrue()) |
| 61 | + |
| 62 | + Expect(w.Close()).NotTo(HaveOccurred()) |
| 63 | + os.Stdout = oldStdout |
| 64 | + }) |
| 65 | + |
| 66 | + It("trims spaces and works", func() { |
| 67 | + reader := bufio.NewReader(strings.NewReader(" yes \n")) |
| 68 | + Expect(YesNo(reader)).To(BeTrue()) |
| 69 | + }) |
| 70 | +}) |
0 commit comments