From 79a74c7ebe0e7ff48c5a022bfdb04600e8cdaee8 Mon Sep 17 00:00:00 2001 From: heren-ke Date: Sun, 15 Dec 2024 20:24:06 +0800 Subject: [PATCH] feat(prompt/prompter.go):add test case for prompter.go --- console/prompt/prompter_test.go | 74 +++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 console/prompt/prompter_test.go diff --git a/console/prompt/prompter_test.go b/console/prompt/prompter_test.go new file mode 100644 index 0000000000..f4b59df5e1 --- /dev/null +++ b/console/prompt/prompter_test.go @@ -0,0 +1,74 @@ +package prompt_test + +import ( + "os" + "strings" + "testing" + + "github.com/ethereum/go-ethereum/console/prompt" + "github.com/stretchr/testify/assert" +) + +func TestPromptInput(t *testing.T) { + // Simulate user input + mockInput := "test input\n" + r, w, _ := os.Pipe() + w.WriteString(mockInput) + w.Close() + os.Stdin = r // Replace os.Stdin temporarily + + // Create a new prompter + p := prompt.NewTerminalPrompter() + defer func() { os.Stdin = os.NewFile(uintptr(0), "/dev/tty") }() // Restore os.Stdin + + // Test PromptInput + result, err := p.PromptInput("Enter something: ") + assert.NoError(t, err) + assert.Equal(t, strings.TrimSpace(mockInput), result) +} + +func TestPromptPassword(t *testing.T) { + // Simulate password input + mockPassword := "secret\n" + r, w, _ := os.Pipe() + w.WriteString(mockPassword) + w.Close() + os.Stdin = r // Replace os.Stdin temporarily + + // Create a new prompter + p := prompt.NewTerminalPrompter() + defer func() { os.Stdin = os.NewFile(uintptr(0), "/dev/tty") }() // Restore os.Stdin + + // Test PromptPassword + result, err := p.PromptPassword("Enter password: ") + assert.NoError(t, err) + assert.Equal(t, strings.TrimSpace(mockPassword), result) +} + +func mockStdin(input string) (restore func()) { + // Create a pipe to replace stdin + r, w, _ := os.Pipe() + w.WriteString(input) + w.Close() + + // Replace os.Stdin with the pipe + originalStdin := os.Stdin + os.Stdin = r + + // Return a function to restore original stdin + return func() { + os.Stdin = originalStdin + } +} + +func TestPromptConfirm(t *testing.T) { + // Test confirmation (yes) + mockInput := "y\n" + restore := mockStdin(mockInput) + defer restore() + + p := prompt.NewTerminalPrompter() + result, err := p.PromptConfirm("Do you confirm?") + assert.NoError(t, err, "Expected no error for valid input") + assert.True(t, result, "Expected confirmation to return true") +}