skip to content

In a Terraform `.tftest.hcl` file, how do you use `expect_failures` to test a module's failure path, and what still fails the `run` block?

level: middleimportance: should knowfreq 44%

answer

  1. a test that passes when something breaks
  2. custom conditions, not every error
  3. which operation the failure must happen in
  4. only one kind of object keeps going
  5. root module of the configuration under test

basics

~20 s

In a Terraform test file, expect_failures lists the object whose custom condition should fail, usually with command = plan and bad input. The run passes only if it does; a type error or provider error still fails the run.

solid answer

~50 s

I write a pair of `run` blocks, usually with `command = plan`. One feeds good input and expects no failure. The other overrides a value in its own `variables` block and lists the object in `expect_failures`, for example `var.cidr_block`. It accepts input variables, outputs, resources, data sources and `check` blocks. The run passes only if that object's custom condition fails; otherwise Terraform reports `Missing expected failure`. It covers custom conditions only, so a type mismatch or a provider error still fails the run. With `command = apply`, a condition that fails during the plan also fails the run, because the apply could not happen. Every condition except a `check` block halts the operation, so I name one object per run and assert only on values computed before it fails. A failing `check` block, normally just a warning, also fails a test unless it is expected.

code

hcl · 21 lines
hcl
# tests/plan.tftest.hcl
variables {
  name       = "orders"
  cidr_block = "10.20.0.0/16"
}

run "accepts_private_range" {
  command = plan
}

run "rejects_public_range" {
  command = plan

  variables {
    cidr_block = "8.8.8.0/24"
  }

  expect_failures = [
    var.cidr_block,
  ]
}

go deeper

for a junior

Recall that expect_failures turns a custom condition's failure into the passing outcome of a run block, and that you give it bad input through that block's own variables.

for a middle

Explain the matching rules: which objects it can name, that only custom conditions count, what Missing expected failure means, and why command = plan is the usual pairing with it.

for a senior

Diagnose the confusing cases: an expected failure shown as the reason an apply run failed, a second listed variable that never reports, a child-module condition that never matches. Say how you would restructure each.

for a principal

Treat negative tests as the module's published promises. Decide which custom conditions are contract and deserve a failure case each, and which are internal and would only add maintenance if tested.

## Why a test needs to expect a failure A module's custom conditions are part of its contract: a shared network module promises to reject a CIDR range it cannot use. Testing the happy path says nothing about that promise. A Terraform test file (`.tftest.hcl`) therefore lets a `run` block declare that a failure is the desired outcome, through the **`expect_failures`** argument. By default, any custom condition that fails while a test file executes makes the test fail, including assertions in `check` blocks. That last part differs from a normal plan or apply, where a failed `check` block is only a warning: under `terraform test` it counts against the run unless it is expected. ## How to write the pair The usual shape is two `run` blocks in the same file, both with `command = plan` so nothing is created: 1. A block with good input, which proves the condition does not reject everything. 2. A block that overrides one value in its own `variables` block and lists the object in `expect_failures`. Run-level `variables` override file-level ones for that block only, and values set in a test file take precedence over environment variables, variable files and the command line, so each case is self-contained. ## What the list can name `expect_failures` takes **checkable objects**, not error messages: | Object | The custom condition it covers | |---|---| | Input variable, such as `var.cidr_block` | `validation` block | | Output value, such as `output.subnet_ids` | `precondition` | | Resource or data source | `precondition` or `postcondition` | | `check` block, such as `check.dns_resolves` | `assert`, or an error from its scoped data source | The source draws one more boundary worth knowing: failures can only be expected against objects in the **root module** of the configuration the `run` block is executing. A condition failing inside a nested child module is not matched. To test one directly, point a `run` block at that module with a `module` block, which makes it the root for that block. ## What still fails the run The argument is narrow on purpose. These all still fail: - **No failure happened.** Terraform reports `Missing expected failure`, saying the object was expected to report an error but did not. This is the guard that stops the test passing because the condition was deleted. - **A different kind of error.** Expected failures apply only to user-defined custom conditions. A type mismatch on a variable fails the run even if that variable is listed, as does a provider error. - **A different condition failed.** Anything not in the list is still an error. - **The failure came at the wrong stage.** Terraform only expects failures in the operation `command` names. ## Why plan is the normal choice A `run` block with `command = apply` has to plan first. If the listed condition fails during that plan, the apply cannot run, so the overall run fails. Terraform adds an `Expected failure while planning` warning next to the original error, which is confusing to read because the failure you listed appears as the reason for the failure. That is why the guidance is to use `expect_failures` with `command = plan` in most cases. The exception is a condition Terraform cannot evaluate during planning because it relies on computed attributes. It will only fire during apply, so `command = apply` is the correct pairing, and the run does create real objects. ## Assertions and several objects Every custom condition except a `check` block halts Terraform when it fails. Two consequences follow: - `assert` blocks beside `expect_failures` should read only values certain to be computed before the object fails. You can arrange that with references or `depends_on` in the configuration. - You can reliably list only **one** object, unless the entries are `check` blocks. The argument is a list purely for `check` blocks, which report and carry on. List two variables and the first failure may stop evaluation before the second reports, giving `Missing expected failure` for a condition that was fine. So write one `run` block per failure path. It reads as a table of cases, and each case fails for a single reason. When a negative case behaves oddly, `terraform test -verbose` helps: it prints the plan or state for each `run` block, and in that mode the source also keeps the original diagnostics on display, expected ones included.

  • How do you test a precondition that lives in a child module of the module under test?
    `expect_failures` matches objects only in the root module of what the `run` block executes, so a child module's failing condition stays an ordinary error. Point a `run` block at the child with `module { source = "./modules/subnets" }`, which makes it the root for that block, and list the resource there.
  • When is `expect_failures` with `command = apply` the right pairing?
    When the condition relies on computed attributes, so Terraform does not evaluate it during the plan and it can only fire during apply. If it fires during the plan instead, the run fails because the apply could not happen. Pairing it with apply also means the block creates real objects, so it costs more than a plan-only case.
  • Why does an `expect_failures` test protect you if someone deletes the validation block?
    Because expecting a failure also requires one. With the condition gone nothing fails, so Terraform reports `Missing expected failure` and the run does not pass. A negative test without that behaviour would stay green forever, while the module silently stopped rejecting bad input.

  • expect_failures makes any error in the run acceptable, including provider errors and type mismatches.
  • A run with expect_failures passes whether or not the listed condition actually fires.
  • Listing several input variables in expect_failures reliably checks each of their validations in one run.
  • A failing check block only warns under terraform test, so it can never fail a run.
  • expect_failures should normally be paired with command = apply, because conditions only fail on real applies.
  • expect_failures can name a failing condition anywhere in a nested child module.