Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ImportStatePersist to preserve state generated by import operation #1052

Merged
merged 8 commits into from Sep 8, 2022
3 changes: 3 additions & 0 deletions .changelog/1052.txt
@@ -0,0 +1,3 @@
```release-note:enhancement
helper/resource: Add ImportStatePersist to optionally persist state generated during import
```
6 changes: 6 additions & 0 deletions helper/resource/testing.go
Expand Up @@ -564,6 +564,12 @@ type TestStep struct {
ImportStateVerify bool
ImportStateVerifyIgnore []string

// ImportStatePersist, if true, will update the persisted state with the
// state generated by the import operation (i.e., terraform import). When
// false (default) the state generated by the import operation is discarded
// at the end of the test step that is verifying import behavior.
ImportStatePersist bool

// ProviderFactories can be specified for the providers that are valid for
// this TestStep. When providers are specified at the TestStep level, all
// TestStep within a TestCase must declare providers.
Expand Down
27 changes: 19 additions & 8 deletions helper/resource/testing_new_import_state.go
Expand Up @@ -7,7 +7,7 @@ import (
"strings"

"github.com/davecgh/go-spew/spew"
testing "github.com/mitchellh/go-testing-interface"
"github.com/mitchellh/go-testing-interface"

"github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest"
Expand Down Expand Up @@ -86,20 +86,31 @@ func testStepNewImportState(ctx context.Context, t testing.T, helper *plugintest
t.Fatal("Cannot import state with no specified config")
}
}
importWd := helper.RequireNewWorkingDir(ctx, t)
defer importWd.Close()

var importWd *plugintest.WorkingDir

// Use the same working directory to persist the state from import
if step.ImportStatePersist {
importWd = wd
} else {
importWd = helper.RequireNewWorkingDir(ctx, t)
defer importWd.Close()
}

err = importWd.SetConfig(ctx, step.Config)
if err != nil {
t.Fatalf("Error setting test config: %s", err)
}

logging.HelperResourceDebug(ctx, "Running Terraform CLI init and import")

err = runProviderCommand(ctx, t, func() error {
return importWd.Init(ctx)
}, importWd, providers)
if err != nil {
t.Fatalf("Error running init: %s", err)
if !step.ImportStatePersist {
err = runProviderCommand(ctx, t, func() error {
return importWd.Init(ctx)
}, importWd, providers)
if err != nil {
t.Fatalf("Error running init: %s", err)
}
}

err = runProviderCommand(ctx, t, func() error {
Expand Down