github.com/sfdevops1/terrra4orm@v0.11.12-beta1/configs/parser_test.go (about) 1 package configs 2 3 import ( 4 "os" 5 "path" 6 "reflect" 7 "testing" 8 9 "github.com/davecgh/go-spew/spew" 10 11 "github.com/hashicorp/hcl2/hcl" 12 "github.com/spf13/afero" 13 ) 14 15 // testParser returns a parser that reads files from the given map, which 16 // is from paths to file contents. 17 // 18 // Since this function uses only in-memory objects, it should never fail. 19 // If any errors are encountered in practice, this function will panic. 20 func testParser(files map[string]string) *Parser { 21 fs := afero.Afero{Fs: afero.NewMemMapFs()} 22 23 for filePath, contents := range files { 24 dirPath := path.Dir(filePath) 25 err := fs.MkdirAll(dirPath, os.ModePerm) 26 if err != nil { 27 panic(err) 28 } 29 err = fs.WriteFile(filePath, []byte(contents), os.ModePerm) 30 if err != nil { 31 panic(err) 32 } 33 } 34 35 return NewParser(fs) 36 } 37 38 // testModuleFromFile reads a single file, wraps it in a module, and returns 39 // it. This is a helper for use in unit tests. 40 func testModuleFromFile(filename string) (*Module, hcl.Diagnostics) { 41 parser := NewParser(nil) 42 f, diags := parser.LoadConfigFile(filename) 43 mod, modDiags := NewModule([]*File{f}, nil) 44 diags = append(diags, modDiags...) 45 return mod, modDiags 46 } 47 48 // testModuleFromDir reads configuration from the given directory path as 49 // a module and returns it. This is a helper for use in unit tests. 50 func testModuleFromDir(path string) (*Module, hcl.Diagnostics) { 51 parser := NewParser(nil) 52 return parser.LoadConfigDir(path) 53 } 54 55 func assertNoDiagnostics(t *testing.T, diags hcl.Diagnostics) bool { 56 t.Helper() 57 return assertDiagnosticCount(t, diags, 0) 58 } 59 60 func assertDiagnosticCount(t *testing.T, diags hcl.Diagnostics, want int) bool { 61 t.Helper() 62 if len(diags) != 0 { 63 t.Errorf("wrong number of diagnostics %d; want %d", len(diags), want) 64 for _, diag := range diags { 65 t.Logf("- %s", diag) 66 } 67 return true 68 } 69 return false 70 } 71 72 func assertDiagnosticSummary(t *testing.T, diags hcl.Diagnostics, want string) bool { 73 t.Helper() 74 75 for _, diag := range diags { 76 if diag.Summary == want { 77 return false 78 } 79 } 80 81 t.Errorf("missing diagnostic summary %q", want) 82 for _, diag := range diags { 83 t.Logf("- %s", diag) 84 } 85 return true 86 } 87 88 func assertResultDeepEqual(t *testing.T, got, want interface{}) bool { 89 t.Helper() 90 if !reflect.DeepEqual(got, want) { 91 t.Errorf("wrong result\ngot: %swant: %s", spew.Sdump(got), spew.Sdump(want)) 92 return true 93 } 94 return false 95 } 96 97 func stringPtr(s string) *string { 98 return &s 99 }