|
1 | 1 | package output |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
| 5 | + "io" |
4 | 6 | "io/ioutil" |
| 7 | + "os" |
5 | 8 | "path" |
6 | 9 | "testing" |
7 | 10 |
|
8 | | - "github.com/cloudskiff/driftctl/test/goldenfile" |
9 | | - |
10 | 11 | "github.com/stretchr/testify/assert" |
11 | 12 |
|
12 | 13 | "github.com/cloudskiff/driftctl/pkg/analyser" |
| 14 | + "github.com/cloudskiff/driftctl/test/goldenfile" |
13 | 15 | ) |
14 | 16 |
|
15 | 17 | func TestJSON_Write(t *testing.T) { |
@@ -84,3 +86,74 @@ func TestJSON_Write(t *testing.T) { |
84 | 86 | }) |
85 | 87 | } |
86 | 88 | } |
| 89 | + |
| 90 | +func TestJSON_Write_stdout(t *testing.T) { |
| 91 | + type args struct { |
| 92 | + analysis *analyser.Analysis |
| 93 | + } |
| 94 | + tests := []struct { |
| 95 | + name string |
| 96 | + path string |
| 97 | + goldenfile string |
| 98 | + args args |
| 99 | + wantErr bool |
| 100 | + }{ |
| 101 | + { |
| 102 | + name: "test json output stdout", |
| 103 | + goldenfile: "output.json", |
| 104 | + path: "stdout", |
| 105 | + args: args{ |
| 106 | + analysis: fakeAnalysis(), |
| 107 | + }, |
| 108 | + wantErr: false, |
| 109 | + }, |
| 110 | + |
| 111 | + { |
| 112 | + name: "test json output /dev/stdout", |
| 113 | + goldenfile: "output.json", |
| 114 | + path: "/dev/stdout", |
| 115 | + args: args{ |
| 116 | + analysis: fakeAnalysis(), |
| 117 | + }, |
| 118 | + wantErr: false, |
| 119 | + }, |
| 120 | + } |
| 121 | + for _, tt := range tests { |
| 122 | + t.Run(tt.name, func(t *testing.T) { |
| 123 | + |
| 124 | + stdout := os.Stdout // keep backup of the real stdout |
| 125 | + r, w, _ := os.Pipe() |
| 126 | + os.Stdout = w |
| 127 | + |
| 128 | + c := NewJSON(tt.path) |
| 129 | + if err := c.Write(tt.args.analysis); (err != nil) != tt.wantErr { |
| 130 | + t.Errorf("Write() error = %v, wantErr %v", err, tt.wantErr) |
| 131 | + } |
| 132 | + |
| 133 | + outC := make(chan []byte) |
| 134 | + // copy the output in a separate goroutine so printing can't block indefinitely |
| 135 | + go func() { |
| 136 | + var buf bytes.Buffer |
| 137 | + _, _ = io.Copy(&buf, r) |
| 138 | + outC <- buf.Bytes() |
| 139 | + }() |
| 140 | + |
| 141 | + // back to normal state |
| 142 | + w.Close() |
| 143 | + os.Stdout = stdout // restoring the real stdout |
| 144 | + result := <-outC |
| 145 | + |
| 146 | + expectedFilePath := path.Join("./testdata/", tt.goldenfile) |
| 147 | + if *goldenfile.Update == tt.goldenfile { |
| 148 | + if err := ioutil.WriteFile(expectedFilePath, result, 0600); err != nil { |
| 149 | + t.Fatal(err) |
| 150 | + } |
| 151 | + } |
| 152 | + expected, err := ioutil.ReadFile(expectedFilePath) |
| 153 | + if err != nil { |
| 154 | + t.Fatal(err) |
| 155 | + } |
| 156 | + assert.Equal(t, string(expected), string(result)) |
| 157 | + }) |
| 158 | + } |
| 159 | +} |
0 commit comments