Skip to content

Commit 40ec980

Browse files
authored
Merge pull request #393 from hashicorp/v2-omit-test-cleanup-when-no-state
v2: omit test cleanup when state is empty
2 parents 277c934 + b717a14 commit 40ec980

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

helper/resource/testing_new.go

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,18 @@ import (
1616
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
1717
)
1818

19-
func getState(t *testing.T, wd *tftest.WorkingDir) *terraform.State {
20-
jsonState := wd.RequireState(t)
21-
state, err := shimStateFromJson(jsonState)
22-
if err != nil {
23-
t.Fatal(err)
19+
func runPostTestDestroy(t *testing.T, c TestCase, wd *tftest.WorkingDir) error {
20+
wd.RequireDestroy(t)
21+
22+
if c.CheckDestroy != nil {
23+
statePostDestroy := getState(t, wd)
24+
25+
if err := c.CheckDestroy(statePostDestroy); err != nil {
26+
return err
27+
}
2428
}
25-
return state
29+
30+
return nil
2631
}
2732

2833
func RunNewTest(t *testing.T, c TestCase, providers map[string]*schema.Provider) {
@@ -31,15 +36,12 @@ func RunNewTest(t *testing.T, c TestCase, providers map[string]*schema.Provider)
3136
wd := acctest.TestHelper.RequireNewWorkingDir(t)
3237

3338
defer func() {
34-
wd.RequireDestroy(t)
39+
statePreDestroy := getState(t, wd)
3540

36-
if c.CheckDestroy != nil {
37-
statePostDestroy := getState(t, wd)
38-
39-
if err := c.CheckDestroy(statePostDestroy); err != nil {
40-
t.Fatal(err)
41-
}
41+
if !stateIsEmpty(statePreDestroy) {
42+
runPostTestDestroy(t, c, wd)
4243
}
44+
4345
wd.Close()
4446
}()
4547

@@ -100,6 +102,19 @@ func RunNewTest(t *testing.T, c TestCase, providers map[string]*schema.Provider)
100102
}
101103
}
102104

105+
func getState(t *testing.T, wd *tftest.WorkingDir) *terraform.State {
106+
jsonState := wd.RequireState(t)
107+
state, err := shimStateFromJson(jsonState)
108+
if err != nil {
109+
t.Fatal(err)
110+
}
111+
return state
112+
}
113+
114+
func stateIsEmpty(state *terraform.State) bool {
115+
return state.Empty() || !state.HasResources()
116+
}
117+
103118
func planIsEmpty(plan *tfjson.Plan) bool {
104119
for _, rc := range plan.ResourceChanges {
105120
if rc.Mode == tfjson.DataResourceMode {
@@ -116,6 +131,7 @@ func planIsEmpty(plan *tfjson.Plan) bool {
116131
}
117132
return true
118133
}
134+
119135
func testIDRefresh(c TestCase, t *testing.T, wd *tftest.WorkingDir, step TestStep, r *terraform.ResourceState) error {
120136
spewConf := spew.NewDefaultConfig()
121137
spewConf.SortKeys = true

0 commit comments

Comments
 (0)