add tfdiags.GetAttribute

The only contextual information returned by the plugins in a diagnostic
is an attribute path. In order to test the conversions, we need to be
able to extract the cty.Path from a diagnostic if it exists.
This commit is contained in:
James Bardin 2018-06-29 17:04:56 -04:00 committed by Martin Atkins
parent adb88eaa16
commit 83538bbecb
2 changed files with 34 additions and 0 deletions

View File

@ -80,6 +80,19 @@ func AttributeValue(severity Severity, summary, detail string, attrPath cty.Path
} }
} }
// GetAttribute extracts an attribute cty.Path from a diagnostic if it contains
// one. Normally this is not accessed directly, and instead the config body is
// added to the Diagnostic to create a more complete message for the user. In
// some cases however, we may want to know just the name of the attribute that
// generated the Diagnostic message.
// This returns a nil cty.Path if it does not exist in the Diagnostic.
func GetAttribute(d Diagnostic) cty.Path {
if d, ok := d.(*attributeDiagnostic); ok {
return d.attrPath
}
return nil
}
type attributeDiagnostic struct { type attributeDiagnostic struct {
diagnosticBase diagnosticBase
attrPath cty.Path attrPath cty.Path

View File

@ -1,6 +1,7 @@
package tfdiags package tfdiags
import ( import (
"reflect"
"testing" "testing"
"github.com/go-test/deep" "github.com/go-test/deep"
@ -137,3 +138,23 @@ baz "b" {
t.Error(problem) t.Error(problem)
} }
} }
func TestGetAttribute(t *testing.T) {
path := cty.Path{
cty.GetAttrStep{Name: "foo"},
cty.IndexStep{Key: cty.NumberIntVal(0)},
cty.GetAttrStep{Name: "bar"},
}
d := AttributeValue(
Error,
"foo[0].bar",
"detail",
path,
)
p := GetAttribute(d)
if !reflect.DeepEqual(path, p) {
t.Fatalf("paths don't match:\nexpected: %#v\ngot: %#v", path, p)
}
}