Skip to content

Commit

Permalink
hopefully remove test failures due to non-deterministic comparisons
Browse files Browse the repository at this point in the history
  • Loading branch information
jjarboe committed Dec 3, 2020
1 parent 8d6e722 commit 932a1a6
Showing 1 changed file with 57 additions and 6 deletions.
63 changes: 57 additions & 6 deletions pkg/iac-providers/terraform/v12/load-dir_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package tfv12

import (
"bytes"
"encoding/json"
"io/ioutil"
"reflect"
Expand All @@ -26,6 +25,47 @@ import (
"github.com/accurics/terrascan/pkg/iac-providers/output"
)

// prepareAllResourceConfigs prepares a
// map[string]map[string]output.ResourceConfig
// from the output.AllResourceConfigs, which is a
// map[string][]output.ResourceConfig
//
// The goal is to put the [] into a map[string] so that we don't rely on the
// implicit order of the [], but can use the keys for ordering.
// The key is computed from the source and id, which should be globally unique.
func prepareAllResourceConfigs(v output.AllResourceConfigs) ([]byte, error) {

newval := make(map[string]map[string]output.ResourceConfig, len(v))
for key, val := range v {
newval[key] = make(map[string]output.ResourceConfig, len(val))
for _, item := range val {
newkey := item.Source + "##" + item.ID
newval[key][newkey] = item
}
}

contents, err := json.Marshal(newval)
if err != nil {
return []byte{}, err
}

return contents, nil
}

// identicalAllResourceConfigs determines if a and b have identical contents
func identicalAllResourceConfigs(a, b output.AllResourceConfigs) (bool, error) {
value1, err := prepareAllResourceConfigs(a)
if err != nil {
return false, err
}
value2, err := prepareAllResourceConfigs(b)
if err != nil {
return false, err
}

return reflect.DeepEqual(value1, value2), nil
}

func TestLoadIacDir(t *testing.T) {

table := []struct {
Expand Down Expand Up @@ -107,12 +147,23 @@ func TestLoadIacDir(t *testing.T) {
t.Errorf("unexpected error; gotErr: '%v', wantErr: '%v'", gotErr, tt.wantErr)
}

gotBytes, _ := json.MarshalIndent(got, "", " ")
gotBytes = append(gotBytes, []byte{'\n'}...)
wantBytes, _ := ioutil.ReadFile(tt.tfJSONFile)
var want output.AllResourceConfigs

if !bytes.Equal(bytes.TrimSpace(gotBytes), bytes.TrimSpace(wantBytes)) {
t.Errorf("got '%v', want: '%v'", string(gotBytes), string(wantBytes))
// Read the expected value and unmarshal into want
contents, _ := ioutil.ReadFile(tt.tfJSONFile)
err := json.Unmarshal(contents, &want)
if err != nil {
t.Errorf("unexpected error unmarshalling want: %v", err)
}

match, err := identicalAllResourceConfigs(got, want)
if err != nil {
t.Errorf("unexpected error checking result: %v", err)
}
if !match {
g, _ := json.MarshalIndent(got, "", " ")
w, _ := json.MarshalIndent(want, "", " ")
t.Errorf("got '%v', want: '%v'", string(g), string(w))
}
})
}
Expand Down

0 comments on commit 932a1a6

Please sign in to comment.