diff --git a/helper/resource/testing.go b/helper/resource/testing.go index 6d82d80173d..d20323df23a 100644 --- a/helper/resource/testing.go +++ b/helper/resource/testing.go @@ -414,6 +414,9 @@ type TestStep struct { // Config a string of the configuration to give to Terraform. If this // is set, then the TestCase will execute this step with the same logic // as a `terraform apply`. + // + // JSON Configuration Syntax can be used and is assumed whenever Config + // contains valid JSON. Config string // Check is called after the Config is applied. Use this step to diff --git a/internal/plugintest/working_dir.go b/internal/plugintest/working_dir.go index 1faeb5c7a71..041fef34efd 100644 --- a/internal/plugintest/working_dir.go +++ b/internal/plugintest/working_dir.go @@ -3,6 +3,7 @@ package plugintest import ( "bytes" "context" + "encoding/json" "errors" "fmt" "io/ioutil" @@ -14,8 +15,9 @@ import ( ) const ( - ConfigFileName = "terraform_plugin_test.tf" - PlanFileName = "tfplan" + ConfigFileName = "terraform_plugin_test.tf" + ConfigFileNameJSON = ConfigFileName + ".json" + PlanFileName = "tfplan" ) // WorkingDir represents a distinct working directory that can be used for @@ -28,6 +30,10 @@ type WorkingDir struct { // baseDir is the root of the working directory tree baseDir string + // configFilename is the full filename where the latest configuration + // was stored; empty until SetConfig is called. + configFilename string + // baseArgs is arguments that should be appended to all commands baseArgs []string @@ -83,8 +89,20 @@ func (wd *WorkingDir) GetHelper() *Helper { // Destroy to establish the configuration. Any previously-set configuration is // discarded and any saved plan is cleared. func (wd *WorkingDir) SetConfig(cfg string) error { - configFilename := filepath.Join(wd.baseDir, ConfigFileName) - err := ioutil.WriteFile(configFilename, []byte(cfg), 0700) + if wd.configFilename != "" { + err := os.Remove(wd.configFilename) + if err != nil && !os.IsNotExist(err) { + return err + } + } + + bCfg := []byte(cfg) + if json.Valid(bCfg) { + wd.configFilename = filepath.Join(wd.baseDir, ConfigFileNameJSON) + } else { + wd.configFilename = filepath.Join(wd.baseDir, ConfigFileName) + } + err := ioutil.WriteFile(wd.configFilename, bCfg, 0700) if err != nil { return err } @@ -135,17 +153,13 @@ func (wd *WorkingDir) ClearPlan() error { // Init runs "terraform init" for the given working directory, forcing Terraform // to use the current version of the plugin under test. func (wd *WorkingDir) Init() error { - if _, err := os.Stat(wd.configFilename()); err != nil { + if wd.configFilename == "" { return fmt.Errorf("must call SetConfig before Init") } return wd.tf.Init(context.Background(), tfexec.Reattach(wd.reattachInfo)) } -func (wd *WorkingDir) configFilename() string { - return filepath.Join(wd.baseDir, ConfigFileName) -} - func (wd *WorkingDir) planFilename() string { return filepath.Join(wd.baseDir, PlanFileName) }