|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +package sqlcmd |
| 5 | + |
| 6 | +import ( |
| 7 | + "os" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/microsoft/go-sqlcmd/pkg/sqlcmd" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | +) |
| 13 | + |
| 14 | +func TestIsConsoleInitializationRequiredWithRedirectedStdin(t *testing.T) { |
| 15 | + // Create a temp file to simulate redirected stdin |
| 16 | + tempFile, err := os.CreateTemp("", "stdin-test-*.txt") |
| 17 | + if err != nil { |
| 18 | + t.Fatalf("Failed to create temp file: %v", err) |
| 19 | + } |
| 20 | + defer os.Remove(tempFile.Name()) |
| 21 | + defer tempFile.Close() |
| 22 | + |
| 23 | + // Write some data to it |
| 24 | + _, err = tempFile.WriteString("SELECT 1;\nGO\n") |
| 25 | + if err != nil { |
| 26 | + t.Fatalf("Failed to write to temp file: %v", err) |
| 27 | + } |
| 28 | + |
| 29 | + // Remember the original stdin |
| 30 | + originalStdin := os.Stdin |
| 31 | + defer func() { os.Stdin = originalStdin }() |
| 32 | + |
| 33 | + // Test with a file redirection |
| 34 | + stdinFile, err := os.Open(tempFile.Name()) |
| 35 | + if err != nil { |
| 36 | + t.Fatalf("Failed to open temp file: %v", err) |
| 37 | + } |
| 38 | + defer stdinFile.Close() |
| 39 | + |
| 40 | + // Replace stdin with our redirected file |
| 41 | + os.Stdin = stdinFile |
| 42 | + |
| 43 | + // Set up a connect settings instance for SQL authentication |
| 44 | + connectConfig := sqlcmd.ConnectSettings{ |
| 45 | + UserName: "testuser", // This will trigger SQL authentication, requiring a password |
| 46 | + } |
| 47 | + |
| 48 | + // Test regular args |
| 49 | + args := &SQLCmdArguments{} |
| 50 | + |
| 51 | + // Print file stat mode for debugging |
| 52 | + fileStat, _ := os.Stdin.Stat() |
| 53 | + t.Logf("File mode: %v", fileStat.Mode()) |
| 54 | + t.Logf("Is character device: %v", (fileStat.Mode()&os.ModeCharDevice) != 0) |
| 55 | + t.Logf("Connection config: %+v", connectConfig) |
| 56 | + t.Logf("RequiresPassword() returns: %v", connectConfig.RequiresPassword()) |
| 57 | + |
| 58 | + // Test with SQL authentication that requires a password |
| 59 | + res := isConsoleInitializationRequired(&connectConfig, args) |
| 60 | + // Should be true since password is required, even with redirected stdin |
| 61 | + assert.True(t, res, "Console initialization should be required when SQL authentication is used") |
| 62 | + |
| 63 | + // Now test with no authentication (no password required) |
| 64 | + connectConfig = sqlcmd.ConnectSettings{} |
| 65 | + res = isConsoleInitializationRequired(&connectConfig, args) |
| 66 | + // Should be false since stdin is redirected and no password is required |
| 67 | + assert.False(t, res, "Console initialization should not be required with redirected stdin and no password") |
| 68 | +} |
0 commit comments