-
Notifications
You must be signed in to change notification settings - Fork 16
statecheck: Add ExpectIdentity
state check for asserting an entire identity object
#470
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,7 @@ | ||
kind: NOTES | ||
body: This alpha pre-release contains testing utilities for managed resource identity, which can be used with `Terraform v1.12.0-alpha20250319`, to | ||
assert identity data stored during apply workflows. A managed resource in a provider can read/store identity data using the `terraform-plugin-framework@v1.15.0-alpha.1` | ||
or `terraform-plugin-sdk/v2@v2.37.0-alpha.1` Go modules. To assert identity data stored by a provider in state, use the `statecheck.ExpectIdentityValue` state check. | ||
or `terraform-plugin-sdk/v2@v2.37.0-alpha.1` Go modules. To assert identity data stored by a provider in state, use the `statecheck.ExpectIdentity` state check. | ||
time: 2025-03-25T11:59:27.455519-04:00 | ||
custom: | ||
Issue: "468" | ||
Issue: "470" |
2 changes: 1 addition & 1 deletion
2
.changes/unreleased/upcoming-stable/ENHANCEMENTS-20250325-121007.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
kind: ENHANCEMENTS | ||
body: 'statecheck: Added `ExpectIdentityValue` state check, which asserts managed resource identity data stored in state.' | ||
body: 'statecheck: Added `ExpectIdentityValue` state check, which asserts a specified attribute value of a managed resource identity in state.' | ||
time: 2025-03-25T12:10:07.55484-04:00 | ||
custom: | ||
Issue: "468" |
5 changes: 5 additions & 0 deletions
5
.changes/unreleased/upcoming-stable/ENHANCEMENTS-20250325-174504.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
kind: ENHANCEMENTS | ||
body: 'statecheck: Added `ExpectIdentity` state check, which asserts all data of a managed resource identity in state.' | ||
time: 2025-03-25T17:45:04.794886-04:00 | ||
custom: | ||
Issue: "470" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
// Copyright (c) HashiCorp, Inc. | ||
// SPDX-License-Identifier: MPL-2.0 | ||
|
||
package statecheck | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"maps" | ||
"slices" | ||
"sort" | ||
|
||
tfjson "github.com/hashicorp/terraform-json" | ||
|
||
"github.com/hashicorp/terraform-plugin-testing/knownvalue" | ||
) | ||
|
||
var _ StateCheck = expectIdentity{} | ||
|
||
type expectIdentity struct { | ||
resourceAddress string | ||
identity map[string]knownvalue.Check | ||
} | ||
|
||
// CheckState implements the state check logic. | ||
func (e expectIdentity) 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 | ||
} | ||
|
||
if resource.IdentitySchemaVersion == nil || len(resource.IdentityValues) == 0 { | ||
resp.Error = fmt.Errorf("%s - Identity not found in state. Either the resource does not support identity or the Terraform version running the test does not support identity. (must be v1.12+)", e.resourceAddress) | ||
|
||
return | ||
} | ||
|
||
if len(resource.IdentityValues) != len(e.identity) { | ||
deltaMsg := "" | ||
if len(resource.IdentityValues) > len(e.identity) { | ||
deltaMsg = createDeltaString(resource.IdentityValues, e.identity, "actual identity has extra attribute(s): ") | ||
} else { | ||
deltaMsg = createDeltaString(e.identity, resource.IdentityValues, "actual identity is missing attribute(s): ") | ||
} | ||
|
||
resp.Error = fmt.Errorf("%s - Expected %d attribute(s) in the actual identity object, got %d attribute(s): %s", e.resourceAddress, len(e.identity), len(resource.IdentityValues), deltaMsg) | ||
return | ||
} | ||
|
||
var keys []string | ||
|
||
for k := range e.identity { | ||
keys = append(keys, k) | ||
} | ||
|
||
sort.SliceStable(keys, func(i, j int) bool { | ||
return keys[i] < keys[j] | ||
}) | ||
|
||
for _, k := range keys { | ||
actualIdentityVal, ok := resource.IdentityValues[k] | ||
|
||
if !ok { | ||
resp.Error = fmt.Errorf("%s - missing attribute %q in actual identity object", e.resourceAddress, k) | ||
return | ||
} | ||
|
||
if err := e.identity[k].CheckValue(actualIdentityVal); err != nil { | ||
resp.Error = fmt.Errorf("%s - %q identity attribute: %s", e.resourceAddress, k, err) | ||
return | ||
} | ||
} | ||
} | ||
|
||
// ExpectIdentity returns a state check that asserts that the identity at the given resource matches a known object, where each | ||
// map key represents an identity attribute name. The identity in state must exactly match the given object and any missing/extra | ||
// attributes will raise a diagnostic. | ||
// | ||
// This state check can only be used with managed resources that support resource identity. Resource identity is only supported in Terraform v1.12+ | ||
func ExpectIdentity(resourceAddress string, identity map[string]knownvalue.Check) StateCheck { | ||
return expectIdentity{ | ||
resourceAddress: resourceAddress, | ||
identity: identity, | ||
} | ||
} | ||
|
||
// createDeltaString prints the map keys that are present in mapA and not present in mapB | ||
func createDeltaString[T any, V any](mapA map[string]T, mapB map[string]V, msgPrefix string) string { | ||
deltaMsg := "" | ||
|
||
deltaMap := make(map[string]T, len(mapA)) | ||
maps.Copy(deltaMap, mapA) | ||
for key := range mapB { | ||
delete(deltaMap, key) | ||
} | ||
|
||
deltaKeys := slices.Sorted(maps.Keys(deltaMap)) | ||
|
||
for i, k := range deltaKeys { | ||
if i == 0 { | ||
deltaMsg += msgPrefix | ||
} else { | ||
deltaMsg += ", " | ||
} | ||
deltaMsg += fmt.Sprintf("%q", k) | ||
} | ||
|
||
return deltaMsg | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Copyright (c) HashiCorp, Inc. | ||
// SPDX-License-Identifier: MPL-2.0 | ||
|
||
package statecheck_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/hashicorp/terraform-plugin-testing/helper/resource" | ||
"github.com/hashicorp/terraform-plugin-testing/knownvalue" | ||
"github.com/hashicorp/terraform-plugin-testing/statecheck" | ||
"github.com/hashicorp/terraform-plugin-testing/tfversion" | ||
) | ||
|
||
func ExampleExpectIdentity() { | ||
// A typical test would accept *testing.T as a function parameter, for instance `func TestSomething(t *testing.T) { ... }`. | ||
t := &testing.T{} | ||
t.Parallel() | ||
|
||
resource.Test(t, resource.TestCase{ | ||
// Resource identity support is only available in Terraform v1.12+ | ||
TerraformVersionChecks: []tfversion.TerraformVersionCheck{ | ||
tfversion.SkipBelow(tfversion.Version1_12_0), | ||
}, | ||
// Provider definition omitted. Assuming "test_resource" has an identity schema with "id" and "name" string attributes | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: `resource "test_resource" "one" {}`, | ||
ConfigStateChecks: []statecheck.StateCheck{ | ||
statecheck.ExpectIdentity( | ||
"test_resource.one", | ||
map[string]knownvalue.Check{ | ||
"id": knownvalue.StringExact("id-123"), | ||
"name": knownvalue.StringExact("John Doe"), | ||
}, | ||
), | ||
}, | ||
}, | ||
}, | ||
}) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.