|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "os" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "gotest.tools/v3/assert" |
| 9 | +) |
| 10 | + |
| 11 | +func TestSubstRunE(t *testing.T) { |
| 12 | + // Set environment variables for testing |
| 13 | + err := os.Setenv("ENV_NAME", "world") |
| 14 | + if err != nil { |
| 15 | + t.Fatal(err) |
| 16 | + } |
| 17 | + |
| 18 | + testCases := []struct { |
| 19 | + name string |
| 20 | + input string |
| 21 | + output string |
| 22 | + }{ |
| 23 | + { |
| 24 | + name: "substitute variables", |
| 25 | + input: "Hello $ENV_NAME!", |
| 26 | + output: "Hello world!", |
| 27 | + }, |
| 28 | + { |
| 29 | + name: "no variables to substitute", |
| 30 | + input: "Hello, world!", |
| 31 | + output: "Hello, world!", |
| 32 | + }, |
| 33 | + { |
| 34 | + name: "empty input", |
| 35 | + input: "", |
| 36 | + output: "", |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "no variables JSON", |
| 40 | + input: `{"foo": "bar"}`, |
| 41 | + output: `{"foo": "bar"}`, |
| 42 | + }, |
| 43 | + { |
| 44 | + name: "substitute variables JSON", |
| 45 | + input: `{"foo": "$ENV_NAME"}`, |
| 46 | + output: `{"foo": "world"}`, |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "no variables key=value", |
| 50 | + input: `foo=bar`, |
| 51 | + output: `foo=bar`, |
| 52 | + }, |
| 53 | + } |
| 54 | + |
| 55 | + // Run tests for each test case as argument |
| 56 | + for _, tc := range testCases { |
| 57 | + t.Run("arg: "+tc.name, func(t *testing.T) { |
| 58 | + // Set up test command |
| 59 | + cmd := newEnvCmd() |
| 60 | + |
| 61 | + // Capture output |
| 62 | + outputBuf := bytes.Buffer{} |
| 63 | + cmd.SetOut(&outputBuf) |
| 64 | + |
| 65 | + // Run command |
| 66 | + cmd.SetArgs([]string{"subst", tc.input}) |
| 67 | + err := cmd.Execute() |
| 68 | + |
| 69 | + // Check output and error |
| 70 | + assert.NilError(t, err) |
| 71 | + assert.Equal(t, tc.output, outputBuf.String()) |
| 72 | + }) |
| 73 | + } |
| 74 | + // Run tests for each test case as stdin |
| 75 | + for _, tc := range testCases { |
| 76 | + t.Run("stdin: "+tc.name, func(t *testing.T) { |
| 77 | + // Set up test command |
| 78 | + cmd := newEnvCmd() |
| 79 | + |
| 80 | + // Set up input |
| 81 | + inputBuf := bytes.NewBufferString(tc.input) |
| 82 | + cmd.SetIn(inputBuf) |
| 83 | + |
| 84 | + // Capture output |
| 85 | + outputBuf := bytes.Buffer{} |
| 86 | + cmd.SetOut(&outputBuf) |
| 87 | + |
| 88 | + // Run command |
| 89 | + cmd.SetArgs([]string{"subst"}) |
| 90 | + err = cmd.Execute() |
| 91 | + |
| 92 | + // Check output and error |
| 93 | + assert.NilError(t, err) |
| 94 | + assert.Equal(t, tc.output, outputBuf.String()) |
| 95 | + }) |
| 96 | + } |
| 97 | +} |
0 commit comments