const ( EnvTfAcc = "TF_ACC" EnvTfAccProviderHost = "TF_ACC_PROVIDER_HOST" EnvTfAccProviderNamespace = "TF_ACC_PROVIDER_NAMESPACE" )
Environment variables for acceptance testing. Additional environment variable constants can be found in the internal/plugintest package.
Deprecated: Use EnvTfAcc instead.
UniqueIDSuffixLength is the string length of the suffix generated by PrefixedUniqueId. This can be used by length validation functions to ensure prefixes are the correct length for the target field.
Deprecated: Copy this value to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/id.UniqueSuffixLength.
UniqueIdPrefix is a string prefix automatically added to return values of the UniqueId function.
Deprecated: Copy this value to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/id.UniquePrefix.
This section is empty.
AddTestSweepers function adds a given name and Sweeper configuration pair to the internal sweeperFuncs map. Invoke this function to register a resource sweeper to be available for running when the -sweep flag is used with `go test`. Sweeper names must be unique to help ensure a given sweeper is only ran once per run.
func ParallelTest(t testing.T, c TestCase)
ParallelTest performs an acceptance test on a resource, allowing concurrency with other ParallelTest. The number of concurrent tests is controlled by the "go test" command -parallel flag.
Tests will fail if they do not properly handle conditions to allow multiple tests to occur against the same resource or service (e.g. random naming).
Test() function requirements and documentation also apply to this function.
Helper for a resource to generate a unique identifier w/ given prefix
After the prefix, the ID consists of an incrementing 26 digit value (to match previous timestamp output). After the prefix, the ID consists of a timestamp and an incrementing 8 hex digit value The timestamp means that multiple IDs created with the same prefix will sort in the order of their creation, even across multiple terraform executions, as long as the clock is not turned back between calls, and as long as any given terraform execution generates fewer than 4 billion IDs.
Deprecated: Copy this function to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/id.PrefixedUnique.
Retry is a basic wrapper around StateChangeConf that will just retry a function until it no longer returns an error.
Deprecated: Please use RetryContext to ensure proper plugin shutdown
RetryContext is a basic wrapper around StateChangeConf that will just retry a function until it no longer returns an error.
Cancellation from the passed in context will propagate through to the underlying StateChangeConf
Deprecated: Copy this function to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.RetryContext.
Test performs an acceptance test on a resource.
Tests are not run unless an environmental variable "TF_ACC" is set to some non-empty value. This is to avoid test cases surprising a user by creating real resources.
Use the ParallelTest() function to automatically set (*testing.T).Parallel() to enable testing concurrency. Use the UnitTest() function to automatically set the TestCase type IsUnitTest field.
This function will automatically find or install Terraform CLI into a temporary directory, based on the following behavior:
Refer to the Env prefixed constants for additional details about these environment variables, and others, that control testing functionality.
func TestMain ¶func TestMain(m interface { Run() int })
TestMain adds sweeper functionality to the "go test" command, otherwise tests are executed as normal. Most provider acceptance tests are written using the Test() function of this package, which imposes its own requirements and Terraform CLI behavior. Refer to that function's documentation for additional details.
Sweepers enable infrastructure cleanup functions to be included with resource definitions, typically so developers can remove all resources of that resource type from testing infrastructure in case of failures that prevented the normal resource destruction behavior of acceptance tests. Use the AddTestSweepers() function to configure available sweepers.
Sweeper flags added to the "go test" command:
-sweep: Comma-separated list of locations/regions to run available sweepers. -sweep-allow-failures: Enable to allow other sweepers to run after failures. -sweep-run: Comma-separated list of resource type sweepers to run. Defaults to all sweepers.
Refer to the Env prefixed constants for environment variables that further control testing functionality.
Helper for a resource to generate a unique identifier w/ default prefix
Deprecated: Copy this function to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/id.Unique.
UnitTest is a helper to force the acceptance testing harness to run in the normal unit test suite. This should only be used for resource that don't have any external dependencies.
Test() function requirements and documentation also apply to this function.
AdditionalCLIOptions allows an intentionally limited set of options to be passed to the Terraform CLI when executing test steps.
type ApplyOptions struct { AllowDeferral bool }
ApplyOptions represents options to be passed to the `terraform apply` command.
type CheckResourceAttrWithFunc func(value string) error
CheckResourceAttrWithFunc is the callback type used to apply a custom checking logic when using TestCheckResourceAttrWith and a value is found for the given name and key.
When this function returns an error, TestCheckResourceAttrWith will fail the check.
An experimental interface exists to potentially replace the CheckResourceAttrWithFunc functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckResourceAttrWith with that experimental interface, by using statecheck.ExpectKnownValue in combination with [knownvalue.StringRegexp]:
package example_test import ( "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/statecheck" "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" ) func TestExpectKnownValue_CheckState_String_Custom(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed string attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.StringRegexp(regexp.MustCompile("str")), }, }, }, }) }
ConfigPlanChecks defines the different points in a Config TestStep when plan checks can be run.
ErrorCheckFunc is a function providers can use to handle errors.
type ExternalProvider struct { VersionConstraint string Source string }
ExternalProvider holds information about third-party providers that should be downloaded by Terraform as part of running the test step.
ImportPlanChecks defines the different points in an Import TestStep when plan checks can be run.
ImportStateCheckFunc is the check function for ImportState tests
ImportStateIdFunc is an ID generation function to help with complex ID generation for ImportState tests.
type ImportStateKind byte
const ( ImportCommandWithID ImportStateKind = iota ImportBlockWithID ImportBlockWithResourceIdentity )
type NotFoundError struct { LastError error LastRequest interface{} LastResponse interface{} Message string Retries int }
NotFoundError represents when a StateRefreshFunc returns a nil result during a StateChangeConf waiter method and that StateChangeConf is configured for specific targets.
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.NotFoundError.
Error returns the Message string, if non-empty, or a string indicating the resource could not be found.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.NotFoundError.
Unwrap returns the LastError, compatible with errors.Unwrap.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.NotFoundError.
type PlanOptions struct { AllowDeferral bool NoRefresh bool }
PlanOptions represents options to be passed to the `terraform plan` command.
RefreshPlanChecks defines the different points in a Refresh TestStep when plan checks can be run.
type RetryError struct { Err error Retryable bool }
RetryError is the required return type of RetryFunc. It forces client code to choose whether or not a given error is retryable.
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.RetryError.
NonRetryableError is a helper to create a RetryError that's _not_ retryable from a given error. To prevent logic errors, will return an error when passed a nil error.
Deprecated: Copy this function to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.NonRetryableError.
RetryableError is a helper to create a RetryError that's retryable from a given error. To prevent logic errors, will return an error when passed a nil error.
Deprecated: Copy this function to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.RetryableError.
Unwrap returns the Err, compatible with errors.Unwrap.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.RetryError.
RetryFunc is the function retried until it succeeds.
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.RetryFunc.
StateChangeConf is the configuration struct used for `WaitForState`.
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.StateChangeConf.
WaitForState watches an object and waits for it to achieve the state specified in the configuration using the specified Refresh() func, waiting the number of seconds specified in the timeout configuration.
Deprecated: Please use WaitForStateContext to ensure proper plugin shutdown
WaitForStateContext watches an object and waits for it to achieve the state specified in the configuration using the specified Refresh() func, waiting the number of seconds specified in the timeout configuration.
If the Refresh function returns an error, exit immediately with that error.
If the Refresh function returns a state other than the Target state or one listed in Pending, return immediately with an error.
If the Timeout is exceeded before reaching the Target state, return an error.
Otherwise, the result is the result of the first call to the Refresh function to reach the target state.
Cancellation from the passed in context will cancel the refresh loop ¶Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.StateChangeConf.
type StateRefreshFunc func() (result interface{}, state string, err error)
StateRefreshFunc is a function type used for StateChangeConf that is responsible for refreshing the item being watched for a state change.
It returns three results. `result` is any object that will be returned as the final object after waiting for state change. This allows you to return the final updated object, for example an EC2 instance after refreshing it. A nil result represents not found.
`state` is the latest state of that object. And `err` is any error that may have happened while refreshing the state.
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.StateRefreshFunc.
SweeperFunc is a signature for a function that acts as a sweeper. It accepts a string for the region that the sweeper is to be ran in. This function must be able to construct a valid client for that region.
TestCase is a single acceptance test case used to test the apply/destroy lifecycle of a resource in a specific configuration.
When the destroy plan is executed, the config from the last TestStep is used to plan it.
Refer to the Env prefixed constants for environment variables that further control testing functionality.
TestCheckFunc is the callback type used with acceptance tests to check the state of a resource. The state passed in is the latest state known, or in the case of being after a destroy, it is the last known state when it was created.
ComposeAggregateTestCheckFunc lets you compose multiple TestCheckFuncs into a single TestCheckFunc.
As a user testing their provider, this lets you decompose your checks into smaller pieces more easily.
Unlike ComposeTestCheckFunc, ComposeAggergateTestCheckFunc runs _all_ of the TestCheckFuncs and aggregates failures.
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field. // Any TestCheckFunc and number of TestCheckFunc may be used within the // function parameters. Any errors are combined and displayed together. resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("example_thing.test", "example_attribute1", "one"), resource.TestCheckResourceAttr("example_thing.test", "example_attribute2", "two"), ) }
ComposeTestCheckFunc lets you compose multiple TestCheckFuncs into a single TestCheckFunc.
As a user testing their provider, this lets you decompose your checks into smaller pieces more easily.
ComposeTestCheckFunc returns immediately on the first TestCheckFunc error. To aggregrate all errors, use ComposeAggregateTestCheckFunc instead.
TestCheckModuleNoResourceAttr - as per TestCheckNoResourceAttr but with support for non-root modules
Deprecated: This functionality is deprecated without replacement. The terraform-plugin-testing Go module is intended for provider testing, which should always be possible within the root module of a configuration. This functionality is a carryover of when this code was used within Terraform core to test both providers and modules. Modern testing implementations to verify interactions between modules should be tested in Terraform core or using tooling outside this Go module.
TestCheckModuleResourceAttr - as per TestCheckResourceAttr but with support for non-root modules
Deprecated: This functionality is deprecated without replacement. The terraform-plugin-testing Go module is intended for provider testing, which should always be possible within the root module of a configuration. This functionality is a carryover of when this code was used within Terraform core to test both providers and modules. Modern testing implementations to verify interactions between modules should be tested in Terraform core or using tooling outside this Go module.
TestCheckModuleResourceAttrPair - as per TestCheckResourceAttrPair but with support for non-root modules
Deprecated: This functionality is deprecated without replacement. The terraform-plugin-testing Go module is intended for provider testing, which should always be possible within the root module of a configuration. This functionality is a carryover of when this code was used within Terraform core to test both providers and modules. Modern testing implementations to verify interactions between modules should be tested in Terraform core or using tooling outside this Go module.
TestCheckModuleResourceAttrPtr - as per TestCheckResourceAttrPtr but with support for non-root modules
Deprecated: This functionality is deprecated without replacement. The terraform-plugin-testing Go module is intended for provider testing, which should always be possible within the root module of a configuration. This functionality is a carryover of when this code was used within Terraform core to test both providers and modules. Modern testing implementations to verify interactions between modules should be tested in Terraform core or using tooling outside this Go module.
TestCheckModuleResourceAttrSet - as per TestCheckResourceAttrSet but with support for non-root modules
Deprecated: This functionality is deprecated without replacement. The terraform-plugin-testing Go module is intended for provider testing, which should always be possible within the root module of a configuration. This functionality is a carryover of when this code was used within Terraform core to test both providers and modules. Modern testing implementations to verify interactions between modules should be tested in Terraform core or using tooling outside this Go module.
TestCheckNoResourceAttr ensures no value exists in the state for the given name and key combination. The opposite of this TestCheckFunc is TestCheckResourceAttrSet. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the following special key syntax to inspect underlying values of a list or map attribute:
While it is possible to check nested attributes under list and map attributes using the special key syntax, checking a list, map, or set attribute directly is not supported. Use TestCheckResourceAttr with the special .# or .% key syntax for those situations instead.
An experimental interface exists to potentially replace the TestCheckNoResourceAttr functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckNoResourceAttr with that experimental interface, by using statecheck.ExpectKnownValue with [knownvalue.Null]:
package example_test import ( "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/statecheck" "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" ) func TestExpectKnownValue_CheckState_AttributeNull(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed attribute named "computed_attribute" that has a null value Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.Null(), ), }, }, }, }) }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_string_attribute = "test-value" // } // // The following TestCheckNoResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckNoResourceAttr("example_thing.test", "non_existent_attribute") }
TestCheckOutput checks an output in the Terraform configuration
An experimental interface exists to potentially replace the TestCheckOutput functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckOutput with that experimental interface, by using statecheck.ExpectKnownOutputValue:
package example_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 TestExpectKnownOutputValue_CheckState_Bool(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ TerraformVersionChecks: []tfversion.TerraformVersionCheck{ tfversion.SkipBelow(tfversion.Version1_8_0), }, // Provider definition omitted. Steps: []resource.TestStep{ { // Example provider containing a provider-defined function named "bool" Config: `output "test" { value = provider::example::bool(true) }`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownOutputValue("test", knownvalue.Bool(true)), }, }, }, }) }
An experimental interface exists to potentially replace the TestCheckOutput functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckOutput with that experimental interface, by using statecheck.ExpectKnownOutputValueAtPath:
package example_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/tfjsonpath" ) func TestExpectKnownOutputValueAtPath_CheckState_Bool(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed boolean attribute named "computed_attribute" Config: `resource "test_resource" "one" {} // Generally, it is not necessary to use an output to test a resource attribute, // the resource attribute should be tested directly instead, by inspecting the // value of the resource attribute. For instance: // // ConfigStateChecks: []statecheck.StateCheck{ // statecheck.ExpectKnownValue( // "test_resource.one", // tfjsonpath.New("computed_attribute"), // knownvalue.Bool(true), // ), // }, // // This is only shown as an example. output test_resource_one_output { value = test_resource.one }`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownOutputValueAtPath( "test_resource_one_output", tfjsonpath.New("computed_attribute"), knownvalue.Bool(true), ), }, }, }, }) }
TestCheckResourceAttr ensures a specific value is stored in state for the given name and key combination. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the following special key syntax to inspect list, map, and set attributes:
The value parameter is the stringified data to check at the given key. Use the following attribute type rules to set the value:
An experimental interface exists to potentially replace the TestCheckResourceAttr functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckResourceAttr with that experimental interface, by using statecheck.ExpectKnownValue:
package example_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/tfjsonpath" ) func TestExpectKnownValue_CheckState_Bool(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed boolean attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.Bool(true), ), }, }, }, }) }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_bool_attribute = true // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckResourceAttr("example_thing.test", "example_bool_attribute", "true") }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_float_attribute = 1.2 // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckResourceAttr("example_thing.test", "example_float_attribute", "1.2") }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_int_attribute = 123 // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckResourceAttr("example_thing.test", "example_int_attribute", "123") }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_list_attribute = ["value1", "value2", "value3"] // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. // Verify the list attribute contains 3 and only 3 elements resource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.#", "3") // Verify each list attribute element value resource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.0", "value1") resource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.1", "value2") resource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.2", "value3") }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_list_block { // example_string_attribute = "test-nested-value" // } // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. // Verify the list block contains 1 and only 1 definition resource.TestCheckResourceAttr("example_thing.test", "example_list_block.#", "1") // Verify a first list block attribute value resource.TestCheckResourceAttr("example_thing.test", "example_list_block.0.example_string_attribute", "test-nested-value") }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_map_attribute = { // key1 = "value1" // key2 = "value2" // key3 = "value3" // } // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. // Verify the map attribute contains 3 and only 3 elements resource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.%", "3") // Verify each map attribute element value resource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.key1", "value1") resource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.key2", "value2") resource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.key3", "value3") }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_string_attribute = "test-value" // } // // The following TestCheckResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckResourceAttr("example_thing.test", "example_string_attribute", "test-value") }
func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc
TestCheckResourceAttrPair ensures value equality in state between the first given name and key combination and the second name and key combination. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The first and second names may use any combination of managed resources and/or data sources.
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the following special key syntax to inspect list, map, and set attributes:
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test1" { // example_string_attribute = "test-value" // } // // resource "example_thing" "test2" { // example_string_attribute = example_thing.test1.example_string_attribute // } // // The following TestCheckResourceAttrPair can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckResourceAttrPair( "example_thing.test1", "example_string_attribute", "example_thing.test2", "example_string_attribute", ) }
TestCheckResourceAttrPtr is like TestCheckResourceAttr except the value is a pointer so that it can be updated while the test is running. It will only be dereferenced at the point this step is run.
Refer to the TestCheckResourceAttr documentation for more information about setting the name, key, and value parameters.
TestCheckResourceAttrSet ensures any value exists in the state for the given name and key combination. The opposite of this TestCheckFunc is TestCheckNoResourceAttr. State value checking is only recommended for testing Computed attributes and attribute defaults.
Use this as a last resort when a more specific TestCheckFunc cannot be implemented, such as:
For managed resources, the name parameter is combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the following special key syntax to inspect underlying values of a list or map attribute:
While it is possible to check nested attributes under list and map attributes using the special key syntax, checking a list, map, or set attribute directly is not supported. Use TestCheckResourceAttr with the special .# or .% key syntax for those situations instead.
An experimental interface exists to potentially replace the TestCheckResourceAttrSet functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckResourceAttrSet with that experimental interface, by using [ExpectKnownValue] with [knownvalue.NotNull]:
package example_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/tfjsonpath" ) func TestExpectKnownValue_CheckState_AttributeFound(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.NotNull(), ), }, }, }, }) }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_string_attribute = "test-value" // } // // The following TestCheckResourceAttrSet can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckResourceAttrSet("example_thing.test", "example_string_attribute") }
TestCheckResourceAttrWith ensures a value stored in state for the given name and key combination, is checked against a custom logic. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the following special key syntax to inspect list, map, and set attributes:
The checkValueFunc parameter is a CheckResourceAttrWithFunc, and it's provided with the attribute value to apply a custom checking logic, if it was found in the state. The function must return an error for the check to fail, or `nil` to succeed.
An experimental interface exists to potentially replace the TestCheckResourceAttrWith functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckResourceAttrWith with that experimental interface, by using statecheck.ExpectKnownValue in combination with [knownvalue.StringRegexp]:
package example_test import ( "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/statecheck" "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" ) func TestExpectKnownValue_CheckState_String_Custom(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed string attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.StringRegexp(regexp.MustCompile("str")), }, }, }, }) }
package main import ( "fmt" "strconv" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_int_attribute = 10 // } // // The following TestCheckResourceAttrWith can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. // Verify the attribute value is an integer, and it's between 5 (included) and 20 (excluded) resource.TestCheckResourceAttrWith("example_thing.test", "example_string_attribute", func(value string) error { valueInt, err := strconv.Atoi(value) if err != nil { return err } if valueInt < 5 && valueInt >= 20 { return fmt.Errorf("should be between 5 and 20") } return nil }) }
package main import ( "fmt" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_string_attribute = "Very long string..." // } // // The following TestCheckResourceAttrWith can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. // Verify the attribute value string length is above 1000 resource.TestCheckResourceAttrWith("example_thing.test", "example_string_attribute", func(value string) error { if len(value) <= 1000 { return fmt.Errorf("should be longer than 1000 characters") } return nil }) }
TestCheckTypeSetElemAttr ensures a specific value is stored in state for the given name and key combination under a list or set. Use this TestCheckFunc in preference over non-set variants to simplify testing code and ensure compatibility with indicies, which can easily change with schema changes. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is a combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the sentinel value '*' to replace the element indexing into a list or set. The sentinel value can be used for each list or set index, if there are multiple lists or sets in the attribute path.
The value parameter is the stringified data to check at the given key. Use the following attribute type rules to set the value:
An experimental interface exists to potentially replace the TestCheckTypeSetElemAttr functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckTypeSetElemAttr with that experimental interface, by using statecheck.ExpectKnownValue in combination with [knownvalue.SetExact]:
package example_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/tfjsonpath" ) func TestExpectKnownValue_CheckState_Set(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed set attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.SetExact([]knownvalue.Check{ knownvalue.StringExact("value2"), knownvalue.StringExact("value1"), }), ), }, }, }, }) }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_set_attribute = ["value1", "value2", "value3"] // } // // The following TestCheckTypeSetElemAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckTypeSetElemAttr("example_thing.test", "example_set_attribute.*", "value1") resource.TestCheckTypeSetElemAttr("example_thing.test", "example_set_attribute.*", "value2") resource.TestCheckTypeSetElemAttr("example_thing.test", "example_set_attribute.*", "value3") }
func TestCheckTypeSetElemAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc
TestCheckTypeSetElemAttrPair ensures value equality in state between the first given name and key combination and the second name and key combination. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is a combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The first and second names may use any combination of managed resources and/or data sources.
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the sentinel value '*' to replace the element indexing into a list or set. The sentinel value can be used for each list or set index, if there are multiple lists or sets in the attribute path.
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // data "example_lookup" "test" { // example_string_attribute = "test-value" // } // // resource "example_thing" "test" { // example_set_attribute = [ // data.example_lookup.test.example_string_attribute, // "another-test-value", // ] // } // // The following TestCheckTypeSetElemAttrPair can be written to assert // against the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckTypeSetElemAttrPair( "example_thing.test", "example_set_attribute.*", "data.example_lookup.test", "example_string_attribute", ) }
TestCheckTypeSetElemNestedAttrs ensures a subset map of values is stored in state for the given name and key combination of attributes nested under a list or set block. Use this TestCheckFunc in preference over non-set variants to simplify testing code and ensure compatibility with indicies, which can easily change with schema changes. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is a combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the sentinel value '*' to replace the element indexing into a list or set. The sentinel value can be used for each list or set index, if there are multiple lists or sets in the attribute path.
The values parameter is the map of attribute names to attribute values expected to be nested under the list or set.
You may check for unset nested attributes, however this will also match keys set to an empty string. Use a map with at least 1 non-empty value.
map[string]string{ "key1": "value", "key2": "", }
If the values map is not granular enough, it is possible to match an element you were not intending to in the set. Provide the most complete mapping of attributes possible to be sure the unique element exists.
An experimental interface exists to potentially replace the TestCheckTypeSetElemNestedAttrs functionality in the future and feedback would be appreciated. This example performs the same check as TestCheckTypeSetElemNestedAttrs with that experimental interface, by using statecheck.ExpectKnownValue in combination with [knownvalue.SetPartial]:
package example_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/tfjsonpath" ) func TestExpectKnownValue_CheckState_SetPartial(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed set attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.SetPartial([]knownvalue.Check{ knownvalue.StringExact("value2"), }), ), }, }, }, }) }
package main import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_set_block { // key1 = "value1a" // key2 = "value2a" // key3 = "value3a" // } // // example_set_block { // key1 = "value1b" // key2 = "value2b" // key3 = "value3b" // } // } // // The following TestCheckTypeSetElemNestedAttrs can be written to assert // against the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestCheckTypeSetElemNestedAttrs( "example_thing.test", "example_set_block.*", map[string]string{ "key1": "value1a", "key2": "value2a", "key3": "value3a", }, ) resource.TestCheckTypeSetElemNestedAttrs( "example_thing.test", "example_set_block.*", map[string]string{ "key1": "value1b", "key2": "value2b", "key3": "value3b", }, ) }
TestMatchOutput ensures a value matching a regular expression is stored in state for the given name. State value checking is only recommended for testing Computed attributes and attribute defaults.
An experimental interface exists to potentially replace the TestMatchOutput functionality in the future and feedback would be appreciated. This example performs the same check as TestMatchOutput with that experimental interface, by using statecheck.ExpectKnownOutputValueAtPath in combination with [knownvalue.StringRegexp]:
package example_test import ( "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/statecheck" "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" ) func TestExpectKnownOutputValueAtPath_CheckState_String_Custom(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed string attribute named "computed_attribute" Config: `resource "test_resource" "one" {} // Generally, it is not necessary to use an output to test a resource attribute, // the resource attribute should be tested directly instead, by inspecting the // value of the resource attribute. For instance: // // ConfigStateChecks: []statecheck.StateCheck{ // statecheck.ExpectKnownValue( // "test_resource.one", // tfjsonpath.New("computed_attribute"), // knownvalue.StringRegexp(regexp.MustCompile("str")), // ), // }, // // This is only shown as an example. output test_resource_one_output { value = test_resource.one }`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownOutputValueAtPath( "test_resource_one_output", tfjsonpath.New("computed_attribute"), knownvalue.StringRegexp(regexp.MustCompile("str"), ), }, }, }, }) }
TestMatchResourceAttr ensures a value matching a regular expression is stored in state for the given name and key combination. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the following special key syntax to inspect list, map, and set attributes:
The value parameter is a compiled regular expression. A typical pattern is using the regexp.MustCompile() function, which will automatically ensure the regular expression is supported by the Go regular expression handlers during compilation.
An experimental interface exists to potentially replace the TestMatchResourceAttr functionality in the future and feedback would be appreciated. This example performs the same check as TestMatchResourceAttr with that experimental interface, by using statecheck.ExpectKnownValue in combination with [knownvalue.StringRegexp]:
package example_test import ( "testing" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/statecheck" "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" ) func TestExpectKnownValue_CheckState_String_Custom(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a computed string attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("computed_attribute"), knownvalue.StringRegexp(regexp.MustCompile("str")), }, }, }, }) }
package main import ( "regexp" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_string_attribute = "test-value" // } // // The following TestMatchResourceAttr can be written to assert against // the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestMatchResourceAttr("example_thing.test", "example_string_attribute", regexp.MustCompile(`^test-`)) }
TestMatchTypeSetElemNestedAttrs ensures a subset map of values, compared by regular expressions, is stored in state for the given name and key combination of attributes nested under a list or set block. Use this TestCheckFunc in preference over non-set variants to simplify testing code and ensure compatibility with indicies, which can easily change with schema changes. State value checking is only recommended for testing Computed attributes and attribute defaults.
For managed resources, the name parameter is a combination of the resource type, a period (.), and the name label. The name for the below example configuration would be "myprovider_thing.example".
resource "myprovider_thing" "example" { ... }
For data sources, the name parameter is a combination of the keyword "data", a period (.), the data source type, a period (.), and the name label. The name for the below example configuration would be "data.myprovider_thing.example".
data "myprovider_thing" "example" { ... }
The key parameter is an attribute path in Terraform CLI 0.11 and earlier "flatmap" syntax. Keys start with the attribute name of a top-level attribute. Use the sentinel value '*' to replace the element indexing into a list or set. The sentinel value can be used for each list or set index, if there are multiple lists or sets in the attribute path.
The values parameter is the map of attribute names to regular expressions for matching attribute values expected to be nested under the list or set.
You may check for unset nested attributes, however this will also match keys set to an empty string. Use a map with at least 1 non-empty value.
map[string]*regexp.Regexp{ "key1": regexp.MustCompile(`^value`), "key2": regexp.MustCompile(`^$`), }
If the values map is not granular enough, it is possible to match an element you were not intending to in the set. Provide the most complete mapping of attributes possible to be sure the unique element exists.
If the values map is not granular enough, it is possible to match an element you were not intending to in the set. Provide the most complete mapping of attributes possible to be sure the unique element exists.
An experimental interface exists to potentially replace the TestMatchTypeSetElemNestedAttrs functionality in the future and feedback would be appreciated. This example performs the same check as TestMatchTypeSetElemNestedAttrs with that experimental interface, by using statecheck.ExpectKnownValue in combination with [knownvalue.SetExact], with a nested [knownvalue.StringRegexp]:
package example_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/tfjsonpath" ) func TestExpectKnownValue_CheckState_SetNestedBlock_Custom(t *testing.T) { t.Parallel() resource.Test(t, resource.TestCase{ // Provider definition omitted. Steps: []resource.TestStep{ { // Example resource containing a set nested block name "block" which contains a computed string attribute named "computed_attribute" Config: `resource "test_resource" "one" {}`, ConfigStateChecks: []statecheck.StateCheck{ statecheck.ExpectKnownValue( "test_resource.one", tfjsonpath.New("block"), knownvalue.SetExact([]knownvalue.Check{ knownvalue.MapExact(map[string]knownvalue.Check{ "computed_attribute": knownvalue.StringRegexp(regexp.MustCompile("str")), }), knownvalue.MapExact(map[string]knownvalue.Check{ "computed_attribute": knownvalue.StringRegexp(regexp.MustCompile("rts")), }), }), ), }, }, }, }) }
package main import ( "regexp" "github.com/hashicorp/terraform-plugin-testing/helper/resource" ) func main() { // This function is typically implemented in a TestStep type Check field, // wrapped with ComposeAggregateTestCheckFunc to combine results from // multiple checks. // // Given the following example configuration: // // resource "example_thing" "test" { // example_set_block { // key1 = "value1a" // key2 = "value2a" // key3 = "value3a" // } // // example_set_block { // key1 = "value1b" // key2 = "value2b" // key3 = "value3b" // } // } // // The following TestMatchTypeSetElemNestedAttrs can be written to assert // against the expected state values. // // NOTE: State value checking is only necessary for Computed attributes, // as the testing framework will automatically return test failures // for configured attributes that mismatch the saved state, however // this configuration and test is shown for illustrative purposes. resource.TestMatchTypeSetElemNestedAttrs( "example_thing.test", "example_set_block.*", map[string]*regexp.Regexp{ "key1": regexp.MustCompile(`1a$`), "key2": regexp.MustCompile(`2a$`), "key3": regexp.MustCompile(`3a$`), }, ) resource.TestMatchTypeSetElemNestedAttrs( "example_thing.test", "example_set_block.*", map[string]*regexp.Regexp{ "key1": regexp.MustCompile(`1b$`), "key2": regexp.MustCompile(`2b$`), "key3": regexp.MustCompile(`3b$`), }, ) }
TestModuleMatchResourceAttr - as per TestMatchResourceAttr but with support for non-root modules
Deprecated: This functionality is deprecated without replacement. The terraform-plugin-testing Go module is intended for provider testing, which should always be possible within the root module of a configuration. This functionality is a carryover of when this code was used within Terraform core to test both providers and modules. Modern testing implementations to verify interactions between modules should be tested in Terraform core or using tooling outside this Go module.
TestStep is a single apply sequence of a test, done within the context of a state.
Multiple TestSteps can be sequenced in a Test to allow testing potentially complex update logic. In general, simply create/destroy tests will only need one step.
Refer to the Env prefixed constants for environment variables that further control testing functionality.
TimeoutError is returned when WaitForState times out
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.TimeoutError.
Error returns a string with any information available.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.TimeoutError.
Unwrap returns the LastError, compatible with errors.Unwrap.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.TimeoutError.
type UnexpectedStateError struct { LastError error State string ExpectedState []string }
UnexpectedStateError is returned when Refresh returns a state that's neither in Target nor Pending
Deprecated: Copy this type to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.UnexpectedStateError.
Error returns a string with the unexpected state value, the desired target, and any last error.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.UnexpectedStateError.
Unwrap returns the LastError, compatible with errors.Unwrap.
Deprecated: Copy this method to the provider codebase or use github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry.UnexpectedStateError.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4