tftest: Terraform Python Testing Helper

1.8.7 · active · verified Thu Apr 16

tftest is a Python package that simplifies testing Terraform modules from Python unit tests. It wraps the Terraform executable, providing convenience methods to set up fixtures, execute Terraform commands (like `init`, `plan`, `apply`, `output`, `destroy`), and parse their outputs. The library is actively maintained, with frequent releases addressing bug fixes, new features, and compatibility updates, often leveraging `pytest` for testing frameworks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `tftest.TerraformTest` with `pytest` to initialize a simple Terraform module, run `terraform output`, and assert the expected value. Ensure the `terraform` CLI is installed and available in your system's PATH for this example to run successfully.

import pytest
import tftest
import os

# This fixture creates a temporary Terraform module for the test.
# In a real project, 'tf_module' would point to your actual Terraform module directory.
@pytest.fixture(scope="module")
def tf_module(tmp_path_factory):
    tf_dir = tmp_path_factory.mktemp("terraform_module_for_tftest")
    (tf_dir / "main.tf").write_text("""
output "greeting" {
  value = "Hello from Terraform!"
}
""")
    
    tf = tftest.TerraformTest(tf_dir)
    tf.setup() # Runs 'terraform init'
    return tf

def test_greeting_output(tf_module):
    # Run 'terraform output' and assert its value
    output = tf_module.output()
    assert output["greeting"]["value"] == "Hello from Terraform!"

view raw JSON →