package main import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "testing" "github.cmd.navi-tech.in/navi-infra/infra-provisioner/bindata" "github.com/sergi/go-diff/diffmatchpatch" ) const ActualOutputDir = "actual_output" const TestDataDir = "testdata" const ExpectedOutputDir = "expected_output" const ManifestFile = "sample_infra_manifest.json" func textDiff(text1, text2 string) string { dmp := diffmatchpatch.New() diffs := dmp.DiffMain(text1, text2, false) return dmp.DiffPrettyText(diffs) } func CompareResourceWithOutput(resouceDir string, resource string) error { dirs, err := ioutil.ReadDir(TestDataDir) if err != nil { return err } for _, dir := range dirs { fmt.Print(dir.Name()) manifest, err := parseManifest(filepath.Join(TestDataDir, dir.Name(), ManifestFile)) if err != nil { return err } err = templateResourceTf(resource, resouceDir, manifest, filepath.Join(TestDataDir, dir.Name(), ActualOutputDir, resouceDir)) if err != nil { return err } err = filepath.Walk(filepath.Join(TestDataDir, dir.Name(), ExpectedOutputDir, resouceDir), func(path string, fileInfo os.FileInfo, err error) error { if err != nil { return err } if fileInfo.IsDir() { return nil } expectedOutput, err := ioutil.ReadFile(path) if err != nil { return err } actualOutput, err := ioutil.ReadFile(filepath.Join(TestDataDir, dir.Name(), ActualOutputDir, resouceDir, filepath.Base(path))) if err != nil { return err } if bytes.Compare(expectedOutput, actualOutput) != 0 { return fmt.Errorf("Mismatch for %s, diff: %s\n", path, textDiff(string(actualOutput), string(expectedOutput))) } return nil }) if err != nil { return err } } return nil } func TestBinData_CompareWithTemplates(t *testing.T) { err := filepath.Walk(TemplatesDir, func(path string, fileInfo os.FileInfo, err error) error { if err != nil { t.Error(err) } if fileInfo.IsDir() { return nil } actualTemplate, err := ioutil.ReadFile(path) if err != nil { t.Error(err) } binDataTemplate, err := bindata.Asset(path) if err != nil { t.Error(err) } if bytes.Compare(actualTemplate, binDataTemplate) != 0 { t.Errorf("Found outdated bindata for %s", path) } return nil }) if err != nil { t.Error(err) } } func TestTemplates_Rds_CompareWithOutput(t *testing.T) { err := CompareResourceWithOutput("rds-tf", "rds") if err != nil { t.Error(err) } } func TestTemplates_S3_CompareWithOutput(t *testing.T) { err := CompareResourceWithOutput("aws-s3-bucket-tf", "s3-bucket") if err != nil { t.Error(err) } } func TestTemplates_AwsRole_CompareWithOutput(t *testing.T) { err := CompareResourceWithOutput("aws-roles-tf", "iam-role") if err != nil { t.Error(err) } }