4 "github.com/hashicorp/terraform/registry"
7 "github.com/hashicorp/terraform/configs"
8 "github.com/hashicorp/terraform/configs/configload"
9 "github.com/hashicorp/terraform/tfdiags"
12 // LoadConfigForTests is a convenience wrapper around configload.NewLoaderForTests,
13 // ModuleInstaller.InstallModules and configload.Loader.LoadConfig that allows
14 // a test configuration to be loaded in a single step.
16 // If module installation fails, t.Fatal (or similar) is called to halt
17 // execution of the test, under the assumption that installation failures are
18 // not expected. If installation failures _are_ expected then use
19 // NewLoaderForTests and work with the loader object directly. If module
20 // installation succeeds but generates warnings, these warnings are discarded.
22 // If installation succeeds but errors are detected during loading then a
23 // possibly-incomplete config is returned along with error diagnostics. The
24 // test run is not aborted in this case, so that the caller can make assertions
25 // against the returned diagnostics.
27 // As with NewLoaderForTests, a cleanup function is returned which must be
28 // called before the test completes in order to remove the temporary
30 func LoadConfigForTests(t *testing.T, rootDir string) (*configs.Config, *configload.Loader, func(), tfdiags.Diagnostics) {
33 var diags tfdiags.Diagnostics
35 loader, cleanup := configload.NewLoaderForTests(t)
36 inst := NewModuleInstaller(loader.ModulesDir(), registry.NewClient(nil, nil))
38 _, moreDiags := inst.InstallModules(rootDir, true, ModuleInstallHooksImpl{})
39 diags = diags.Append(moreDiags)
40 if diags.HasErrors() {
43 return nil, nil, func() {}, diags
46 // Since module installer has modified the module manifest on disk, we need
47 // to refresh the cache of it in the loader.
48 if err := loader.RefreshModules(); err != nil {
49 t.Fatalf("failed to refresh modules after installation: %s", err)
52 config, hclDiags := loader.LoadConfig(rootDir)
53 diags = diags.Append(hclDiags)
54 return config, loader, cleanup, diags
57 // MustLoadConfigForTests is a variant of LoadConfigForTests which calls
58 // t.Fatal (or similar) if there are any errors during loading, and thus
59 // does not return diagnostics at all.
61 // This is useful for concisely writing tests that don't expect errors at
62 // all. For tests that expect errors and need to assert against them, use
63 // LoadConfigForTests instead.
64 func MustLoadConfigForTests(t *testing.T, rootDir string) (*configs.Config, *configload.Loader, func()) {
67 config, loader, cleanup, diags := LoadConfigForTests(t, rootDir)
68 if diags.HasErrors() {
72 return config, loader, cleanup