Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions .github/workflows/linting.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,30 @@

name: Linting
on:
push:
branches:
- master
pull_request:
branches:
- master
tags:
- ci
- lint

permissions:
contents: read

jobs:
linting:
name: Linting
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Set up Python
id: python-setup
uses: actions/setup-python@v2
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.9"
python-version: "3.13"

- name: Install dependencies
id: python-dependencies
Expand All @@ -42,10 +47,10 @@ jobs:
- name: Boilerplate
id: boilerplate
run: |
python3 .github/workflows/scripts/check_boilerplate.py $GITHUB_WORKSPACE
python3 .github/workflows/scripts/check_boilerplate.py "$GITHUB_WORKSPACE"

- name: Check python formatting
id: lint
run: |
yapf --diff --recursive --parallel \
*.py test
*.py test
12 changes: 8 additions & 4 deletions .github/workflows/scripts/check_boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
import sys


_EXCLUDE_DIRS = ('.git', '.terraform')
_EXCLUDE_DIRS = (
'.git', '.terraform', '.venv', 'venv', 'env', 'build', 'dist',
'.pytest_cache', '__pycache__'
)
_MATCH_FILES = (
'Dockerfile', '.py', '.sh', '.tf', '.yaml', '.yml'
)
Expand All @@ -41,9 +44,10 @@ def main(dir):
if fname in _MATCH_FILES or os.path.splitext(fname)[1] in _MATCH_FILES:
fpath = os.path.abspath(os.path.join(root, fname))
try:
if not _MATCH_RE.search(open(fpath).read()):
errors.append(fpath)
except (IOError, OSError):
with open(fpath, encoding='utf-8', errors='ignore') as handle:
if not _MATCH_RE.search(handle.read()):
errors.append(fpath)
except OSError:
warnings.append(fpath)
if warnings:
print('The following files cannot be accessed:')
Expand Down
70 changes: 47 additions & 23 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,58 +14,82 @@

name: Python tests
on:
push:
branches:
- master
pull_request:
branches:
- master
tags:
- ci
- test

permissions:
contents: read

env:
GOOGLE_APPLICATION_CREDENTIALS: "/home/runner/credentials.json"
PYTEST_ADDOPTS: "--color=yes"
PYTHON_VERSION: 3.9
TF_PLUGIN_CACHE_DIR: "/home/runner/.terraform.d/plugin-cache"
TF_VERSION: 1.1.8
TG_VERSION: 0.36.9

jobs:
tests:
name: Python tests
name: Python ${{ matrix.python-version }} (${{ matrix.iac }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.13"]
iac: ["terraform", "opentofu"]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Config auth
id: auth
run: |
echo '{"type": "service_account", "project_id": "test-only"}' \
| tee -a $GOOGLE_APPLICATION_CREDENTIALS
| tee -a "$GOOGLE_APPLICATION_CREDENTIALS"

- name: Set up Python
id: python-setup
uses: actions/setup-python@v2
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ env.PYTHON_VERSION }}
python-version: ${{ matrix.python-version }}

- name: Set up Terraform
id: tf-setup
uses: hashicorp/setup-terraform@v1
if: matrix.iac == 'terraform'
uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: ${{ env.TF_VERSION }}
terraform_wrapper: false

- name: Install Terragrunt
id: tg-setup
run: |
sudo wget -q -O /bin/terragrunt \
https://github.com/gruntwork-io/terragrunt/releases/download/v${{ env.TG_VERSION }}/terragrunt_linux_amd64
sudo chmod +x /bin/terragrunt
terragrunt -v
- name: Set up OpenTofu
if: matrix.iac == 'opentofu'
uses: opentofu/setup-opentofu@a1320f892987e89d278cc92dc5adc984fb93aca4 # v2.0.2
with:
tofu_wrapper: false

- name: Run tests
id: python-test
env:
IAC_FLAVOUR: ${{ matrix.iac }}
run: |
mkdir -p ${{ env.TF_PLUGIN_CACHE_DIR }}
mkdir -p "$TF_PLUGIN_CACHE_DIR"
pip install -r DEV-REQUIREMENTS.txt
pytest -vv
if [ "$IAC_FLAVOUR" = "opentofu" ]; then
pytest -vv --tf-binary=tofu
else
pytest -vv --tf-binary=terraform
fi

python-tests:
name: Python tests
runs-on: ubuntu-latest
needs: tests
if: always()
steps:
- name: Check matrix result
env:
TESTS_RESULT: ${{ needs.tests.result }}
run: |
if [ "$TESTS_RESULT" != "success" ]; then
exit 1
fi
18 changes: 16 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,19 @@
All notable changes to this project will be documented in this file.
<!-- markdownlint-disable MD024 -->

## [Unreleased] <!-- from: 2023-10-11 08:39:19+00:00 to: None since: v1.8.5 -->
## [Unreleased]

## [2.0.0] - 2026-11-20

### BREAKING CHANGES

- Requires Python 3.10+, removes `enable_cache`/`use_cache` method caching, and standardizes `TerraformTest.tfdir` as a `pathlib.Path` object. [[#95](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/pull/95)]

- [[#95](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/pull/95)] Release v2.0.0: cleanup, bug fixes, and packaging/CI modernization ([ludoo](https://github.com/ludoo))

## [1.8.8] - 2026-06-29 <!-- from: 2026-03-31 08:05:11+00:00 to: 2026-06-29 13:52:30+00:00 since: v1.8.7 -->

- [[#93](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/pull/93)] Fix TypeError when calling decorated methods with positional arguments ([ludoo](https://github.com/ludoo)) <!-- 2026-06-29 13:47:18+00:00 -->

## [1.8.7] - 2026-03-31

Expand Down Expand Up @@ -216,7 +228,9 @@ All notable changes to this project will be documented in this file.
<!-- 2019-09-10 06:58:18+00:00 < None -->

<!-- markdown-link-check-disable -->
[Unreleased]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v1.8.7...HEAD
[Unreleased]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v2.0.0...HEAD
[2.0.0]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v1.8.8...v2.0.0
[1.8.8]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v1.8.7...v1.8.8
[1.8.7]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v1.8.4...v1.8.7
[1.8.5]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v1.8.4...v1.8.5
[1.8.4]: https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/compare/v1.8.3...v1.8.4
Expand Down
69 changes: 24 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
# Python Test Helper for Terraform
# Python Test Helper for Terraform and OpenTofu

This simple helper facilitates testing Terraform modules from Python unit tests, by wrapping the Terraform executable and exposing convenience methods to set up fixtures, execute Terraform commands, and parse their output.
This simple helper facilitates testing Terraform and OpenTofu modules from Python unit tests by wrapping the `terraform` (or `tofu`) executable and exposing convenience methods to set up fixtures, execute commands, and parse their output.

It allows for different types of tests: lightweight tests that only use Terraform `init` and `plan` to ensure code is syntactically correct and the right number and type of resources should be created, or full-fledged tests that run the full `apply`/`output`/`destroy` cycle, and can then be used to test the actual created resources, or the state file.
It supports both lightweight tests that only run `init` and `plan` to ensure code is valid and creates the expected resources, and full end-to-end tests that run `apply`, `output`, and `destroy` against live environments or local state.

As an additional convenience, the module also provides an easy way to request and access the plan output (via `terraform plan -out` and `terraform show`) and the outputs (via `terraform output -json`), and return them wrapped in simple classes that streamline accessing their attributes.
As an additional convenience, the module provides parsed wrappers around JSON plan output (via `terraform plan -out` and `terraform show -json`), module outputs (via `terraform output -json`), and pulled state (`terraform state pull`).

This module is heavily inspired by two projects: [Terratest](https://github.com/gruntwork-io/terratest) for the lightweight approach to testing Terraform, and [python-terraform](https://github.com/beelit94/python-terraform) for wrapping the Terraform command in Python.
This module is inspired by [Terratest](https://github.com/gruntwork-io/terratest) for the lightweight approach to testing Terraform, and [python-terraform](https://github.com/beelit94/python-terraform) for wrapping the CLI in Python.

## Example Usage

The [`test`](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/tree/master/test) folder contains simple examples on how to write tests for both `plan` and `apply`, using either synthetic fixtures (simple representations of the plan output and output files), or minimal root modules. More examples can be found in the [Cloud Foundation Fabric](https://github.com/terraform-google-modules/cloud-foundation-fabric) repository, for which this module was developed.
The [`test`](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/tree/master/test) folder contains examples of tests for both `plan` and `apply`, using synthetic JSON fixtures and minimal root modules. Extensive real-world usage can be found in the [Cloud Foundation Fabric](https://github.com/GoogleCloudPlatform/cloud-foundation-fabric) repository, for which this module was originally developed.

This is a test that uses plan output on an actual module:
Using `TerraformTest` as a context manager ensures linked files and runtime artifacts (`.terraform/`, state files, and generated lockfiles) are cleaned up deterministically when the block exits:

```hcl
```python
import pytest
import tftest


@pytest.fixture
def plan(fixtures_dir):
tf = tftest.TerraformTest('plan', fixtures_dir)
tf.setup(extra_files=['plan.auto.tfvars'])
return tf.plan(output=True)
with tftest.TerraformTest('plan', fixtures_dir) as tf:
tf.setup(extra_files=['plan.auto.tfvars'])
yield tf.plan(output=True)


def test_variables(plan):
Expand All @@ -46,50 +46,29 @@ def test_modules(plan):
assert res['values']['location'] == plan.variables['gcs_location']
```

## Caching

The `TerraformTest` `setup`, `init`, `plan`, `apply`, `output` and `destroy` methods have the ability to cache it's associate output to a local `.tftest-cache` directory. For subsequent calls of the method, the cached value can be returned instead of calling the actual underlying `terraform` command. Using the cache value can be significantly faster than running the Terraform command again especially if the command is time-intensive.

To determine if the cache should be used, first a hash value is generated using the current `TerraformTest` instance `__init__` and calling method arguments, file contents of the `tfdir` and file contents of any `tf_var_file` or `extra_files` method argument. The hash value is compared to the hash value of the cached instance's associated arguments. If the hash is the same then the cache is used, otherwise the method is executed.

The benefits of the caching feature include:
- Faster setup time for testing terraform modules that don't change between testing sessions
- Writing tests without worrying about errors within their test code resulting in the Terraform setup logic to run again

Please see the following example for how to use it:
To inspect or reuse a binary plan file directly, pass `plan_out` to `plan()` and optionally pass `plan_file` to `apply()`:

```python
import pytest
import tftest


@pytest.fixture
def output(fixtures_dir):
tf = tftest.TerraformTest('apply', fixtures_dir, enable_cache=True)
tf.setup(use_cache=True)
tf.apply(use_cache=True)
yield tf.output(use_cache=True)
tf.destroy(use_cache=True, **{"auto_approve": True})


def test_apply(output):
value = output['triggers']
assert len(value) == 2
assert list(value[0].keys()) == ['name', 'template']
assert value[0]['name'] == 'one'

def test_saved_plan(fixtures_dir, tmp_path):
plan_file = tmp_path / 'out.tfplan'
with tftest.TerraformTest('apply', fixtures_dir) as tf:
tf.setup()
tf.plan(plan_out=plan_file, tf_vars={'names': ['one']})
tf.apply(plan_file=plan_file)
assert tf.output()['triggers'][0]['name'] == 'one'
tf.destroy()
```


To run against OpenTofu instead of Terraform, pass `binary='tofu'` when instantiating `TerraformTest`.

## Compatibility

Starting from version `1.0.0` Terraform `0.12` is required, and tests written with previous versions of this module are incompatible. Check the [`CHANGELOG.md`](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/blob/master/CHANGELOG.md) file for details on what's changed.
Version `2.0.0` requires Python `3.10` or newer, standardizes `tf.tfdir` as a `pathlib.Path` object, and removes the experimental method caching layer (`enable_cache` / `use_cache`). Terragrunt support was removed in `1.8.6`. Check [`CHANGELOG.md`](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/blob/master/CHANGELOG.md) for full release history.

## Testing

Tests use the `pytest` framework and have no other dependency except on the Terraform binary. The version used during development is in the `DEV-REQUIREMENTS.txt` file.
Tests use `pytest` and have no runtime dependencies beyond a `terraform` or `tofu` binary (`pytest --tf-binary=tofu`). Development dependencies are listed in `DEV-REQUIREMENTS.txt`.

## Disclaimer

This is not an officially supported Google product.
This is not an officially supported Google product.
46 changes: 46 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "tftest"
dynamic = ["version"]
description = "Simple Terraform and OpenTofu test helper"
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
authors = [
{ name = "Ludovico Magnocavallo", email = "ludomagno@google.com" },
]
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
]

[project.urls]
Homepage = "https://github.com/GoogleCloudPlatform/terraform-python-testing-helper"

[tool.setuptools]
py-modules = ["tftest"]

[tool.setuptools.dynamic]
version = { attr = "tftest.__version__" }
Loading
Loading