Documentation ¶
Index ¶
- Constants
- func AddTestSweepers(name string, s *Sweeper)
- func GRPCTestProvider(rp terraform.ResourceProvider) providers.Interface
- func LogOutput(t TestT) (logOutput io.Writer, err error)
- func ParallelTest(t TestT, c TestCase)
- func PrefixedUniqueId(prefix string) string
- func Retry(timeout time.Duration, f RetryFunc) error
- func RunNewTest(t *testing.T, c TestCase, providers map[string]terraform.ResourceProvider)
- func Test(t TestT, c TestCase)
- func TestMain(m *testing.M)
- func UniqueId() string
- func UnitTest(t TestT, c TestCase)
- type CreateFunc
- type DestroyFunc
- type DiffFunc
- type ImportStateCheckFunc
- type ImportStateIdFunc
- type Map
- func (m *Map) Apply(info *terraform.InstanceInfo, s *terraform.InstanceState, ...) (*terraform.InstanceState, error)
- func (m *Map) Diff(info *terraform.InstanceInfo, s *terraform.InstanceState, ...) (*terraform.InstanceDiff, error)
- func (m *Map) Refresh(info *terraform.InstanceInfo, s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error)
- func (m *Map) Resources() []terraform.ResourceType
- func (m *Map) Validate(t string, c *terraform.ResourceConfig) ([]string, []error)
- type NotFoundError
- type RefreshFunc
- type Resource
- type RetryError
- type RetryFunc
- type StateChangeConf
- type StateRefreshFunc
- type Sweeper
- type SweeperFunc
- type TestCase
- type TestCheckFunc
- func ComposeAggregateTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc
- func ComposeTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc
- func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestCheckFunc
- func TestCheckModuleResourceAttr(mp []string, name string, key string, value string) TestCheckFunc
- func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirst string, keyFirst string, mpSecond []string, ...) TestCheckFunc
- func TestCheckModuleResourceAttrPtr(mp []string, name string, key string, value *string) TestCheckFunc
- func TestCheckModuleResourceAttrSet(mp []string, name string, key string) TestCheckFunc
- func TestCheckNoResourceAttr(name, key string) TestCheckFunc
- func TestCheckOutput(name, value string) TestCheckFunc
- func TestCheckResourceAttr(name, key, value string) TestCheckFunc
- func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc
- func TestCheckResourceAttrPtr(name string, key string, value *string) TestCheckFunc
- func TestCheckResourceAttrSet(name, key string) TestCheckFunc
- func TestMatchOutput(name string, r *regexp.Regexp) TestCheckFunc
- func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc
- func TestModuleMatchResourceAttr(mp []string, name string, key string, r *regexp.Regexp) TestCheckFunc
- type TestProvider
- type TestStep
- type TestT
- type TimeoutError
- type UnexpectedStateError
- type UpdateFunc
Constants ¶
const EnvLogPathMask = "TF_LOG_PATH_MASK"
Set to a file mask in sprintf format where %s is test name
const TestEnvVar = "TF_ACC"
const UniqueIDSuffixLength = 26
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.
const UniqueIdPrefix = `terraform-`
Variables ¶
This section is empty.
Functions ¶
func AddTestSweepers ¶
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 GRPCTestProvider ¶
func GRPCTestProvider(rp terraform.ResourceProvider) providers.Interface
GRPCTestProvider takes a legacy ResourceProvider, wraps it in the new GRPC shim and starts it in a grpc server using an inmem connection. It returns a GRPCClient for this new server to test the shimmed resource provider.
func ParallelTest ¶
ParallelTest performs an acceptance test on a resource, allowing concurrency with other ParallelTest.
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). All other requirements of the Test function also apply to this function.
func PrefixedUniqueId ¶
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.
func Retry ¶
Retry is a basic wrapper around StateChangeConf that will just retry a function until it no longer returns an error.
func RunNewTest ¶ added in v1.7.0
func Test ¶
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.
Tests will fail unless the verbose flag (`go test -v`, or explicitly the "-test.v" flag) is set. Because some acceptance tests take quite long, we require the verbose flag so users are able to see progress output.
Types ¶
type CreateFunc ¶
type CreateFunc func( *terraform.InstanceState, *terraform.InstanceDiff, interface{}) (*terraform.InstanceState, error)
CreateFunc is a function that creates a resource that didn't previously exist.
type DestroyFunc ¶
type DestroyFunc func( *terraform.InstanceState, interface{}) error
DestroyFunc is a function that destroys a resource that previously exists using the state.
type DiffFunc ¶
type DiffFunc func( *terraform.InstanceState, *terraform.ResourceConfig, interface{}) (*terraform.InstanceDiff, error)
DiffFunc is a function that performs a diff of a resource.
type ImportStateCheckFunc ¶
type ImportStateCheckFunc func([]*terraform.InstanceState) error
ImportStateCheckFunc is the check function for ImportState tests
type ImportStateIdFunc ¶
ImportStateIdFunc is an ID generation function to help with complex ID generation for ImportState tests.
type Map ¶
Map is a map of resources that are supported, and provides helpers for more easily implementing a ResourceProvider.
func (*Map) Apply ¶
func (m *Map) Apply( info *terraform.InstanceInfo, s *terraform.InstanceState, d *terraform.InstanceDiff, meta interface{}) (*terraform.InstanceState, error)
Apply performs a create or update depending on the diff, and calls the proper function on the matching Resource.
func (*Map) Diff ¶
func (m *Map) Diff( info *terraform.InstanceInfo, s *terraform.InstanceState, c *terraform.ResourceConfig, meta interface{}) (*terraform.InstanceDiff, error)
Diff performs a diff on the proper resource type.
func (*Map) Refresh ¶
func (m *Map) Refresh( info *terraform.InstanceInfo, s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error)
Refresh performs a Refresh on the proper resource type.
Refresh on the Resource won't be called if the state represents a non-created resource (ID is blank).
An error is returned if the resource isn't registered.
func (*Map) Resources ¶
func (m *Map) Resources() []terraform.ResourceType
Resources returns all the resources that are supported by this resource map and can be used to satisfy the Resources method of a ResourceProvider.
type NotFoundError ¶
type NotFoundError struct { LastError error LastRequest interface{} LastResponse interface{} Message string Retries int }
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
type RefreshFunc ¶
type RefreshFunc func( *terraform.InstanceState, interface{}) (*terraform.InstanceState, error)
RefreshFunc is a function that performs a refresh of a specific type of resource.
type Resource ¶
type Resource struct { ConfigValidator *config.Validator Create CreateFunc Destroy DestroyFunc Diff DiffFunc Refresh RefreshFunc Update UpdateFunc }
type RetryError ¶
RetryError is the required return type of RetryFunc. It forces client code to choose whether or not a given error is retryable.
func NonRetryableError ¶
func NonRetryableError(err error) *RetryError
NonRetryableError is a helper to create a RetryError that's _not_ retryable from a given error.
func RetryableError ¶
func RetryableError(err error) *RetryError
RetryableError is a helper to create a RetryError that's retryable from a given error.
type RetryFunc ¶
type RetryFunc func() *RetryError
RetryFunc is the function retried until it succeeds.
type StateChangeConf ¶
type StateChangeConf struct { Delay time.Duration // Wait this time before starting checks Pending []string // States that are "allowed" and will continue trying Refresh StateRefreshFunc // Refreshes the current state Target []string // Target state Timeout time.Duration // The amount of time to wait before timeout MinTimeout time.Duration // Smallest time to wait before refreshes PollInterval time.Duration // Override MinTimeout/backoff and only poll this often NotFoundChecks int // Number of times to allow not found // This is to work around inconsistent APIs ContinuousTargetOccurence int // Number of times the Target state has to occur continuously }
StateChangeConf is the configuration struct used for `WaitForState`.
func (*StateChangeConf) WaitForState ¶
func (conf *StateChangeConf) WaitForState() (interface{}, error)
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.
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.
type StateRefreshFunc ¶
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.
`state` is the latest state of that object. And `err` is any error that may have happened while refreshing the state.
type Sweeper ¶
type Sweeper struct { // Name for sweeper. Must be unique to be ran by the Sweeper Runner Name string // Dependencies list the const names of other Sweeper functions that must be ran // prior to running this Sweeper. This is an ordered list that will be invoked // recursively at the helper/resource level Dependencies []string // Sweeper function that when invoked sweeps the Provider of specific // resources F SweeperFunc }
type SweeperFunc ¶
type 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.
type TestCase ¶
type TestCase struct { // IsUnitTest allows a test to run regardless of the TF_ACC // environment variable. This should be used with care - only for // fast tests on local resources (e.g. remote state with a local // backend) but can be used to increase confidence in correct // operation of Terraform without waiting for a full acctest run. IsUnitTest bool // PreCheck, if non-nil, will be called before any test steps are // executed. It will only be executed in the case that the steps // would run, so it can be used for some validation before running // acceptance tests, such as verifying that keys are setup. PreCheck func() // Providers is the ResourceProvider that will be under test. // // Alternately, ProviderFactories can be specified for the providers // that are valid. This takes priority over Providers. // // The end effect of each is the same: specifying the providers that // are used within the tests. Providers map[string]terraform.ResourceProvider ProviderFactories map[string]terraform.ResourceProviderFactory // PreventPostDestroyRefresh can be set to true for cases where data sources // are tested alongside real resources PreventPostDestroyRefresh bool // CheckDestroy is called after the resource is finally destroyed // to allow the tester to test that the resource is truly gone. CheckDestroy TestCheckFunc // Steps are the apply sequences done within the context of the // same state. Each step can have its own check to verify correctness. Steps []TestStep // The settings below control the "ID-only refresh test." This is // an enabled-by-default test that tests that a refresh can be // refreshed with only an ID to result in the same attributes. // This validates completeness of Refresh. // // IDRefreshName is the name of the resource to check. This will // default to the first non-nil primary resource in the state. // // IDRefreshIgnore is a list of configuration keys that will be ignored. IDRefreshName string IDRefreshIgnore []string // DisableBinaryDriver forces this test case to run using the legacy test // driver, even if the binary test driver has been enabled. // This property will be removed in version 2.0.0 of the SDK. DisableBinaryDriver bool }
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.
type TestCheckFunc ¶
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.
func ComposeAggregateTestCheckFunc ¶
func ComposeAggregateTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc
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.
func ComposeTestCheckFunc ¶
func ComposeTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc
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.
func TestCheckModuleNoResourceAttr ¶
func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestCheckFunc
TestCheckModuleNoResourceAttr - as per TestCheckNoResourceAttr but with support for non-root modules
func TestCheckModuleResourceAttr ¶
func TestCheckModuleResourceAttr(mp []string, name string, key string, value string) TestCheckFunc
TestCheckModuleResourceAttr - as per TestCheckResourceAttr but with support for non-root modules
func TestCheckModuleResourceAttrPair ¶
func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirst string, keyFirst string, mpSecond []string, nameSecond string, keySecond string) TestCheckFunc
TestCheckModuleResourceAttrPair - as per TestCheckResourceAttrPair but with support for non-root modules
func TestCheckModuleResourceAttrPtr ¶
func TestCheckModuleResourceAttrPtr(mp []string, name string, key string, value *string) TestCheckFunc
TestCheckModuleResourceAttrPtr - as per TestCheckResourceAttrPtr but with support for non-root modules
func TestCheckModuleResourceAttrSet ¶
func TestCheckModuleResourceAttrSet(mp []string, name string, key string) TestCheckFunc
TestCheckModuleResourceAttrSet - as per TestCheckResourceAttrSet but with support for non-root modules
func TestCheckNoResourceAttr ¶
func TestCheckNoResourceAttr(name, key string) TestCheckFunc
TestCheckNoResourceAttr is a TestCheckFunc which ensures that NO value exists in state for the given name/key combination.
func TestCheckOutput ¶
func TestCheckOutput(name, value string) TestCheckFunc
TestCheckOutput checks an output in the Terraform configuration
func TestCheckResourceAttr ¶
func TestCheckResourceAttr(name, key, value string) TestCheckFunc
TestCheckResourceAttr is a TestCheckFunc which validates the value in state for the given name/key combination.
func TestCheckResourceAttrPair ¶
func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc
TestCheckResourceAttrPair is a TestCheckFunc which validates that the values in state for a pair of name/key combinations are equal.
func TestCheckResourceAttrPtr ¶
func TestCheckResourceAttrPtr(name string, key string, value *string) TestCheckFunc
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.
func TestCheckResourceAttrSet ¶
func TestCheckResourceAttrSet(name, key string) TestCheckFunc
TestCheckResourceAttrSet is a TestCheckFunc which ensures a value exists in state for the given name/key combination. It is useful when testing that computed values were set, when it is not possible to know ahead of time what the values will be.
func TestMatchOutput ¶
func TestMatchOutput(name string, r *regexp.Regexp) TestCheckFunc
func TestMatchResourceAttr ¶
func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc
TestMatchResourceAttr is a TestCheckFunc which checks that the value in state for the given name/key combination matches the given regex.
func TestModuleMatchResourceAttr ¶
func TestModuleMatchResourceAttr(mp []string, name string, key string, r *regexp.Regexp) TestCheckFunc
TestModuleMatchResourceAttr - as per TestMatchResourceAttr but with support for non-root modules
type TestProvider ¶
type TestProvider interface {
TestReset() error
}
TestProvider can be implemented by any ResourceProvider to provide custom reset functionality at the start of an acceptance test. The helper/schema Provider implements this interface.
type TestStep ¶
type TestStep struct { // ResourceName should be set to the name of the resource // that is being tested. Example: "aws_instance.foo". Various test // modes use this to auto-detect state information. // // This is only required if the test mode settings below say it is // for the mode you're using. ResourceName string // PreConfig is called before the Config is applied to perform any per-step // setup that needs to happen. This is called regardless of "test mode" // below. PreConfig func() // Taint is a list of resource addresses to taint prior to the execution of // the step. Be sure to only include this at a step where the referenced // address will be present in state, as it will fail the test if the resource // is missing. // // This option is ignored on ImportState tests, and currently only works for // resources in the root module path. Taint []string // Config a string of the configuration to give to Terraform. If this // is set, then the TestCase will execute this step with the same logic // as a `terraform apply`. Config string // Check is called after the Config is applied. Use this step to // make your own API calls to check the status of things, and to // inspect the format of the ResourceState itself. // // If an error is returned, the test will fail. In this case, a // destroy plan will still be attempted. // // If this is nil, no check is done on this step. Check TestCheckFunc // Destroy will create a destroy plan if set to true. Destroy bool // ExpectNonEmptyPlan can be set to true for specific types of tests that are // looking to verify that a diff occurs ExpectNonEmptyPlan bool // ExpectError allows the construction of test cases that we expect to fail // with an error. The specified regexp must match against the error for the // test to pass. ExpectError *regexp.Regexp // PlanOnly can be set to only run `plan` with this configuration, and not // actually apply it. This is useful for ensuring config changes result in // no-op plans PlanOnly bool // PreventDiskCleanup can be set to true for testing terraform modules which // require access to disk at runtime. Note that this will leave files in the // temp folder PreventDiskCleanup bool // PreventPostDestroyRefresh can be set to true for cases where data sources // are tested alongside real resources PreventPostDestroyRefresh bool // SkipFunc is called before applying config, but after PreConfig // This is useful for defining test steps with platform-dependent checks SkipFunc func() (bool, error) // ImportState, if true, will test the functionality of ImportState // by importing the resource with ResourceName (must be set) and the // ID of that resource. ImportState bool // ImportStateId is the ID to perform an ImportState operation with. // This is optional. If it isn't set, then the resource ID is automatically // determined by inspecting the state for ResourceName's ID. ImportStateId string // ImportStateIdPrefix is the prefix added in front of ImportStateId. // This can be useful in complex import cases, where more than one // attribute needs to be passed on as the Import ID. Mainly in cases // where the ID is not known, and a known prefix needs to be added to // the unset ImportStateId field. ImportStateIdPrefix string // ImportStateIdFunc is a function that can be used to dynamically generate // the ID for the ImportState tests. It is sent the state, which can be // checked to derive the attributes necessary and generate the string in the // desired format. ImportStateIdFunc ImportStateIdFunc // ImportStateCheck checks the results of ImportState. It should be // used to verify that the resulting value of ImportState has the // proper resources, IDs, and attributes. ImportStateCheck ImportStateCheckFunc // ImportStateVerify, if true, will also check that the state values // that are finally put into the state after import match for all the // IDs returned by the Import. Note that this checks for strict equality // and does not respect DiffSuppressFunc or CustomizeDiff. // // ImportStateVerifyIgnore is a list of prefixes of fields that should // not be verified to be equal. These can be set to ephemeral fields or // fields that can't be refreshed and don't matter. ImportStateVerify bool ImportStateVerifyIgnore []string // contains filtered or unexported fields }
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.
type TestT ¶
type TestT interface { Error(args ...interface{}) Fatal(args ...interface{}) Skip(args ...interface{}) Name() string Parallel() }
TestT is the interface used to handle the test lifecycle of a test.
Users should just use a *testing.T object, which implements this.
type TimeoutError ¶
type TimeoutError struct { LastError error LastState string Timeout time.Duration ExpectedState []string }
TimeoutError is returned when WaitForState times out
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
type UnexpectedStateError ¶
UnexpectedStateError is returned when Refresh returns a state that's neither in Target nor Pending
func (*UnexpectedStateError) Error ¶
func (e *UnexpectedStateError) Error() string
type UpdateFunc ¶
type UpdateFunc func( *terraform.InstanceState, *terraform.InstanceDiff, interface{}) (*terraform.InstanceState, error)
UpdateFunc is a function that is called to update a resource that previously existed. The difference between this and CreateFunc is that the diff is guaranteed to only contain attributes that don't require a new resource.