Skip to content

Commit

Permalink
Adding ExpectKnownOutputValueAtPath state check (#266)
Browse files Browse the repository at this point in the history
  • Loading branch information
bendbennett committed Jan 15, 2024
1 parent 4e3ca3a commit d93aa82
Show file tree
Hide file tree
Showing 2 changed files with 1,849 additions and 0 deletions.
94 changes: 94 additions & 0 deletions statecheck/expect_known_output_value_at_path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package statecheck

import (
"context"
"fmt"
"reflect"

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 = expectKnownOutputValueAtPath{}

type expectKnownOutputValueAtPath struct {
outputAddress string
outputPath tfjsonpath.Path
knownValue knownvalue.Check
}

// CheckState implements the state check logic.
func (e expectKnownOutputValueAtPath) CheckState(ctx context.Context, req CheckStateRequest, resp *CheckStateResponse) {
var output *tfjson.StateOutput

if req.State == nil {
resp.Error = fmt.Errorf("state is nil")
}

if req.State.Values == nil {
resp.Error = fmt.Errorf("state does not contain any state values")
}

for address, oc := range req.State.Values.Outputs {
if e.outputAddress == address {
output = oc

break
}
}

if output == nil {
resp.Error = fmt.Errorf("%s - Output not found in state", e.outputAddress)

return
}

result, err := tfjsonpath.Traverse(output.Value, e.outputPath)

if err != nil {
resp.Error = err

return
}

if result == nil {
resp.Error = fmt.Errorf("value is null")

return
}

switch reflect.TypeOf(result).Kind() {
case reflect.Bool,
reflect.Map,
reflect.Slice,
reflect.String:
if err := e.knownValue.CheckValue(result); err != nil {
resp.Error = err

return
}
default:
errorStr := fmt.Sprintf("unrecognised output type: %T, known value type is %T", result, e.knownValue)
errorStr += "\n\nThis is an error in statecheck.ExpectKnownOutputValueAtPath.\nPlease report this to the maintainers."

resp.Error = fmt.Errorf(errorStr)

return
}
}

// ExpectKnownOutputValueAtPath returns a state check that asserts that the specified output at the given path
// has a known type and value.
func ExpectKnownOutputValueAtPath(outputAddress string, outputPath tfjsonpath.Path, knownValue knownvalue.Check) StateCheck {
return expectKnownOutputValueAtPath{
outputAddress: outputAddress,
outputPath: outputPath,
knownValue: knownValue,
}
}
Loading

0 comments on commit d93aa82

Please sign in to comment.