Skip to content
30 changes: 24 additions & 6 deletions brokerpaktestframework/terraform_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,23 +134,41 @@ type TFStateValue struct {
// SetTFState set the Terraform State in a JSON file.
func (p TerraformMock) SetTFState(values []TFStateValue) error {
var outputs = make(map[string]struct {
Type string `json:"type"`
Value any `json:"value"`
Type json.RawMessage `json:"type"`
Value any `json:"value"`
})

for _, value := range values {
outputs[value.Name] = struct {
Type string `json:"type"`
Value any `json:"value"`
Type json.RawMessage `json:"type"`
Value any `json:"value"`
}{
Type: value.Type,
Type: normalizeOutputType(value.Type),
Value: value.Value,
}
}

return p.setTFStateFile(workspace.Tfstate{
Version: 4,
TerraformVersion: p.Version,
Outputs: outputs})
Outputs: outputs,
})
}

func normalizeOutputType(t string) json.RawMessage {
s := strings.TrimSpace(t)
if s == "" {
return json.RawMessage(`"string"`)
}

if (strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]")) ||
(strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")) ||
(strings.HasPrefix(s, "\"") && strings.HasSuffix(s, "\"")) {
return json.RawMessage(s)
}

b, _ := json.Marshal(s)
return json.RawMessage(b)
}

// ReturnTFState set the Terraform State in a JSON file.
Expand Down
4 changes: 2 additions & 2 deletions pkg/providers/tf/workspace/tfstate.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ type Tfstate struct {
Version int `json:"version"`
TerraformVersion string `json:"terraform_version"`
Outputs map[string]struct {
Type string `json:"type"`
Value any `json:"value"`
Type json.RawMessage `json:"type"`
Value any `json:"value"`
} `json:"outputs"`
}

Expand Down
19 changes: 19 additions & 0 deletions pkg/providers/tf/workspace/tfstate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package workspace

import "fmt"
import "testing"

func ExampleNewTfstate_good() {
state := `{
Expand Down Expand Up @@ -110,3 +111,21 @@ func ExampleTfstate_GetOutputs() {

// Output: map[hostname:somehost]
}

func TestNewTfstate_AllowsArrayOutputType(t *testing.T) {
state := []byte(`{
"version": 4,
"terraform_version": "1.8.2",
"outputs": {
"list_output_causes_error": {
"value": [],
"type": ["list", "string"]
}
}
}`)

_, err := NewTfstate(state)
if err != nil {
t.Fatalf("unexpected error when output.type is an array: %v", err)
}
}
Loading