Choose the Contract That a Mock Can Honestly Prove
Every test starts with a claim, not a tool. The question is not whether to mock but what the run is entitled to conclude. A suite that proves the wrong thing is worse than no suite, because it turns an unchecked assumption into a green badge that reviewers stop reading.
A green badge is not a proof
Write down what the run is entitled to conclude before choosing a tool. A suite that proves the wrong claim converts an unchecked assumption into a badge, and reviewers stop looking at it.
Three layers answer three different questions. A unit test proves your expressions compute what you intended. A contract test proves your module composes its inputs and outputs correctly at a boundary. An integration test proves the provider and the service accept the result. No layer can borrow another layer's credibility.
Three layers, three claims
Unit tests prove expressions, contract tests prove module boundaries, integration tests prove the service accepts the result. Each answers a different question, and a passing unit test cannot stand in for an integration run.
A unit test here is a plan against a fake provider. Terraform still parses every file, evaluates locals and functions, resolves references, and checks each argument against the provider schema. The API call is what disappears, not the configuration logic.
A mock removes the API, not the logic
Terraform parses files, evaluates locals, resolves references and validates every argument against the real schema. Only the API call is faked, so a mock plan still catches type and reference errors.
A contract test fixes one boundary and reads what crosses it. An override pins a data source, a resource, or a module output while the rest of the graph runs normally. The assertion should describe the composition around that pinned value, never the value itself.
An integration test buys one fact with real money. It authenticates, consumes quota, collides with global names, and waits for eventual consistency. That expense is justified only when the fact is one the cheaper layers cannot reach.
The schema is real even when the data is not. A mock provider loads the installed provider's schema, so a misspelled argument, a missing required attribute, an invalid block nesting, or a wrong type still fails. That makes a mocked plan a genuine schema test, not a string-comparison exercise.
Required arguments do not become optional. Mocked providers invent values only for computed attributes. Anything required must appear in your configuration, so the mock cannot paper over a missing input the way a careless override could.
Provider-side validation never runs. Name rules, cross-field checks, region enums, and normalization live inside the provider's own code. A mock provider replaces that code, so those checks disappear together with the API call.
Authorization is invisible. No credential is read, no request is signed, and no policy is evaluated. A mock suite passes in an account with no permissions at all, which is exactly the property that makes it cheap and exactly the reason it cannot certify a deployment.
Generated values have no format. Numbers become zero, booleans become false, collections become empty, and strings become a random eight-character token. An ARN or resource ID invented this way will not resemble the real one, so any assertion about shape has to come from a value you supplied.
Provider defaults are missing. A real provider fills optional computed attributes, normalizes case, and sometimes preserves a prior value through a plan modifier. A mock generates a generic value or returns what you injected, so testing a default means testing your assumption about the default.
Reads are missing as well. Data sources return generated data instead of querying, refresh does not reconcile with the account, and drift and deleted objects stay invisible. A mock suite can stay green while the resource it describes no longer exists.
What a mock can honestly prove. Naming and prefixes, iteration keys, conditionals, merged tags, output wiring, validation rules, and the dependency order that is explicit in your configuration. All of those are properties of the configuration text, which is precisely what the fake provider executes.
What it cannot prove. API acceptance, provider validation, IAM, quota, global uniqueness, generated formats, service defaults, drift, readiness, and behavior under load. Each one requires a request that actually leaves Terraform and reaches an account.
Choose by the cost of being wrong. A wrong tag is cheap to fix after deployment; a rejected bucket name blocks the deployment; a wrong trust policy is an incident. Put cheap-to-detect failures in the fast layer and pay for one real check on the expensive one.
Write the leftover assumption down. Each suite should carry one sentence naming what it does not prove, stored beside the test file. That sentence is the handoff to the next layer and the reason a real test exists at all.
The first figure maps each claim to its honest verdict and its failure branch. The second shows the same boundary as three layers, with what each layer can see printed beside what it cannot.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
Q["A behaviour you want to lock down"] --> C{"What kind of claim
is it?"}
C -->|"this expression computes
the value I intended"| U["Unit: mock provider,
command = plan"]
C -->|"this module composes an
injected input correctly"| K["Contract: override at
one boundary"]
C -->|"the API accepts this and
the object works"| I["Integration: real provider,
command = apply"]
U --> U1["Proves names, keys, tags,
conditionals and wiring"]
U --> U2["Cannot see provider
validation, IAM or quota"]
K --> K1["Proves composition around
a value you supplied"]
K --> K2["Cannot see whether the
supplied value is real"]
I --> I1["Proves acceptance, identity
and readiness"]
I --> I2["Slow, costs money,
can leak resources"]
U2 -.->|"promote one assumption"| I
K2 -.->|"promote one assumption"| I
U1 --> G["Green check that matches
the claim it makes"]
K1 --> G
I1 --> G
U2 --> R["A rejected name, a 403
or a timeout survives the mock"]
K2 --> R
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class Q,C primary;
class U,K secondary;
class I ok;
class U1,K1,I1,G ok;
class U2,K2,I2,R danger;
The failure branches are the useful half of that map. Every danger node is a claim that the mock cannot support, and each one has a cheaper early signal than a failed deployment. A rejected name can be caught by the real provider in one apply; a missing permission can be caught by the same run before the assertion executes.
The multiplier is the promotion rule. You do not need a real test for every mocked scenario, only for the assumption whose failure would be expensive or silent. One real run can cover the naming rule, the permission, and the read-back for a whole module if it is designed to isolate them.
A passing mock therefore narrows the search space rather than closing it. It tells you the module is internally coherent and that a failure, if one comes, belongs to the provider or the account. That is a valuable statement, but it is a different sentence from "the infrastructure works", and the two should never share a dashboard row without a label.
Configure Mock Providers and Resource or Data Overrides
The mock provider block replaces the provider, not the configuration. Writing mock_provider "aws" {} at the root of a test file makes every call to the default AWS provider return fake data with the real schema. No credential, region, or endpoint is required, but initialization still installs the provider binary because the schema comes from it.
The mock shares the provider namespace. A real provider block and a mock provider block cannot both claim the default name, so mixing the two requires an alias on one of them. Inside a file that only mocks, the unaliased block is the simplest form and leaves nothing to misroute.
Computed values follow fixed rules. Numbers become zero, booleans false, strings a random eight-character token, collections empty, and objects recurse through their required sub-attributes. The types are dependable; the values are placeholders that exist only to let the plan complete.
Random strings are the first trap. A generated name is not stable across runs, so an assertion pinned to a literal value fails every time, while an assertion that compares the value with itself proves nothing. Pin the values your assertions read, and leave everything else generated.
Pin values by type, not by instance. A mock_resource block with a defaults map applies to every resource of that type that the mocked provider serves. Two buckets therefore receive the same ARN, which is fine for wiring and wrong for any test that expects distinct identities.
Timing matters more than the value. By default, generated data appears during apply while a plan sees an unknown value. A plan assertion that reads such an attribute fails because the value is unknown, not because the logic is wrong, which is the most common false alarm in a new mock suite.
One attribute fixes the timing. Setting override_during = plan on the mock provider makes generated data available during planning and reuses it during apply. The same attribute exists on individual mock resource and data blocks when only one type needs early values.
Overrides are narrower than mocks. An override_resource block targets one address and replaces that resource's provider call, and the data variant does the same for a single data source. The rest of the graph keeps whatever provider configuration the run uses.
A module override cuts deeper. An override_module block replaces that module's outputs and creates nothing inside it. That is useful for isolating a caller, and useless for testing the module's own logic.
An override is an input, not evidence. If you inject an ARN and then assert that same ARN, the assertion is circular. The useful pattern is to inject a boundary value and assert the output that composes it, such as a policy that embeds the account ID or a tag that combines it with a tier.
Precedence is nearest-wins. Resource and data overrides may sit at the root of the test file, inside a run block, or nested in a mock provider, and mock data can also be loaded from a directory through the provider's source argument. A run-level block beats a file-level block, and a directly nested block beats the shared file.
Addresses need their module path. An override for a data source inside a module is not the same address as a root-level lookup. Naming the wrong target leaves a different path in place: a mocked read returns generated data, and a real read is attempted against the actual provider, which usually surfaces as a credential error.
Shared mock data belongs in its own directory. A .tfmock.hcl file can hold resource and data defaults, and the provider's source argument loads the directory. That is how several test files agree on an ARN format without copying the same block, while a local block can still override one file's expectation.
Overrides hide read failures by design. If the overridden data source would have failed on a missing image or a denied lookup, the test cannot report that failure. Acceptable only when the lookup is not the claim under test, and worth a comment when it is.
Configure Mock Providers and Resource or Data Overrides
Status: design-only. Terraform CLI 1.17.1 and AWS provider 6.x were current when this was written. The steps follow documented mock and override behaviour; no AWS apply was performed for this article, and no command output is quoted.
Prerequisites. A module directory with a validated name and tier, one S3 bucket, a versioning resource, a bucket policy that reads the caller account, and outputs for the bucket, its ARN, and the policy. No AWS credentials are needed for steps 1 to 8.
- From the module directory, run
terraform init -input=false. The provider installs even though every later run is mocked, because the schema is loaded from the binary. - Create
tests/unit.tftest.hclwith amock_providerblock, amock_resourcedefault ARN for the bucket, and amock_datadefault account ID for the caller identity. Leave the timing at its default for now. - Run the suite with the filter flag. Expect the prefix and tag assertions, which read configured values, to pass with no credential in the environment.
- Add a plan assertion that the bucket ARN output is non-empty. Rerun. Expect a failure that names an unknown value rather than a wrong string. Add
override_during = planto the mock provider and rerun; the assertion should now pass because the value is generated during planning. - Add an
override_datablock for the caller identity at file scope with account111122223333, then assert the policy contains that account. Change the injected value to444455556666and rerun: the assertion should fail and print both values. - Repeat the override inside a run block with a third account. Confirm the run-level value wins, then delete the local block and confirm the file-level value returns.
- Remove the override and rerun. The policy assertion should now fail because the account comes from generated mock data rather than the pinned value. Restore the override.
- Unset every AWS variable and run both suites again. A failure at this point means a resource or data source is still reaching the real provider despite the mock.
| Block | Scope | What it replaces | Consequence for the assertion |
|---|---|---|---|
mock_provider | whole file or one run | every call to that provider | schema is checked, API and IAM are absent |
mock_resource | every instance of one type | computed values for that type | two instances share one pinned value |
mock_data | every instance of one data type | computed values for that type | the lookup never happens |
override_resource | one target address | that resource's provider call | the value is an input, not evidence |
override_data | one target address | that data source's read | read failures are hidden by design |
override_module | one module call | the module's outputs | nothing inside the module runs |
source | one mock provider | loads mock data files | a nested block wins over the file |
Expected observation. The suite passes without credentials, fails when an assertion reads an unpinned computed value at plan time, and follows the nearest override when two scopes disagree. Replacing the injected account changes the computed policy, which proves the assertion is reading the composition rather than the injection.
Failure checks. An unknown-value diagnostic means the timing is wrong, not the expression. An override that appears to do nothing usually names the wrong address or the wrong module path. Two resources returning the same ARN is the documented type-wide behaviour, not a provider bug. A credential error in a mocked suite means one target escaped the mock.
Cost and cleanup. No cloud object is created, so the only cost is provider download and local CPU. Delete the temporary test files after the exercise, and keep credentials out of the file even while experimenting, because a committed account ID is a small leak that outlives the test.
Configuration mistakes cluster around scope and time. A default that is too wide makes two resources look identical; a default that is too narrow leaves one assertion reading an unknown; an override in the wrong scope silently tests the file-level value. Naming the scope and the phase beside each block prevents all three.
The second figure follows the mechanics and the two branches that produce a false red: an unknown value read at plan time, and an override that misses its target.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
T["tests/unit.tftest.hcl"] --> M["mock_provider aws
real schema, invented data"]
M --> INIT["terraform init still installs
the provider binary"]
M --> CMD{"command"}
CMD -->|"plan"| P["computed attributes are
unknown by default"]
CMD -->|"apply"| A["values generated in memory,
no API call"]
P --> OD{"override_during = plan?"}
OD -->|"yes"| KN["value known at plan,
the assertion can read it"]
OD -->|"no"| UN["assertion compares an
unknown value and fails"]
UN --> FIX["set override_during = plan
or assert after apply"]
M --> DEF["mock_resource defaults
pin one type-wide value"]
M --> OVR["override_data at
one target address"]
OVR --> DER["assert the output that
composes the value"]
DEF --> TAUT["asserting the default
proves wiring only"]
DER --> PASS["contract claim holds"]
KN --> PASS
TAUT --> WARN["acceptable only when wiring
is the claim"]
OVR --> MISS["wrong target address
leaves another path in place"]
MISS --> CRED["the run reads generated data
or needs real credentials"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class T,CMD,OD primary;
class M,DEF,OVR secondary;
class KN,DER,PASS ok;
class UN,FIX,MISS,CRED danger;
class P,A,INIT,TAUT,WARN warn;
Two branches deserve a permanent comment in the test file. The unknown-value branch is a timing problem and should be fixed by the mock, never by weakening the assertion. The missed-target branch is a scope problem and should fail loudly, because it means the value under assertion came from somewhere other than the seam you named.
Share Fixtures Without Leaking State Between Tests
State is the part of a test file people forget. Each file starts with empty state held in memory, never writes to your configured backend, and destroys what it created when the file ends. Runs that execute the same module share one state; each alternate module gets its own; a shared key can join them.
A fixture is just an earlier run's output. A setup run loads a small module, then later runs read its output by name and pass it into a variable. That is the supported handoff, and it is why parsing CLI output to find a bucket name is a smell rather than a technique.
A fixture must stay an input. The moment an assertion starts checking the fixture's own values, the test is grading the fixture. Assert the module under test, and let the fixture output arrive as a variable.
The default state sharing is the quiet leak. Any run without a module block reuses the main state, so a second run with different variables plans an update to the first run's objects. Assertions then describe the mutated object, and whether the file passes depends on the order the author happened to write.
A shared key makes the coupling explicit. state_key gives a run a named state, so two modules can share one or two runs can be kept apart. Merging is legitimate for a setup-and-consume pair, but it also puts ownership and destroy order into the run order.
File-level variables are shared by construction. They reach every run, and a run-level block replaces them as whole values rather than merging attributes. Half-overriding an object silently drops the rest of it, which produces a confusing diff in a run that looked unrelated.
Committed test values outrank the environment. Variables in the test file beat environment variables, command-line flags, and ordinary variable files, so CI cannot quietly change a committed value. Automatic variable files inside the test directory are the supported place for account-specific values, and they apply only to tests in that directory.
Order dependence is a design smell. If a test passes only after another run, state is carrying a fixture that nobody named. Either expose the dependency through an output or split the file, because a hidden dependency turns a reordering into a mystery failure.
Parallelism is safe under two conditions. Runs must not reference each other's outputs, and they must not share a state key. A parallel run that violates either rule is not faster, it is a scheduler-dependent test that fails on a different machine.
Determinism means no ambient inputs. A clock, a random suffix, an account ID read from the environment, a default region, or a leftover object from yesterday each turn the suite into a weather report. Pin them through variables and overrides, then the only variable left is the code under test.
Cheap means a small graph and a plan. A fixture that creates a network to test a bucket tag is not a fixture; it is a second integration test with a misleading name. The fixture should create the smallest object that satisfies the contract.
Cleanup belongs to the fixture design. Resources are destroyed in reverse run order, so a setup bucket cannot go before the run that filled it. force_destroy, short names, no deletion protection, and an expiry tag are part of the fixture, not an afterthought.
A shared fixture needs one owner. Document which run creates it, which runs consume it, and what a setup failure means for the rest. Otherwise one broken prerequisite produces a cascade of assertion failures that all point at the wrong place.
The next figure draws the state boundaries inside a single file and the two ways a value crosses them: a run output, and a merged key.
The diagram has one rule hidden in it. A value may cross a run boundary as a typed output, and it may cross a module boundary through a merged key, but it should never cross as a copied literal. The first two are visible to Terraform; the third is invisible coupling that survives refactors and breaks silently when the fixture changes.
Cheapness follows from the same picture. A file with one alternate module and two consuming runs has three states to reason about and one destroy order. A file with five modules has five, and the author usually cannot say which state owns the bucket that failed to delete.
Mix Real and Mock Providers Deliberately
Mixing is a routing decision. A real provider block and a mock provider block share one namespace, so one carries an alias, and each run chooses its provider through a mapping. The mapping is the whole mechanism; there is no hidden switch that turns mocking on or off.
The real side still needs real configuration. Region and credentials come from the test file, the environment, or an automatic variable file inside the test directory. Provider blocks may read test variables and earlier run outputs, which is how a setup run can supply short-lived credentials to a second provider.
Credentials belong to exactly one layer. A mock run should work with an empty environment, and a real run should use a disposable account with a scoped role. If a supposed mock run needs credentials, the mapping probably did not apply and the test is quietly calling the real provider.
The shared state is the hazard. Real and mock applies against the same module share the main state. A mock run can write invented computed values over a real object's record. The next real run, or the final destroy, then works from identifiers the API never issued.
Switching identity inside one state is the documented failure. Terraform warns that changing providers between apply runs can make resources unusable by the next provider. The warning is easy to read past because the plan often looks plausible; the damage appears at destroy or at the next refresh.
A plan-only mock run writes nothing but can still mislead. Its provider invents the values it reads, so the diff may show changes that no real API would produce. Use it for expressions, not for a verdict about drift.
Separate files are the clean boundary. Put the real smoke test in its own file with its own state, and keep the mock suite in another. The cost is one more file, not one more framework, and each file owns its cleanup and its claim.
If a file must contain both, separate the addresses. A real setup run can create resource A and publish its name, while a mock run exercises a different address or module that consumes the name. Never let two provider identities own the same address across apply runs.
Destroy order follows run order, not intent. The state referenced by the latest run is destroyed first, so the last run decides the order of the cleanup pass. A real object whose record was overwritten by a mock run has no clean owner left.
The legitimate mixed pattern is a real fixture feeding a mocked assertion. A setup run creates one real bucket and publishes its name; the mock run then tests how the module builds a policy around that name without creating anything. The expensive call is a fixture, and the assertion is still about composition.
Blast radius grows with every real address. Each real resource adds a name that can collide, a quota that can exhaust, and an object that can leak. Keep the real side to one address per claim, tagged with an owner and an expiry.
The table compares the arrangements by what Terraform calls, what state is written, and what the arrangement can honestly claim.
| Arrangement | What Terraform calls | State written | Cleanup | Honest claim |
|---|---|---|---|---|
| Mock, plan only | schema only | none | none needed | derivations, keys and wiring |
| Mock, apply | schema only | in-memory only | discarded with the process | apply-time expressions, still no API |
| Override one data source | provider for everything except the target | in-memory or real, depending on the run | normal provider destroy | composition around a pinned input |
| Real and mock in one file, same address | both, in run order | one shared main state | real provider last, with mock values | nothing reliable |
| Real in a separate file | real provider only | its own in-memory state | reverse run order | acceptance and readiness |
The fourth row is the one to remove during review. It is not a stronger test because it combines both providers; it is a test whose state has two authors. The same coverage is available by splitting the file, and the split costs nothing at runtime.
The next figure contrasts the mixed file with the split file on the dimension that matters: which provider owns the state at destroy time.
The picture also explains why deleting a leftover is harder than it looks. A mock run leaves no object, but it can leave a state record that the real provider never issued. A later destroy or refresh then works from that record, and the cleanup error can name an identifier that never existed in the account.
Keep One Real Test for the Assumption the Mock Cannot Check
Every mock suite leaves a residue. The residue is the single assumption the fast layer could not test: the provider accepts the name, the role can write, the generated identifier has the expected shape, or the service answers once it is created. Pick the most expensive residue and buy it once.
The real test should assert an API fact. Comparing an output with the value that produced it proves only that Terraform copied a string. A useful assertion reads something only the API knows: the created bucket, the ARN shape returned by the provider, the versioning status read back, or one successful request to the endpoint.
One call is enough for a module. Create the smallest object the contract needs, read it back through a data source or a loader module, and assert the property that the mock could not produce. Then destroy it. A second real resource should be justified by a second claim, not by symmetry.
Readiness is a different claim from creation. A successful create proves the control plane accepted the write. It does not prove that DNS resolves, that the certificate matches, or that the process serves traffic. Readiness needs its own probe, its own success signal, and its own time budget.
A bounded wait has three numbers. The maximum attempts, the interval between them, and the total deadline. Retry only a named transient signal such as a connection error or a not-found immediately after creation; a permission error or a validation error will never improve with time and should fail at once.
Teardown deserves the same design effort. force_destroy on a test bucket, no deletion protection, a short name, no final snapshot, and an expiry tag cover the common ways a passing test leaves residue. The tag is what a scheduled sweep can find when the process dies before destroy.
A failing test must fail for the intended reason. Read where the diagnostic points: an assertion line means the contract changed; a provider error means the API refused; a timeout means readiness was assumed; a destroy error means cleanup is incomplete. Four locations, four different repairs.
Two negative controls prove the suite is live. Break the derivation and confirm the mock suite fails on the assertion with the expected and actual values. Revoke the write permission and confirm the real suite fails at the API before any assertion runs. If the real suite still passes, it is not reaching the account.
Do not let the mock absorb the negative control. A mock will happily create a bucket whose name starts with the reserved xn-- prefix, because provider-side validation never runs. Terraform's own variable validation rejects only the rules you wrote; the provider's rule set is larger.
Assertion messages carry the contract forward. Write what assumption failed and what the consequence is, not just that two strings differ. The next person reads the message at two in the morning, with no memory of the test's design.
The lab builds the three-layer suite and then breaks it twice, once in the fast layer and once in the real one, so the failure location itself becomes the evidence.
Build the module test pyramid
Status: design-only. Terraform CLI 1.17.1 and AWS provider 6.x were current when this was written. No AWS apply was performed for this article, and no command output is quoted. Every identifier below is an example, not a captured value.
Prerequisites. A module with a validated name and tier, one S3 bucket, versioning, a bucket policy built from the caller account, and outputs for the bucket, ARN, and policy. A disposable account and region for steps 6 to 9, and permission to create and delete buckets there.
- Initialise the module once. The provider schema is needed by every layer, including the mocked ones.
- Write the unit suite from the previous section and run it with credentials unset. Expect a pass; this is the fast layer that will run on every commit.
- Add a contract suite with
override_datafor the caller identity and an assertion on the composed policy. Confirm that changing the injected account changes the assertion result. - Break the prefix derivation by replacing the separator. Rerun the unit suite. Expect the assertion to fail with the actual prefix, at the assertion line, not with a provider error.
- Restore the separator. Confirm both mocked suites pass again without any credential.
- Create
tests/smoke.tftest.hclin its own file with the real provider,command = apply, andforce_destroyon the bucket. - Assert an API fact: read the bucket back and check that the returned name carries the prefix, and that the ARN is non-empty and shaped like the provider's output. Keep the assertion to the property the mock could not supply.
- Use a name with the reserved
xn--prefix and rerun both layers. The name passes the module's own validation, so expect the unit suite to pass and the real suite to fail in the real layer. This is the proof that the mock cannot see provider naming rules, and the reason the real test exists. - Restore the name. Remove the create permission from the test role and rerun the real suite. Expect a failure before the assertions. Restore the permission and confirm the suite is green again.
| Check | Evidence | Verdict |
|---|---|---|
| Unit suite is credential-free | Passes with the environment emptied | Mock is complete |
| Unknown value fails at plan | Diagnostic names an unknown value | Timing is explicit |
| Override changes composition | New account appears in the policy | Assertion is live |
| Mock misses a bad name | Reserved prefix still passes the unit suite | Expected limit |
| Real suite rejects the name | Provider error, before assertions | Real path is exercised |
| Revoked permission fails | Access error before assertions | Test is not self-certifying |
| Cleanup is complete | Second read finds no bucket | Teardown works |
Expected observation. The unit suite fails only when the derivation changes, the contract suite fails only when the injected input changes, and the real suite fails when the API or the permission changes. Each failure points at a different line, which is the practical definition of a useful pyramid.
Failure checks. An unknown value at plan means the mock needs override_during = plan. An override with no effect names the wrong address. A real suite that passes after the permission is revoked is using a mock or a different identity. A leftover bucket after a green run means force_destroy or the destroy order is wrong.
Cost and cleanup. One bucket for the duration of the real run plus a handful of API requests. Destroy it, read it back to confirm it is gone, and check the tagged inventory for anything past its expiry. Mock runs cost only local CPU.
The pyramid is not a hierarchy of importance. The real test is not better than the mock; it is answering a different question at a different price. A team that keeps only the real test runs slowly and hides logic defects behind API errors; a team that keeps only the mock ships a green suite into a rejected deployment.
Three suites, three claims. The mock proves the configuration computes the values it promises. The override proves the module composes an injected boundary correctly. The real run proves the provider accepts the result. Keep those sentences next to the files, and a green pipeline will mean exactly as much as it says.