# Testing Terraform code

Test modules with terraform test: plan-only and apply runs, assertions and expect_failures. Then see where integration tests with Terratest fit, and what to test at each level.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 14. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/14-testing

## What you will learn

- Place static checks, terraform test and integration tests on a testing pyramid
- Write a .tftest.hcl file with variables, run blocks and assertions
- Test that validation rejects bad input with expect_failures
- Explain what Terratest does and when it's worth the cost

> **Lab status.** **Verified lab:** terraform test failing, then passing with expect_failures. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** Terratest and mock providers: explained, not run. <br />**Cloud lab:** Terratest applies real infrastructure in a test account.

Once a module is used by several teams, "I'll check the plan" isn't enough: a small change can break
someone else's environment. Terraform has a built-in test framework, and for bigger modules there
are integration tests that build real infrastructure. This lesson starts with a test that **fails**,
because it found a real gap in the module from lesson 10.

> **Figure.** A testing pyramid. At the base, static checks: fmt -check, validate, tflint, trivy or checkov, seconds and free on every commit. In the middle, terraform test with .tftest.hcl files: run blocks with command plan or apply, assert and expect_failures; seconds to minutes, and plan-only runs create nothing. At the top, integration tests with Terratest: real apply, call it, destroy; minutes and costs money.
>
> Most tests belong at the bottom. Real-infrastructure tests are for modules many people depend on.

## terraform test

Tests live in files ending in `.tftest.hcl`, usually in a `tests/` folder next to the module. Run
`terraform test` from the module folder. Each file has:

- **`variables`**: input values for every run in the file.
- **`run` blocks**: each one plans or applies the module, then checks **assertions**.

The lab's test for the `site` module:

```hcl
# tests/site.tftest.hcl
variables {
  name  = "shop"
  pages = ["index", "cart"]
}

run "creates_one_file_per_page" {
  command = plan

  assert {
    condition     = length(local_file.page) == 2
    error_message = "Expected one file per page."
  }
}

run "file_names_use_the_site_name" {
  command = apply

  assert {
    condition     = alltrue([for f in output.files : startswith(f, "./out/shop/")])
    error_message = "Every file should live under out/shop/."
  }
}

run "rejects_an_empty_page_list" {
  command = plan

  variables {
    pages = []
  }

  assert {
    condition     = length(local_file.page) > 0
    error_message = "A site needs at least one page."
  }
}
```

What each run does:

1. **`creates_one_file_per_page`** only plans (`command = plan`), so nothing is created. It checks the
   planned resources: two pages in, two files out.
2. **`file_names_use_the_site_name`** applies for real, then checks the module's output. At the end of
   the file, `terraform test` destroys everything the runs created.
3. **`rejects_an_empty_page_list`** overrides `pages` with an empty list and expects the module to
   refuse it.

### The first run: a real failure

```text
$ terraform test
tests/site.tftest.hcl... in progress
  run "creates_one_file_per_page"... pass
  run "file_names_use_the_site_name"... pass
  run "rejects_an_empty_page_list"... fail

Error: Test assertion failed

  on tests/site.tftest.hcl line 32, in run "rejects_an_empty_page_list":
  32:     condition     = length(local_file.page) > 0
    ├────────────────

A site needs at least one page.
tests/site.tftest.hcl... tearing down
tests/site.tftest.hcl... fail

Failure! 2 passed, 1 failed.
```

The module happily planned a site with **zero** pages. Nothing in it said that was wrong. That's
exactly what tests are for.

### The fix, and a better test

First, make the module reject the bad input with a validation rule (lesson 6):

```hcl
# variables.tf
variable "pages" {
  description = "Page names to create."
  type        = list(string)
  default     = ["index"]

  validation {
    condition     = length(var.pages) > 0
    error_message = "A site needs at least one page."
  }
}
```

Then the test should check that validation fails. That's what `expect_failures` is for: the run
passes only if the listed object fails its check.

```hcl
run "rejects_an_empty_page_list" {
  command = plan

  variables {
    pages = []
  }

  expect_failures = [var.pages]
}
```

```text
$ terraform test
tests/site.tftest.hcl... in progress
  run "creates_one_file_per_page"... pass
  run "file_names_use_the_site_name"... pass
  run "rejects_an_empty_page_list"... pass
tests/site.tftest.hcl... tearing down
tests/site.tftest.hcl... pass

Success! 3 passed, 0 failed.
```

If someone later deletes the validation block, this test fails again. That's a test that protects
something.

### More test features

- **`mock_provider "aws" {}`** (Terraform 1.7+) fakes a provider, so apply-mode tests run with no cloud
  account and no cost; computed values get made-up placeholders.
- **`module { source = "./tests/setup" }`** inside a run uses a helper module, for example to create
  a VPC the module under test needs.
- **Runs share state in order**, so a later run can read `run.<name>.<output>` from an earlier one.
- Put `terraform test` in the same CI job as validate. Plan-only tests need no credentials.

## Integration tests

Plan-mode tests prove the code **would** do the right thing. Integration tests prove the real result
works: apply in a sandbox account, then check from the outside that, say, the load balancer answers
on port 80 and the bucket really refuses public reads, then destroy.

They're slow (minutes) and cost money, so use them for modules many teams depend on, run them on a
schedule or before a release rather than on every commit, and always in a separate test account with
a budget alarm.

## Terratest

**Terratest** is an open-source Go library from Gruntwork for these integration tests. A test reads
like this (not run for this course; it needs Go and a cloud account):

```go
// test/site_test.go
package test

import (
	"testing"

	"github.com/gruntwork-io/terratest/modules/terraform"
	"github.com/stretchr/testify/assert"
)

func TestSite(t *testing.T) {
	opts := &terraform.Options{
		TerraformDir: "../examples/basic",
		Vars:         map[string]interface{}{"name": "shop"},
	}
	defer terraform.Destroy(t, opts) // always clean up, even if the test fails

	terraform.InitAndApply(t, opts)

	files := terraform.OutputList(t, opts, "files")
	assert.Equal(t, 1, len(files))
}
```

`InitAndApply` runs real Terraform, `Output...` reads outputs, and Terratest has helpers to make HTTP
requests, SSH into servers and query AWS. With `terraform test` now built in, many teams start there
and add Terratest only where they need Go's flexibility.

## Mission: Write a test that catches a real bug

For the site module from lesson 10, write tests/site.tftest.hcl with a plan-mode run counting files, an apply-mode run checking output paths, and a run proving an empty page list is rejected. Run it, see the last run fail, add the validation block, and run again until all three pass.

- You need: modules/site from lesson 10
- You'll have: tests/site.tftest.hcl

```sh
$ cd modules/site && mkdir -p tests
$ terraform init && terraform test
$ # add the validation block and expect_failures, then:
$ terraform test
```

The lab went from `Failure! 2 passed, 1 failed.` to `Success! 3 passed, 0 failed.` If the first run
passes all three, your module already validates `pages`: remove the rule and watch the test catch it.

## Try it

- Add a tests/ folder with a .tftest.hcl file to a module and run `terraform test`.
- Write a run block with `command = plan` and one with `command = apply`, and compare what they create.
- Make a test fail on purpose and read the error.
- Use expect_failures to prove a validation rule works.
- Do the mini mission and keep `tests/site.tftest.hcl`.

## Quiz

1. What does `command = plan` in a run block mean?
   - The test applies real infrastructure
   - **The test only plans; assertions check planned values, and nothing is created** (answer)
   - The test skips assertions
   Why: Plan-mode runs are fast and free. Apply-mode runs create real resources, check them, and Terraform destroys them at the end of the file.

2. How do you test that a variable's validation rejects an empty list?
   - Assert the list is empty
   - **Set the bad value in the run and list the variable in expect_failures** (answer)
   - You can't test validation
   Why: expect_failures makes the run pass only if those checkable objects (here var.pages) fail. If validation is missing, the test fails.

3. When is a Terratest-style integration test worth it?
   - For every small change
   - **For shared modules many teams rely on, where you need proof the real infrastructure works end to end** (answer)
   - Never
   Why: Integration tests apply real resources, call them and destroy them. They're slow and cost money, so use them where a failure would hurt most.

## Resources

- [Terraform tests](https://developer.hashicorp.com/terraform/language/tests) (HashiCorp)
- [terraform test command](https://developer.hashicorp.com/terraform/cli/commands/test) (HashiCorp)
- [Mocks in Terraform tests](https://developer.hashicorp.com/terraform/language/tests/mocking) (HashiCorp)
- [Terratest](https://terratest.gruntwork.io/) (Gruntwork)
- [Write Terraform tests (tutorial)](https://developer.hashicorp.com/terraform/tutorials/configuration-language/test) (HashiCorp)
