From 9ec8c141566ddbf08d20d5a830a7e46353af3add Mon Sep 17 00:00:00 2001 From: Elie Date: Tue, 30 Mar 2021 17:43:21 +0200 Subject: [PATCH] Truncate file when opening file in json output --- pkg/cmd/scan/output/json.go | 2 +- pkg/cmd/scan/output/json_test.go | 36 +++++++++++++++++++ .../testdata/output_multiples_times.json | 15 ++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 pkg/cmd/scan/output/testdata/output_multiples_times.json diff --git a/pkg/cmd/scan/output/json.go b/pkg/cmd/scan/output/json.go index 6f535577..29f7da3b 100644 --- a/pkg/cmd/scan/output/json.go +++ b/pkg/cmd/scan/output/json.go @@ -21,7 +21,7 @@ func NewJSON(path string) *JSON { func (c *JSON) Write(analysis *analyser.Analysis) error { file := os.Stdout if !isStdOut(c.path) { - f, err := os.OpenFile(c.path, os.O_CREATE|os.O_RDWR, 0600) + f, err := os.OpenFile(c.path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600) if err != nil { return err } diff --git a/pkg/cmd/scan/output/json_test.go b/pkg/cmd/scan/output/json_test.go index aee274cf..3ee0482c 100644 --- a/pkg/cmd/scan/output/json_test.go +++ b/pkg/cmd/scan/output/json_test.go @@ -157,3 +157,39 @@ func TestJSON_Write_stdout(t *testing.T) { }) } } + +func TestJSON_WriteMultiplesTimesInSameFile(t *testing.T) { + emptyAnalysis := &analyser.Analysis{} + longerAnalysis := fakeAnalysis() + tempDir := t.TempDir() + tempFile, err := ioutil.TempFile(tempDir, "result") + if err != nil { + t.Fatal(err) + } + c := NewJSON(tempFile.Name()) + + if err := c.Write(longerAnalysis); err != nil { + t.Errorf("First write error = %v", err) + } + + if err := c.Write(emptyAnalysis); err != nil { + t.Errorf("Second write error = %v", err) + } + + result, err := ioutil.ReadFile(tempFile.Name()) + if err != nil { + t.Fatal(err) + } + goldenFileName := "output_multiples_times.json" + expectedFilePath := path.Join("./testdata/", goldenFileName) + if *goldenfile.Update == goldenFileName { + if err := ioutil.WriteFile(expectedFilePath, result, 0600); err != nil { + t.Fatal(err) + } + } + expected, err := ioutil.ReadFile(expectedFilePath) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, string(expected), string(result)) +} diff --git a/pkg/cmd/scan/output/testdata/output_multiples_times.json b/pkg/cmd/scan/output/testdata/output_multiples_times.json new file mode 100644 index 00000000..ff8b6755 --- /dev/null +++ b/pkg/cmd/scan/output/testdata/output_multiples_times.json @@ -0,0 +1,15 @@ +{ + "summary": { + "total_resources": 0, + "total_drifted": 0, + "total_unmanaged": 0, + "total_missing": 0, + "total_managed": 0 + }, + "managed": null, + "unmanaged": null, + "missing": null, + "differences": null, + "coverage": 0, + "alerts": null +} \ No newline at end of file