allow TestCheckNoResourceAttr for empty containers

Stricter type handling in the new shims may add empty containers into
the state where they were previously elided. Since the detection of
missing and empty containers in the legacy state was never reliable,
allow TestCheckNoResourceAttr to succeed if the key is a container count
index, and the value is "0"
This commit is contained in:
James Bardin 2019-01-09 13:09:02 -05:00
parent c63040c737
commit 7973872524
2 changed files with 45 additions and 1 deletions

View File

@ -1026,7 +1026,20 @@ func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestChe
} }
func testCheckNoResourceAttr(is *terraform.InstanceState, name string, key string) error { func testCheckNoResourceAttr(is *terraform.InstanceState, name string, key string) error {
if _, ok := is.Attributes[key]; ok { // Empty containers may sometimes be included in the state.
// If the intent here is to check for an empty container, allow the value to
// also be "0".
emptyCheck := false
if strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%") {
emptyCheck = true
}
val, exists := is.Attributes[key]
if emptyCheck && val == "0" {
return nil
}
if exists {
return fmt.Errorf("%s: Attribute '%s' found when not expected", name, key) return fmt.Errorf("%s: Attribute '%s' found when not expected", name, key)
} }

View File

@ -1144,3 +1144,34 @@ func TestCheckResourceAttr_empty(t *testing.T) {
}) })
} }
} }
func TestCheckNoResourceAttr_empty(t *testing.T) {
s := terraform.NewState()
s.AddModuleState(&terraform.ModuleState{
Path: []string{"root"},
Resources: map[string]*terraform.ResourceState{
"test_resource": &terraform.ResourceState{
Primary: &terraform.InstanceState{
Attributes: map[string]string{
"empty_list.#": "0",
"empty_map.%": "0",
},
},
},
},
})
for _, key := range []string{
"empty_list.#",
"empty_map.%",
"missing_list.#",
"missing_map.%",
} {
t.Run(key, func(t *testing.T) {
check := TestCheckNoResourceAttr("test_resource", key)
if err := check(s); err != nil {
t.Fatal(err)
}
})
}
}