hashicorp / terraform-plugin-testing

Module for testing Terraform providers
Mozilla Public License 2.0
44 stars 11 forks source link

FR: utilize slices and maps Golang packages for testing helper functions #322

Open mschuchard opened 2 months ago

mschuchard commented 2 months ago

With the advent of the slices and maps packages promotion from experimental to core in Go 1.21, and generics in 1.17, we now have e.g. https://pkg.go.dev/slices#Equal. Could we have helper functions as part of the type https://pkg.go.dev/github.com/hashicorp/terraform-plugin-testing/helper/resource#TestCheckFunc that e.g. ascertain list and set equality instead of using the cumbersome https://pkg.go.dev/github.com/hashicorp/terraform-plugin-testing/helper/resource#example-TestCheckResourceAttr-TypeListAttribute?

There are for sure other examples, but I feel the above is demonstrative of what I am trying to communicate.

bendbennett commented 2 months ago

Hi @mschuchard 👋

One option that is available for verifying list and set equality of values in state is to use state checks with the knownvalue package introduced in v1.7.0.

For example, to perform the equivalent check to the list equality check that you linked to, you could use the following:

package provider

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/tfjsonpath"
)

func TestExpectKnownValue_CheckState_List(t *testing.T) {
    t.Parallel()

    resource.Test(t, resource.TestCase{
        // Provider definition omitted.
        Steps: []resource.TestStep{
            {
                // Example resource containing a computed list attribute named "list_attribute"
                Config: `resource "example_thing" "test" {}`,
                ConfigStateChecks: []statecheck.StateCheck{
                    statecheck.ExpectKnownValue(
                        "example_thing.test",
                        tfjsonpath.New("list_attribute"),
                        knownvalue.ListExact([]knownvalue.Check{
                            knownvalue.StringExact("value1"),
                            knownvalue.StringExact("value2"),
                            knownvalue.StringExact("value3"),
                        }),
                    ),
                },
            },
        },
    })
}

The acceptance testing documentation contains some information regarding state checks, and plan checks which can be used in conjunction with known value checks.