-
Notifications
You must be signed in to change notification settings - Fork 12
/
expect_known_value.go
84 lines (61 loc) · 1.91 KB
/
expect_known_value.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package statecheck
import (
"context"
"fmt"
tfjson "github.com/hashicorp/terraform-json"
"github.com/hashicorp/terraform-plugin-testing/knownvalue"
"github.com/hashicorp/terraform-plugin-testing/tfjsonpath"
)
// Resource State Check
var _ StateCheck = expectKnownValue{}
type expectKnownValue struct {
resourceAddress string
attributePath tfjsonpath.Path
knownValue knownvalue.Check
}
// CheckState implements the state check logic.
func (e expectKnownValue) CheckState(ctx context.Context, req CheckStateRequest, resp *CheckStateResponse) {
var resource *tfjson.StateResource
if req.State == nil {
resp.Error = fmt.Errorf("state is nil")
return
}
if req.State.Values == nil {
resp.Error = fmt.Errorf("state does not contain any state values")
return
}
if req.State.Values.RootModule == nil {
resp.Error = fmt.Errorf("state does not contain a root module")
return
}
for _, r := range req.State.Values.RootModule.Resources {
if e.resourceAddress == r.Address {
resource = r
break
}
}
if resource == nil {
resp.Error = fmt.Errorf("%s - Resource not found in state", e.resourceAddress)
return
}
result, err := tfjsonpath.Traverse(resource.AttributeValues, e.attributePath)
if err != nil {
resp.Error = err
return
}
if err := e.knownValue.CheckValue(result); err != nil {
resp.Error = fmt.Errorf("error checking value for attribute at path: %s.%s, err: %s", e.resourceAddress, e.attributePath.String(), err)
return
}
}
// ExpectKnownValue returns a state check that asserts that the specified attribute at the given resource
// has a known type and value.
func ExpectKnownValue(resourceAddress string, attributePath tfjsonpath.Path, knownValue knownvalue.Check) StateCheck {
return expectKnownValue{
resourceAddress: resourceAddress,
attributePath: attributePath,
knownValue: knownValue,
}
}