diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index 296c506..7bef9cc 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -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 @@ -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 diff --git a/.github/workflows/scripts/check_boilerplate.py b/.github/workflows/scripts/check_boilerplate.py index 762d67d..f8647e6 100755 --- a/.github/workflows/scripts/check_boilerplate.py +++ b/.github/workflows/scripts/check_boilerplate.py @@ -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' ) @@ -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:') diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 46dc3f8..6be9111 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index d620677..ebe1a19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,19 @@ All notable changes to this project will be documented in this file. -## [Unreleased] +## [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 + +- [[#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)) ## [1.8.7] - 2026-03-31 @@ -216,7 +228,9 @@ All notable changes to this project will be documented in this file. -[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 diff --git a/README.md b/README.md index 10e6377..5c1ee1e 100644 --- a/README.md +++ b/README.md @@ -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): @@ -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. \ No newline at end of file +This is not an officially supported Google product. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..775fddb --- /dev/null +++ b/pyproject.toml @@ -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__" } diff --git a/setup.py b/setup.py deleted file mode 100644 index d14e223..0000000 --- a/setup.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright 2019 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. - -import setuptools - -from tftest import __version__ - -with open("README.md", "r") as fh: - long_description = fh.read() - -setuptools.setup( - name="tftest", - version=__version__, - author="Ludovico Magnocavallo", - author_email="ludomagno@google.com", - description="Simple Terraform test helper", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/GoogleCloudPlatform/terraform-python-testing-helper", - py_modules=['tftest'], - classifiers=[ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: Apache Software License", - "Operating System :: OS Independent", - ], - setup_requires=['nose>=1.3'], - test_suite='nose.collector', -) diff --git a/test/conftest.py b/test/conftest.py index 149aff0..d57022a 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -14,6 +14,29 @@ import os import pytest +import tftest + + +def pytest_addoption(parser): + parser.addoption('--tf-binary', action='store', + default=os.environ.get('TFTEST_BINARY', 'terraform'), + help='Terraform or OpenTofu binary to use in tests.') + + +@pytest.fixture(scope='session', autouse=True) +def configure_tf_binary(request): + binary = request.config.getoption('--tf-binary') + if binary != 'terraform': + orig_init = tftest.TerraformTest.__init__ + + def _init(self, tfdir, basedir=None, binary=binary, env=None): + orig_init(self, tfdir, basedir=basedir, binary=binary, env=env) + + with pytest.MonkeyPatch.context() as mp: + mp.setattr(tftest.TerraformTest, '__init__', _init) + yield + else: + yield @pytest.fixture(scope='session') diff --git a/test/test_args.py b/test/test_args.py index 3e0ab0e..d855a11 100644 --- a/test/test_args.py +++ b/test/test_args.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. "Test the function for mapping Terraform arguments." +from pathlib import Path import pytest import tftest @@ -99,6 +100,15 @@ ({ 'tf_var_file': ['foo.tfvar', 'bar.tfvar'] }, ['-var-file=foo.tfvar', '-var-file=bar.tfvar']), + ({ + 'tf_var_file': ('foo.tfvar', 'bar.tfvar') + }, ['-var-file=foo.tfvar', '-var-file=bar.tfvar']), + ({ + 'plan_out': 'plan.out' + }, ['-out=plan.out']), + ({ + 'init_vars': Path('backend.hcl') + }, ['-backend-config', 'backend.hcl']), ({ 'tf_vars': { 'text': 'text' @@ -113,7 +123,12 @@ 'tf_vars': { 'bool': False } - }, ['-var', 'bool=False']), + }, ['-var', 'bool=false']), + ({ + 'tf_vars': { + 'bool': True + } + }, ['-var', 'bool=true']), ({ 'tf_vars': { 'dict': { @@ -159,4 +174,4 @@ def test_targets(): def test_parallelism_arg(): - assert tftest.parse_args(parallelism=10) == ['-parallelism', 10] + assert tftest.parse_args(parallelism=10) == ['-parallelism', '10'] diff --git a/test/test_backend_config.py b/test/test_backend_config.py index 3e1ebd0..94634e1 100644 --- a/test/test_backend_config.py +++ b/test/test_backend_config.py @@ -11,18 +11,24 @@ # 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. -"Test the plan output wrapper classes." +"Test local backend configuration arguments." +from pathlib import Path +import shutil import pytest import tftest @pytest.fixture -def run_init(fixtures_dir): +def run_init(fixtures_dir, tmp_path): + mod_dir = tmp_path / 'backend_config' + shutil.copytree(Path(fixtures_dir) / 'backend_config', mod_dir) def init_runner(**backend_config): - tf = tftest.TerraformTest('apply', fixtures_dir) - tf.setup(init_vars=backend_config) + with tftest.TerraformTest(mod_dir) as tf: + tf.setup(init_vars=backend_config) + tf.apply() + assert (mod_dir / backend_config['path']).is_file() return init_runner diff --git a/test/test_cache.py b/test/test_cache.py deleted file mode 100644 index 124e3d2..0000000 --- a/test/test_cache.py +++ /dev/null @@ -1,211 +0,0 @@ -# Copyright 2019 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. - -import logging -import os -import shutil -import uuid -import json -import pytest -import tftest -from unittest.mock import patch, DEFAULT, Mock - -pytest_plugins = [ - str("_pytest.pytester"), -] - -_LOGGER = logging.getLogger('tftest') - -cache_methods = ["setup", "init", "plan", "apply", "output", "destroy"] - - -@pytest.fixture -def tf(request, fixtures_dir): - terra = tftest.TerraformTest( - tfdir='plan_no_resource_changes', - basedir=fixtures_dir, - enable_cache=request.param, - ) - yield terra - - _LOGGER.debug("Removing cache dir") - try: - shutil.rmtree(terra.cache_dir) - except FileNotFoundError: - _LOGGER.debug("%s does not exists", terra.cache_dir) - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache(tf): - """ - Ensures cache is used and runs the execute_command() for first call of the - method only - """ - for method in cache_methods: - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(2): - getattr(tf, method)(use_cache=True) - assert mock_execute_command.call_count == 1 - - -@pytest.mark.parametrize("tf", [ - pytest.param(True, id="enable_cache"), - pytest.param(False, id="disable_cache"), -], indirect=True) -def test_no_use_cache(tf): - expected_call_count = 2 - for method in cache_methods: - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(expected_call_count): - getattr(tf, method)(use_cache=False) - assert mock_execute_command.call_count == expected_call_count - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache_with_same_tf_var_file(tf, tmp_path): - """ - Ensures cache is used if the same tf_var_file argument is passed - within subsequent method calls - """ - tf_var_file_methods = ["plan", "apply", "destroy"] - - tf_vars_file = tmp_path / (str(uuid.uuid4()) + '.json') - tf_vars_file.write_text(json.dumps({"foo": "old"})) - - for method in tf_var_file_methods: - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(2): - getattr(tf, method)(use_cache=True, tf_var_file=tf_vars_file) - - assert mock_execute_command.call_count == 1 - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache_with_new_tf_var_file(tf, tmp_path): - """ - Ensures cache is not used if a different tf_var_file argument is passed - within subsequent method calls - """ - tf_var_file_methods = ["plan", "apply", "destroy"] - expected_call_count = 2 - - tf_vars_file = tmp_path / (str(uuid.uuid4()) + '.json') - - for method in tf_var_file_methods: - tf_vars_file.write_text(json.dumps({"foo": "old"})) - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(expected_call_count): - getattr(tf, method)(use_cache=True, tf_var_file=tf_vars_file) - tf_vars_file.write_text(json.dumps({"foo": "new"})) - - assert mock_execute_command.call_count == expected_call_count - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache_with_new_extra_files(tf, tmp_path): - """ - Ensures cache is not used if a different extra_files argument is passed - within subsequent method calls - """ - expected_call_count = 2 - tf_vars_file = tmp_path / (str(uuid.uuid4()) + '.json') - tf_vars_file.write_text(json.dumps({"foo": "old"})) - - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(expected_call_count): - tf.setup(use_cache=True, extra_files=[tf_vars_file]) - tf_vars_file.write_text(json.dumps({"foo": "new"})) - - assert mock_execute_command.call_count == expected_call_count - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache_with_same_extra_files(tf, tmp_path): - """ - Ensures cache is used if the same extra_files argument is passed - within subsequent method calls - """ - tf_vars_file = tmp_path / (str(uuid.uuid4()) + '.json') - tf_vars_file.write_text(json.dumps({"foo": "old"})) - - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(2): - tf.setup(use_cache=True, extra_files=[tf_vars_file]) - - assert mock_execute_command.call_count == 1 - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache_with_new_env(tf): - """ - Ensures cache is not used if the env attribute is updated - before subsequent method calls - """ - expected_call_count = 2 - for method in cache_methods: - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(expected_call_count): - getattr(tf, method)(use_cache=True) - tf._env["foo"] = "bar" - - assert mock_execute_command.call_count == expected_call_count - - del tf._env["foo"] - - -@pytest.fixture -def dummy_tf_filepath(tf): - filepath = os.path.join(tf.tfdir, "bar.txt") - with open(filepath, "w") as f: - f.write("old") - - yield filepath - - os.remove(filepath) - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_use_cache_with_new_tf_content(tf, dummy_tf_filepath): - """ - Ensures cache is not used if the tfdir directory is updated - before subsequent method calls - """ - expected_call_count = 2 - for method in cache_methods: - with patch.object(tf, 'execute_command', - wraps=tf.execute_command) as mock_execute_command: - for _ in range(expected_call_count): - getattr(tf, method)(use_cache=True) - with open(dummy_tf_filepath, "w") as f: - f.write(str(uuid.uuid4())) - - assert mock_execute_command.call_count == expected_call_count - - -@pytest.mark.parametrize("tf", [True], indirect=True) -def test_output_positional_arg(tf): - """ - Ensures output() can be called with positional arguments when caching is enabled - """ - with patch.object(tf, 'execute_command') as mock_execute: - mock_execute.return_value.out = "{}" - tf.output("my_output", use_cache=True) - assert mock_execute.call_count == 1 diff --git a/test/test_files.py b/test/test_files.py index 8b5435f..d189ebb 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -11,23 +11,64 @@ # 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. -"Test fixture file setup and removal." +"Test fixture file setup, directory linking, and cleanup behavior." import os +from pathlib import Path import tempfile import tftest def test_setup_files(): with tempfile.TemporaryDirectory() as tmpdir: + with tempfile.NamedTemporaryFile(delete=False) as tmpfile: + tmpfile_path = Path(tmpfile.name) try: - with tempfile.NamedTemporaryFile(delete=False) as tmpfile: - tf = tftest.TerraformTest(tmpdir) - tf.setup(extra_files=[tmpfile.name]) - assert os.path.exists( - os.path.join(tmpdir, os.path.basename(tmpfile.name))) - tf = None - assert not os.path.exists( - os.path.join(tmpdir, os.path.basename(tmpfile.name))) + tf = tftest.TerraformTest(tmpdir, basedir=tmpfile_path.parent) + tf.setup(extra_files=[tmpfile_path.name]) + assert (Path(tmpdir) / tmpfile_path.name).exists() + tf = None + assert not (Path(tmpdir) / tmpfile_path.name).exists() finally: - os.unlink(tmpfile.name) + tmpfile_path.unlink(missing_ok=True) + + +def test_setup_files_and_dirs_with_context_manager(tmp_path): + mod_dir = tmp_path / 'mod' + mod_dir.mkdir() + (mod_dir / 'main.tf').write_text('output "ok" {\n value = true\n}\n') + extra_file = tmp_path / 'extra.auto.tfvars' + extra_file.write_text('') + extra_dir = tmp_path / 'sub_dir' + extra_dir.mkdir() + (extra_dir / 'nested.txt').write_text('hello') + + with tftest.TerraformTest(mod_dir) as tf: + tf.setup(extra_files=[extra_file, extra_dir]) + assert (mod_dir / 'extra.auto.tfvars').is_file() + assert (mod_dir / 'sub_dir' / 'nested.txt').is_file() + + assert not (mod_dir / 'extra.auto.tfvars').exists() + assert not (mod_dir / 'sub_dir').exists() + assert (extra_dir / 'nested.txt').is_file() + + +def test_existing_lockfile_preserved_on_cleanup(fixtures_dir, tmp_path): + mod_with_lock = tmp_path / 'with_lock' + mod_with_lock.mkdir() + (mod_with_lock / 'main.tf').write_text('terraform {}\n') + lockfile = mod_with_lock / '.terraform.lock.hcl' + lockfile.write_text('# existing lockfile\n') + + with tftest.TerraformTest(mod_with_lock) as tf: + tf.setup() + assert lockfile.is_file() + assert lockfile.read_text() == '# existing lockfile\n' + + mod_without_lock = tmp_path / 'without_lock' + mod_without_lock.mkdir() + (mod_without_lock / 'main.tf').write_text('resource "null_resource" "x" {}\n') + with tftest.TerraformTest(mod_without_lock) as tf: + tf.setup() + assert (mod_without_lock / '.terraform.lock.hcl').is_file() + assert not (mod_without_lock / '.terraform.lock.hcl').exists() diff --git a/test/test_no_outputs.py b/test/test_no_outputs.py index e95060d..8e1c61c 100644 --- a/test/test_no_outputs.py +++ b/test/test_no_outputs.py @@ -19,9 +19,9 @@ @pytest.fixture(scope="module") def plan(fixtures_dir): - tf = tftest.TerraformTest('no_outputs', fixtures_dir) - tf.setup(extra_files=['plan.auto.tfvars']) - return tf.plan(output=True) + with tftest.TerraformTest('no_outputs', fixtures_dir) as tf: + tf.setup(extra_files=['plan.auto.tfvars']) + yield tf.plan(output=True) def test_variables(plan): diff --git a/test/test_pickle.py b/test/test_pickle.py deleted file mode 100644 index 1325179..0000000 --- a/test/test_pickle.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2019 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. -"Test serialization of tftest instances" - -import pytest -import tftest -import pickle - - -def assert_pickle_flow(obj): - """Ensures instance is the same after being pickled""" - pickled_obj = pickle.dumps(obj) - pickled_obj = pickle.loads(pickled_obj) - assert isinstance(pickled_obj, type(obj)) - - -@pytest.fixture(scope="module") -def tf(fixtures_dir): - tf = tftest.TerraformTest("plan_no_resource_changes", fixtures_dir) - tf.setup() - return tf - - -def test_setup(fixtures_dir): - tf = tftest.TerraformTest("plan_no_resource_changes", fixtures_dir) - expected = tf.setup() - assert_pickle_flow(expected) - - -def test_plan(tf): - expected = tf.plan(output=True) - assert_pickle_flow(expected) - - -def test_apply(tf): - expected = tf.apply() - assert_pickle_flow(expected) - - -def test_output(tf): - expected = tf.output() - assert_pickle_flow(expected) - - -def test_state_pull(tf): - expected = tf.state_pull() - assert_pickle_flow(expected) diff --git a/test/test_plan.py b/test/test_plan.py index e680bae..4bcc359 100644 --- a/test/test_plan.py +++ b/test/test_plan.py @@ -13,6 +13,11 @@ # limitations under the License. "Test the plan output wrapper classes." +import copy +from pathlib import Path +import pickle +import shutil +import tempfile import pytest import tftest @@ -106,3 +111,47 @@ def test_plan_prior_state(plan_out): def test_plan_no_prior_state(plan_out_no_prior): prior_resources = plan_out_no_prior.prior_resources assert not prior_resources + + +def test_plan_null_prior_state(): + plan = tftest.TerraformPlanOutput({'prior_state': None, 'variables': None}) + assert plan.prior_resources == {} + assert dict(plan.variables) == {} + + +def test_plan_getattr_and_serialization(plan_out): + assert not hasattr(plan_out, 'nonexistent_attribute') + assert getattr(plan_out, 'nonexistent_attribute', 'fallback') == 'fallback' + copied = copy.deepcopy(plan_out) + assert copied.format_version == plan_out.format_version + unpickled = pickle.loads(pickle.dumps(plan_out)) + assert unpickled.resources == plan_out.resources + + +def test_plan_output_does_not_leak_temp_files(fixtures_dir): + tmp_root = Path(tempfile.gettempdir()) + before = set(tmp_root.glob('tmp*')) + with tftest.TerraformTest('plan_no_resource_changes', fixtures_dir) as tf: + tf.setup() + result = tf.plan(output=True) + assert result.outputs['just_an_output'] == 'Hello, plan!' + after = set(tmp_root.glob('tmp*')) + assert after - before == set() + + +def test_plan_out_and_apply_plan_file(fixtures_dir, tmp_path): + mod_dir = tmp_path / 'apply_mod' + shutil.copytree(Path(fixtures_dir) / 'apply', mod_dir) + saved_plan = tmp_path / 'saved.tfplan' + + with tftest.TerraformTest(mod_dir) as tf: + tf.setup() + plan = tf.plan(output=True, plan_out=saved_plan, + tf_vars={'names': ['alpha']}) + assert saved_plan.is_file() + assert 'null_resource.sample["alpha"]' in plan.resources + tf.apply(plan_file=saved_plan) + out = tf.output() + assert len(out['triggers']) == 1 + assert out['triggers'][0]['name'] == 'alpha' + assert saved_plan.is_file() diff --git a/test/test_prevent_destroy.py b/test/test_prevent_destroy.py index 874943c..bfbd032 100644 --- a/test/test_prevent_destroy.py +++ b/test/test_prevent_destroy.py @@ -13,6 +13,8 @@ # limitations under the License. "Test init and plan with prevent_destroy lifecycles" import logging +from pathlib import Path +import shutil from unittest.mock import mock_open, patch import pytest @@ -20,19 +22,40 @@ def test_with_no_lifecycle_override(fixtures_dir): - tf = tftest.TerraformTest('prevent_destroy', fixtures_dir) - tf.setup() - tf.apply(auto_approve=True) - with pytest.raises(tftest.TerraformTestError): + with tftest.TerraformTest('prevent_destroy', fixtures_dir) as tf: + tf.setup() + tf.apply(auto_approve=True) + with pytest.raises(tftest.TerraformTestError): + tf.destroy(auto_approve=True) + tf.setup(disable_prevent_destroy=True) tf.destroy(auto_approve=True) - tf.output() def test_with_with_lifecycle_override(fixtures_dir): - tf = tftest.TerraformTest('prevent_destroy', fixtures_dir) - tf.setup(disable_prevent_destroy=True) - tf.apply(auto_approve=True) - tf.destroy(auto_approve=True) + with tftest.TerraformTest('prevent_destroy', fixtures_dir) as tf: + tf.setup(disable_prevent_destroy=True) + tf.apply(auto_approve=True) + tf.destroy(auto_approve=True) + + +def test_compact_syntax_and_idempotent_setup(tmp_path, monkeypatch): + mod_dir = tmp_path / 'bkp_mod' + mod_dir.mkdir() + main_tf = mod_dir / 'main.tf' + original = ('resource "terraform_data" "x" {\n' + ' lifecycle {\n' + ' prevent_destroy=true\n' + ' }\n' + '}\n') + main_tf.write_text(original) + monkeypatch.chdir(tmp_path) + with tftest.TerraformTest('./bkp_mod') as tf: + tf.setup(disable_prevent_destroy=True) + tf.setup(disable_prevent_destroy=True) + tf.apply(auto_approve=True) + tf.destroy(auto_approve=True) + assert main_tf.read_text() == original + assert not (mod_dir / 'main.tf.bkp').exists() @patch('tftest.shutil.copy') diff --git a/test/test_sample_plan.py b/test/test_sample_plan.py index 2e9e107..2f25f98 100644 --- a/test/test_sample_plan.py +++ b/test/test_sample_plan.py @@ -19,9 +19,9 @@ @pytest.fixture(scope="module") 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): diff --git a/test/test_sample_plan_error.py b/test/test_sample_plan_error.py index 0ea1f1e..f20614f 100644 --- a/test/test_sample_plan_error.py +++ b/test/test_sample_plan_error.py @@ -11,8 +11,10 @@ # 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. -"Test command out attribute of tftest exception class." +"Test command execution, error handling, parallelism, and bool variables." +from pathlib import Path +import sys import pytest import tftest @@ -22,8 +24,55 @@ def test_cmd_err(fixtures_dir): tf = tftest.TerraformTest('foobar') tf.setup() assert not e.value.cmd_error - tf = tftest.TerraformTest('plan', fixtures_dir) - tf.setup() + with tftest.TerraformTest('plan', fixtures_dir) as tf: + tf.setup() + with pytest.raises(tftest.TerraformTestError) as e: + tf.plan() + assert e.value.cmd_error + + +def test_missing_binary_raises(tmp_path): + tf = tftest.TerraformTest(tmp_path, binary='nonexistent-terraform-binary-xyz') + with pytest.raises(tftest.TerraformTestError) as e: + tf.setup() + assert e.value.cmd_error is None + + +def test_bool_tf_vars_and_parallelism_execution(tmp_path): + (tmp_path / 'main.tf').write_text('variable "flag" {\n' + ' type = bool\n' + '}\n' + 'output "flag" {\n' + ' value = var.flag\n' + '}\n') + with tftest.TerraformTest(tmp_path) as tf: + tf.setup() + plan = tf.plan(output=True, parallelism=5, tf_vars={'flag': True}) + assert plan.outputs['flag'] is True + + +def test_nonzero_exit_codes_and_large_stderr(tmp_path): + helper = tmp_path / 'fake_tf.py' + helper.write_text('import sys\n' + 'cmd = sys.argv[1]\n' + 'if cmd == "panic":\n' + ' sys.stderr.write("E" * 200000 + "\\n")\n' + ' sys.exit(2)\n' + 'if cmd == "plan" and "-detailed-exitcode" in sys.argv:\n' + ' sys.stdout.write("changes present\\n")\n' + ' sys.exit(2)\n' + 'sys.exit(0)\n') + wrapper = tmp_path / 'fake_tf.sh' + wrapper.write_text( + f'#!/usr/bin/env bash\nexec "{sys.executable}" "{helper}" "$@"\n') + wrapper.chmod(0o755) + + tf = tftest.TerraformTest(tmp_path, binary=wrapper) with pytest.raises(tftest.TerraformTestError) as e: - tf.plan() - assert e.value.cmd_error + tf.execute_command('panic') + assert e.value.cmd_error is not None + assert len(e.value.cmd_error) >= 200000 + + res = tf.execute_command('plan', '-detailed-exitcode') + assert res.retcode == 2 + assert 'changes present' in res.out diff --git a/test/test_state.py b/test/test_state.py index 72ccbae..752fdf1 100644 --- a/test/test_state.py +++ b/test/test_state.py @@ -37,3 +37,40 @@ def test_resources(state): res = state.resources['module.vpc-remote.google_compute_network.network'] assert res['mode'] == 'managed' assert res['instances'][0]['attributes']['name'] == 'remote' + + +def test_root_and_data_resources_and_empty_state(): + raw = { + 'version': + 4, + 'resources': [ + { + 'mode': 'managed', + 'type': 'null_resource', + 'name': 'root_item', + 'instances': [], + }, + { + 'mode': 'data', + 'type': 'null_resource', + 'name': 'root_item', + 'instances': [], + }, + { + 'module': 'module.child', + 'mode': 'data', + 'type': 'google_client_config', + 'name': 'current', + 'instances': [], + }, + ], + } + st = tftest.TerraformState(raw) + assert set(st.resources.keys()) == { + 'null_resource.root_item', + 'data.null_resource.root_item', + 'module.child.data.google_client_config.current', + } + assert not hasattr(st, 'nonexistent_attr') + empty = tftest.TerraformState({'version': 4}) + assert empty.resources == {} diff --git a/test/test_tfdir_path.py b/test/test_tfdir_path.py index bf9123a..83f05e8 100644 --- a/test/test_tfdir_path.py +++ b/test/test_tfdir_path.py @@ -21,12 +21,24 @@ def test_tfdir_as_path(): with tempfile.TemporaryDirectory() as tmpdir: tmpdir_path = Path(tmpdir).resolve() tf = tftest.TerraformTest(tmpdir_path) - # The regression: tf.tfdir / 'something' throws TypeError - # if tf.tfdir is converted to a string. + assert isinstance(tf.tfdir, Path) assert (tf.tfdir / 'something') == tmpdir_path / 'something' def test_tfdir_as_str(): with tempfile.TemporaryDirectory() as tmpdir: tf = tftest.TerraformTest(tmpdir) - assert isinstance(tf.tfdir, str) + assert isinstance(tf.tfdir, Path) + assert (tf.tfdir / 'something') == Path(tmpdir) / 'something' + + +def test_tfdir_relative(): + with tempfile.TemporaryDirectory() as tmpdir: + sub = Path(tmpdir) / 'child' + sub.mkdir() + tf_from_str = tftest.TerraformTest('child', basedir=tmpdir) + tf_from_path = tftest.TerraformTest(Path('child'), basedir=Path(tmpdir)) + assert isinstance(tf_from_str.tfdir, Path) + assert isinstance(tf_from_path.tfdir, Path) + assert tf_from_str.tfdir == sub + assert tf_from_path.tfdir == sub diff --git a/test/test_workspace.py b/test/test_workspace.py index 2737c67..cdb7034 100644 --- a/test/test_workspace.py +++ b/test/test_workspace.py @@ -13,19 +13,19 @@ # limitations under the License. "Test init and plan using an actual example." +from pathlib import Path import pytest import tftest -import shutil -import os @pytest.fixture(scope='module') def terraform_test(fixtures_dir): - tf = tftest.TerraformTest('plan_no_variables', fixtures_dir) - tf.setup() - yield tf - shutil.rmtree(os.path.join(tf.tfdir, 'terraform.tfstate.d')) - os.remove(os.path.join(tf.tfdir, '.terraform.lock.hcl')) + with tftest.TerraformTest('plan_no_variables', fixtures_dir) as tf: + tf.setup() + tf_dir = tf.tfdir + yield tf + assert not (Path(tf_dir) / 'terraform.tfstate.d').exists() + assert not (Path(tf_dir) / '.terraform.lock.hcl').exists() def test_new_workspace(terraform_test): diff --git a/tftest.py b/tftest.py index e34d738..c05eb30 100644 --- a/tftest.py +++ b/tftest.py @@ -11,62 +11,77 @@ # 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. -"""Simple Python wrapper for Terraform test fixtures. +"""Simple Python wrapper for Terraform and OpenTofu test fixtures. See documentation in the TerraformTest class for usage. Terraform wrapping inspired by https://github.com/beelit94/python-terraform """ import collections -import inspect +import collections.abc import itertools import json import logging import os -import pickle import re import shutil import stat import subprocess import sys import tempfile +import threading import weakref -from hashlib import sha1 from pathlib import Path -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, Iterable, List, Optional, Sequence, Union -__version__ = '1.8.8' +__version__ = '2.0.0' _LOGGER = logging.getLogger('tftest') +PathType = Union[str, os.PathLike] + TerraformCommandOutput = collections.namedtuple('TerraformCommandOutput', 'retcode out err') -TerraformStateResource = collections.namedtuple( - 'TerraformStateResource', 'key provider type attributes depends_on raw') + +def _rmtree(path: Path) -> None: + """Remove a directory tree, clearing read-only bits if needed.""" + + def remove_readonly(func: Any, fpath: str, exc: Any) -> None: + _LOGGER.warning('Issue deleting file %s, caused by %s', fpath, exc) + os.chmod(fpath, stat.S_IWRITE) + func(fpath) + + if sys.version_info >= (3, 12): + shutil.rmtree(path, onexc=remove_readonly) + else: + shutil.rmtree(path, onerror=remove_readonly) class TerraformTestError(Exception): @property - def cmd_error(self): + def cmd_error(self) -> Optional[str]: return self.args[1] if len(self.args) > 1 else None -def parse_args(init_vars=None, tf_vars=None, targets=None, **kw): +def parse_args(init_vars: Optional[Union[Dict[str, Any], PathType]] = None, + tf_vars: Optional[Dict[str, Any]] = None, + targets: Optional[Iterable[str]] = None, **kw: Any) -> List[str]: """Convert method arguments for use in Terraform commands. Args: - init_vars: dict of key/values converted to -backend-config='k=v' form, or - string argument converted to -backend-config=arg + init_vars: dict of key/values converted to -backend-config=k=v form, or + string/path argument converted to -backend-config arg. tf_vars: dict of key/values converted to -var k=v form. + targets: iterable of resource addresses converted to -target=addr. **kw: converted to the appropriate Terraform flag. Returns: A list of command arguments for use with subprocess. """ - cmd_args = [] + cmd_args: List[str] = [] bool_flags = { 'auto_approve': '-auto-approve', @@ -95,473 +110,396 @@ def parse_args(init_vars=None, tf_vars=None, targets=None, **kw): 'state': '-state', } for kwarg, flag in kv_flags.items(): - if kw.get(kwarg): - cmd_args.extend([flag, kw[kwarg]]) + val = kw.get(kwarg) + if val is not None and val != '': + cmd_args.extend([flag, str(val)]) if isinstance(init_vars, dict): cmd_args += [f'-backend-config={k}={v}' for k, v in init_vars.items()] - elif isinstance(init_vars, str): - cmd_args += ['-backend-config', f'{init_vars}'] + elif isinstance(init_vars, (str, os.PathLike)): + cmd_args += ['-backend-config', str(init_vars)] + if tf_vars: cmd_args += list( - itertools.chain.from_iterable( - ("-var", - f"{k}={json.dumps(v) if isinstance(v, (dict, list)) else v}") - for k, v in tf_vars.items())) + itertools.chain.from_iterable(( + '-var', + f'{k}={json.dumps(v) if isinstance(v, (dict, list, tuple, bool)) else v}', + ) for k, v in tf_vars.items())) + if targets: - cmd_args += [f"-target={t}" for t in targets] + cmd_args += [f'-target={t}' for t in targets] + if kw.get('tf_var_file'): tf_var_file = kw['tf_var_file'] if isinstance(tf_var_file, (list, tuple)): cmd_args += [f'-var-file={v}' for v in tf_var_file] else: cmd_args.append(f'-var-file={tf_var_file}') + + if kw.get('plan_out'): + cmd_args.append(f"-out={kw['plan_out']}") + return cmd_args class TerraformJSONBase(collections.abc.Mapping): - "Base class for JSON wrappers." + """Base class for JSON wrappers.""" - def __init__(self, raw): + def __init__(self, raw: Dict[str, Any]): self._raw = raw - def __bytes__(self): - return bytes(self._raw) - - def __getitem__(self, index): + def __getitem__(self, index: str) -> Any: return self._raw[index] def __iter__(self): return iter(self._raw) - def __len__(self): + def __len__(self) -> int: return len(self._raw) - def __str__(self): + def __str__(self) -> str: return str(self._raw) class TerraformValueDict(TerraformJSONBase): - "Minimal wrapper to directly expose outputs or variables." + """Minimal wrapper to directly expose outputs or variables.""" - def __init__(self, raw): - super(TerraformValueDict, self).__init__(raw) + def __init__(self, raw: Optional[Dict[str, Any]]): + raw = raw or {} + super().__init__(raw) # only matters for outputs - self.sensitive = tuple(k for k, v in raw.items() if v.get('sensitive')) + self.sensitive = tuple( + k for k, v in raw.items() if isinstance(v, dict) and v.get('sensitive')) - def __getattr__(self, name): - if isinstance(name, str) and name[:2] == name[-2:] == '__': - # skip non-existing dunder method lookups + def __getattr__(self, name: str) -> Any: + if isinstance(name, str) and name.startswith('__') and name.endswith('__'): raise AttributeError(name) return getattr(self._raw, name) - def __getitem__(self, name): + def __getitem__(self, name: str) -> Any: return self._raw[name].get('value') class TerraformPlanModule(TerraformJSONBase): - "Minimal wrapper for parsed plan output modules." + """Minimal wrapper for parsed plan output modules.""" - def __init__(self, raw): - super(TerraformPlanModule, self).__init__(raw) + def __init__(self, raw: Optional[Dict[str, Any]]): + raw = raw or {} + super().__init__(raw) prefix = raw.get('address', '') self._strip = 0 if not prefix else len(prefix) + 1 - self._modules = self._resources = None + self._modules: Optional[Dict[str, 'TerraformPlanModule']] = None + self._resources: Optional[Dict[str, Dict[str, Any]]] = None @property - def child_modules(self): + def child_modules(self) -> Dict[str, 'TerraformPlanModule']: if self._modules is None: - self._modules = dict( - (mod['address'][self._strip:], TerraformPlanModule(mod)) - for mod in self._raw.get('child_modules', {})) + self._modules = { + mod['address'][self._strip:]: TerraformPlanModule(mod) + for mod in (self._raw.get('child_modules') or []) + } return self._modules @property - def resources(self): + def resources(self) -> Dict[str, Dict[str, Any]]: if self._resources is None: - self._resources = dict((res['address'][self._strip:], res) - for res in self._raw.get('resources', [])) + self._resources = { + res['address'][self._strip:]: res + for res in (self._raw.get('resources') or []) + } return self._resources class TerraformPlanOutput(TerraformJSONBase): - "Minimal wrapper for Terraform plan JSON output." - - def __init__(self, raw): - super(TerraformPlanOutput, self).__init__(raw) - planned_values = raw.get('planned_values', {}) - self.root_module = TerraformPlanModule(planned_values.get( - 'root_module', {})) - self.outputs = TerraformValueDict(planned_values.get('outputs', {})) - self.resource_changes = dict( - (v['address'], v) for v in self._raw.get('resource_changes', {})) + """Minimal wrapper for Terraform plan JSON output.""" + + def __init__(self, raw: Optional[Dict[str, Any]]): + raw = raw or {} + super().__init__(raw) + planned_values = raw.get('planned_values') or {} + self.root_module = TerraformPlanModule( + planned_values.get('root_module') or {}) + self.outputs = TerraformValueDict(planned_values.get('outputs') or {}) + self.resource_changes = { + v['address']: v for v in (self._raw.get('resource_changes') or []) + } # there might be no variables defined - self.variables = TerraformValueDict(raw.get('variables', {})) + self.variables = TerraformValueDict(raw.get('variables') or {}) + prior_values = (raw.get('prior_state') or {}).get('values') or {} self.prior_root_module = TerraformPlanModule( - raw.get('prior_state', {}).get('values', {}).get('root_module', {})) + prior_values.get('root_module') or {}) @property - def resources(self): + def resources(self) -> Dict[str, Dict[str, Any]]: return self.root_module.resources @property - def modules(self): + def modules(self) -> Dict[str, TerraformPlanModule]: return self.root_module.child_modules @property - def prior_resources(self): + def prior_resources(self) -> Dict[str, Dict[str, Any]]: return self.prior_root_module.resources - def __getattr__(self, name): - return self._raw[name] - - def __getstate__(self): - return self.__dict__ - - def __setstate__(self, d): - self.__dict__.update(d) + def __getattr__(self, name: str) -> Any: + if isinstance(name, str) and name.startswith('__') and name.endswith('__'): + raise AttributeError(name) + try: + return self._raw[name] + except KeyError as e: + raise AttributeError(name) from e class TerraformState(TerraformJSONBase): - "Minimal wrapper for Terraform state JSON format." + """Minimal wrapper for Terraform state JSON format.""" - def __init__(self, raw): - super(TerraformState, self).__init__(raw) - self.outputs = TerraformValueDict(raw.get('outputs', {})) - self._resources = None + def __init__(self, raw: Optional[Dict[str, Any]]): + raw = raw or {} + super().__init__(raw) + self.outputs = TerraformValueDict(raw.get('outputs') or {}) + self._resources: Optional[Dict[str, Dict[str, Any]]] = None @property - def resources(self): - if not self._resources: - resources = {} - for res in self._raw['resources']: - name = f"{res.get('module')}.{res.get('type')}.{res.get('name')}" + def resources(self) -> Dict[str, Dict[str, Any]]: + if self._resources is None: + resources: Dict[str, Dict[str, Any]] = {} + for res in (self._raw.get('resources') or []): + parts = [ + res.get('module'), + 'data' if res.get('mode') == 'data' else None, + res.get('type'), + res.get('name'), + ] + name = '.'.join(p for p in parts if p) resources[name] = res self._resources = resources return self._resources - def __getattr__(self, name): - return self._raw[name] - - def __getstate__(self): - return self.__dict__ - - def __setstate__(self, d): - self.__dict__.update(d) + def __getattr__(self, name: str) -> Any: + if isinstance(name, str) and name.startswith('__') and name.endswith('__'): + raise AttributeError(name) + try: + return self._raw[name] + except KeyError as e: + raise AttributeError(name) from e -class TerraformTest(object): - """Helper class for use in testing Terraform modules. +class TerraformTest: + """Helper class for use in testing Terraform and OpenTofu modules. This helper class can be used to set up fixtures in Terraform tests, so that - the usual Terraform commands (init, plan, apply, output, destroy) can be run - on a module. Configuration is done at instantiation first, by passing in the - Terraform root module path, and then in the setup method through files that - will be temporarily linked in the module, and Terraform variables. - - The standard way of using this is by calling setup to configure the module - through temporarily linked Terraform files and variables, run one or more - Terraform commands, then check command output, state, or created resources - from individual tests. - - The local .terraform directory (including local state) and any linked file - are removed when the instance is garbage collected. Destroy needs to be - called explicitly using destroy(). + the usual commands (init, plan, apply, output, destroy) can be run on a + module. Configuration is done at instantiation first, by passing in the + Terraform root module path, and then in the setup method through files or + directories that will be temporarily linked in the module, and Terraform + variables. + + Instances can be used as a context manager (`with TerraformTest(...) as tf:`) + for deterministic cleanup, or cleaned up via `cleanup()`. If neither is used, + the local .terraform directory (including local state) and any linked files + are removed when the instance is garbage collected. Cloud resource teardown + still needs to be called explicitly using `destroy()`. Args: tfdir: the Terraform module directory to test, either an absolute path, or - relative to basedir. + relative to basedir. Stored on `self.tfdir` as an absolute `pathlib.Path`. basedir: optional base directory to use for relative paths, defaults to the - directory above the one this module lives in. - binary: path to the Terraform command. + current working directory. + binary: path or name of the Terraform/OpenTofu command. env: a dict with custom environment variables to pass to terraform. - enable_cache: Determines if the caching enabled for specific methods - cache_dir: optional base directory to use for caching, defaults to - the directory of the python file that instantiates this class """ - def __init__(self, tfdir, basedir=None, binary='terraform', env=None, - enable_cache=False, cache_dir=None): + def __init__(self, tfdir: PathType, basedir: Optional[PathType] = None, + binary: PathType = 'terraform', + env: Optional[Dict[str, str]] = None) -> None: """Set Terraform folder to operate on, and optional base directory.""" - self._basedir = basedir or os.getcwd() - self.binary = binary - self.tfdir = self._abspath(tfdir) - self._env = env or {} - self.env = {k: v for k, v in os.environ.items() if k != 'TF_LOG'} - self._plan_formatter = lambda out: TerraformPlanOutput(json.loads(out)) - self._output_formatter = lambda out: TerraformValueDict(json.loads(out)) - self.enable_cache = enable_cache - if not cache_dir: - self.cache_dir = Path( - inspect.stack()[1].filename).parent / ".tftest-cache" - else: - self.cache_dir = Path(cache_dir) + self._basedir: Path = (Path(basedir).resolve() + if basedir is not None else Path.cwd()) + self.binary: PathType = binary + self.tfdir: Path = self._abspath(tfdir) + self.env: Dict[str, str] = { + k: v for k, v in os.environ.items() if k != 'TF_LOG' + } if env is not None: self.env.update(env) + self._plan_formatter = lambda out: TerraformPlanOutput(json.loads(out)) + self._output_formatter = lambda out: TerraformValueDict(json.loads(out)) + self._finalizer: Optional[weakref.finalize] = None + self._linked_files: List[str] = [] + self._remove_lockfile: Optional[bool] = None + self._restore_files: bool = False - @classmethod - def _cleanup(cls, tfdir, filenames, deep=True, restore_files=False): - """Remove linked files and .terraform folder at instance deletion.""" + def __enter__(self) -> 'TerraformTest': + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.cleanup() - def remove_readonly(func, path, excinfo): - _LOGGER.warning(f'Issue deleting file {path}, caused by {excinfo}') - os.chmod(path, stat.S_IWRITE) - func(path) + def cleanup(self) -> None: + """Run registered cleanup immediately if present.""" + if self._finalizer is not None and self._finalizer.alive: + self._finalizer() + self._linked_files.clear() + self._remove_lockfile = None + self._restore_files = False + @classmethod + def _cleanup(cls, tfdir: Path, filenames: Sequence[str], deep: bool = True, + restore_files: bool = False, + remove_lockfile: bool = True) -> None: + """Remove linked files and Terraform runtime artifacts.""" _LOGGER.debug('cleaning up %s %s', tfdir, filenames) tf_path = Path(tfdir) for filename in filenames: - (tf_path / filename).unlink(missing_ok=True) + target = tf_path / filename + if target.is_symlink() or target.is_file(): + target.unlink(missing_ok=True) + elif target.is_dir(): + _rmtree(target) if not deep: return terraform_dir = tf_path / '.terraform' if terraform_dir.is_dir(): - shutil.rmtree(terraform_dir, onerror=remove_readonly) + _rmtree(terraform_dir) - lock_file = tf_path / '.terraform.lock.hcl' - if lock_file.is_file(): - lock_file.unlink() + if remove_lockfile: + lock_file = tf_path / '.terraform.lock.hcl' + if lock_file.is_file(): + lock_file.unlink() state_file = tf_path / 'terraform.tfstate' if state_file.is_file(): state_file.unlink() + state_dir = tf_path / 'terraform.tfstate.d' + if state_dir.is_dir(): + _rmtree(state_dir) + for backup_path in tf_path.glob('terraform.tfstate.backup*'): if backup_path.is_file(): backup_path.unlink() - _LOGGER.debug('Restoring original TF files after prevent destroy changes') - if restore_files: + if restore_files and tf_path.is_dir(): + _LOGGER.debug('Restoring original TF files after prevent destroy changes') for bkp_file in tf_path.rglob('*.bkp'): + if '.terraform' in bkp_file.parts: + continue try: - shutil.copy(str(bkp_file), f'{str(bkp_file).strip(".bkp")}') - except (IOError, OSError): + shutil.copy(str(bkp_file), str(bkp_file.with_suffix(''))) + except OSError as e: _LOGGER.exception( f'Unable to restore terraform file {bkp_file.resolve()}') raise TerraformTestError( - f'Restore of terraform file ({bkp_file.resolve()}) failed') + f'Restore of terraform file ({bkp_file.resolve()}) failed') from e else: bkp_file.unlink(missing_ok=True) - def _abspath(self, path): + def _abspath(self, path: PathType) -> Path: """Make relative path absolute from base dir.""" path_obj = Path(path) if path_obj.is_absolute(): - return path - return str(Path(self._basedir) / path) - - def _dirhash(self, directory, hash, ignore_hidden=False, - exclude_directories=[], excluded_extensions=[]): - """Returns hash of directory's file contents""" - assert Path(directory).is_dir() - try: - dir_iter = sorted(Path(directory).iterdir(), key=lambda p: str(p).lower()) - except FileNotFoundError: - return hash - for path in dir_iter: - if path.is_file(): - if ignore_hidden and path.name.startswith("."): - continue - if path.suffix in excluded_extensions: - continue - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(4096), b""): - hash.update(chunk) - elif path.is_dir() and path.name not in exclude_directories: - hash = self._dirhash(path, hash, ignore_hidden=ignore_hidden, - exclude_directories=exclude_directories, - excluded_extensions=excluded_extensions) - return hash - - def generate_cache_hash(self, method_kwargs): - """Returns a hash value using the instance's attributes and method keyword arguments""" - params = { - **{ - k: v for k, v in self.__dict__.items() - # only uses instance attributes that are involved in the results of - # the decorated method - if k in ["binary", "_basedir", "tfdir", "_env"] - }, - **method_kwargs, - } - - # creates hash of file contents - for path_param in ["extra_files", "tf_var_file"]: - if path_param in method_kwargs: - if isinstance(method_kwargs[path_param], list): - params[path_param] = [ - sha1(open(fp, 'rb').read()).hexdigest() - for fp in method_kwargs[path_param] - ] - else: - params[path_param] = sha1( - open(method_kwargs[path_param], 'rb').read()).hexdigest() - - # creates hash of all file content within tfdir - # excludes .terraform/, hidden files, tfstate files from being used for hash - params["tfdir"] = self._dirhash(self.tfdir, sha1(), ignore_hidden=True, - exclude_directories=[".terraform"], - excluded_extensions=['.backup', '.tfstate' - ]).hexdigest() - - return sha1( - json.dumps(params, sort_keys=True, - default=str).encode("cp037")).hexdigest() + ".pickle" - - def _cache(func): - sig = inspect.signature(func) - - def cache(self, *args, **kwargs): - """ - Runs the tftest instance method or retreives the cache value if it exists - - Args: - kwargs: Keyword argument that are passed to the decorated method - Returns: - Output of the tftest instance method - """ - _LOGGER.info("Cache decorated method: %s", func.__name__) - - if not self.enable_cache: - return func(self, *args, **kwargs) - - method_args = sig.bind(self, *args, **kwargs).arguments - method_args.pop('self', None) - - if not method_args.get("use_cache", False): - return func(self, *args, **kwargs) - - cache_dir = self.cache_dir / \ - Path(sha1(str(self.tfdir).encode("cp037")).hexdigest()) / \ - Path(func.__name__) - cache_dir.mkdir(parents=True, exist_ok=True) - - hash_filename = self.generate_cache_hash(method_args) - cache_key = cache_dir / hash_filename - _LOGGER.debug("Cache key: %s", cache_key) - - try: - f = cache_key.open("rb") - except OSError: - _LOGGER.debug("Could not read cache path") - else: - _LOGGER.info("Getting output from cache") - return pickle.load(f) - - _LOGGER.info("Running command") - out = func(self, *args, **kwargs) - - if out: - # the hash value will now include any changes - # to the tfdir directory - hash_filename = self.generate_cache_hash(method_args) - cache_key = cache_dir / hash_filename - _LOGGER.debug("Cache key: %s", cache_key) - - _LOGGER.info("Writing command to cache") - try: - f = cache_key.open("wb") - except OSError as e: - _LOGGER.error("Cache could not write path") - else: - with f: - pickle.dump(out, f, pickle.HIGHEST_PROTOCOL) - - return out + return path_obj + return self._basedir / path_obj - return cache - - @_cache - def setup(self, extra_files: Optional[List[str]] = None, - plugin_dir: Optional[str] = None, + def setup(self, extra_files: Optional[Sequence[PathType]] = None, + plugin_dir: Optional[PathType] = None, init_vars: Optional[Union[Dict[str, Any], - str]] = None, backend: bool = True, + PathType]] = None, backend: bool = True, cleanup_on_exit: bool = True, disable_prevent_destroy: bool = False, - workspace_name: Optional[str] = None, use_cache: bool = False, - **kw: Any) -> str: + workspace_name: Optional[str] = None, **kw: Any) -> str: """Setup method to use in test fixtures. This method prepares a new Terraform environment for testing the module specified at init time, and returns init output. Args: - extra_files: list of absolute or relative to base paths to be linked in - the root module folder + extra_files: list of absolute or relative to base file or directory paths + to be linked in the root module folder. plugin_dir: path to a plugin directory to be used for Terraform init, eg - built with terraform-bundle - init_vars: Terraform backend configuration variables - backend: Terraform backend argument - cleanup_on_exit: remove .terraform and terraform.tfstate files on exit - disable_prevent_destroy: set all prevent destroy to false - workspace_name: name of workspace to create or select + built with terraform-bundle. + init_vars: Terraform backend configuration variables. + backend: Terraform backend argument. + cleanup_on_exit: remove .terraform and terraform.tfstate files on exit. + disable_prevent_destroy: set all prevent_destroy to false. + workspace_name: name of workspace to create or select. Returns: Terraform init output. """ - # remove lifecycle prevent destroy + if self._remove_lockfile is None: + self._remove_lockfile = not (self.tfdir / '.terraform.lock.hcl').is_file() + if disable_prevent_destroy: - min_python = (3, 5) - if sys.version_info < min_python: - raise TerraformTestError( - 'The disable_prevent_destroy flag requires at least Python 3.5') - for tf_file in Path(self.tfdir).rglob('*.tf'): - try: - shutil.copy(str(tf_file), f'{str(tf_file)}.bkp') - # except (OSError, IOError) as exc: - except (OSError, IOError): - _LOGGER.exception( - f'Unable to backup terraform file {tf_file.resolve()}') - raise TerraformTestError( - f'Backup of terraform file ({tf_file.resolve()}) failed') - try: - with open(tf_file, 'r') as src: - terraform = src.read() - with open(tf_file, 'w') as src: - terraform = re.sub(r'prevent_destroy\s+=\s+true', - 'prevent_destroy = false', terraform) - src.write(terraform) - except (OSError, IOError): - _LOGGER.exception( - f'Unable to update prevent_destroy in file {tf_file.resolve()}') - raise TerraformTestError( - f'Unable to update prevent_destroy in file ({tf_file.resolve()}) failed' - ) + self._restore_files = True + if self.tfdir.is_dir(): + for tf_file in self.tfdir.rglob('*.tf'): + if '.terraform' in tf_file.parts: + continue + bkp_file = Path(f'{tf_file}.bkp') + if not bkp_file.exists(): + try: + shutil.copy(str(tf_file), str(bkp_file)) + except OSError as e: + _LOGGER.exception( + f'Unable to backup terraform file {tf_file.resolve()}') + raise TerraformTestError( + f'Backup of terraform file ({tf_file.resolve()}) failed' + ) from e + try: + with open(tf_file, 'r', encoding='utf-8') as src: + terraform = src.read() + with open(tf_file, 'w', encoding='utf-8') as src: + terraform = re.sub(r'prevent_destroy\s*=\s*true', + 'prevent_destroy = false', terraform) + src.write(terraform) + except OSError as e: + _LOGGER.exception( + f'Unable to update prevent_destroy in file {tf_file.resolve()}') + raise TerraformTestError( + f'Unable to update prevent_destroy in file ({tf_file.resolve()}) failed' + ) from e - # link extra files inside dir - filenames = [] for link_src in (extra_files or []): - link_src_path = Path(self._abspath(link_src)) + link_src_path = self._abspath(link_src) filename = link_src_path.name - if link_src_path.is_file(): - link_dst = Path(self.tfdir) / filename + if link_src_path.exists(): + link_dst = self.tfdir / filename try: if os.name == 'nt': - shutil.copy(link_src_path, link_dst) + if link_src_path.is_dir(): + shutil.copytree(link_src_path, link_dst) + else: + shutil.copy(link_src_path, link_dst) else: os.symlink(link_src_path, link_dst) - filenames.append(filename) - except FileExistsError as e: # pylint:disable=undefined-variable + if filename not in self._linked_files: + self._linked_files.append(filename) + except FileExistsError as e: _LOGGER.warning(e) else: _LOGGER.debug('linked %s', link_src_path) else: - _LOGGER.warning(f'no such file {link_src_path}') + _LOGGER.warning('no such file or directory %s', link_src_path) + + if self._finalizer is not None and self._finalizer.alive: + self._finalizer.detach() self._finalizer = weakref.finalize(self, self._cleanup, self.tfdir, - filenames, deep=cleanup_on_exit, - restore_files=disable_prevent_destroy) + list(self._linked_files), + deep=cleanup_on_exit, + restore_files=self._restore_files, + remove_lockfile=self._remove_lockfile) setup_output = self.init(plugin_dir=plugin_dir, init_vars=init_vars, - backend=backend, use_cache=use_cache, **kw) + backend=backend, **kw) if workspace_name: setup_output += self.workspace(name=workspace_name) return setup_output - @_cache def init(self, input: bool = False, color: bool = False, - force_copy: bool = False, plugin_dir: Optional[str] = None, - init_vars: Optional[Union[Dict[str, Any], str]] = None, - backend: bool = True, use_cache: bool = False, **kw: Any) -> str: + force_copy: bool = False, plugin_dir: Optional[PathType] = None, + init_vars: Optional[Union[Dict[str, Any], PathType]] = None, + backend: bool = True, **kw: Any) -> str: """Run Terraform init command.""" cmd_args = parse_args(input=input, color=color, backend=backend, force_copy=force_copy, plugin_dir=plugin_dir, @@ -570,7 +508,7 @@ def init(self, input: bool = False, color: bool = False, def workspace(self, name: str) -> str: """Run Terraform workspace command.""" - raw_ws_out = self.execute_command('workspace', *['list']).out + raw_ws_out = self.execute_command('workspace', 'list').out cmd_args = ['select', name] if name not in [ ws.replace('*', '').strip() @@ -580,70 +518,82 @@ def workspace(self, name: str) -> str: cmd_args = ['new', name] return self.execute_command('workspace', *cmd_args).out - @_cache def plan(self, input: bool = False, color: bool = False, refresh: bool = True, tf_vars: Optional[Dict[str, Any]] = None, - targets: Optional[List[str]] = None, output: bool = False, - tf_var_file: Optional[Union[str, List[str]]] = None, - state: Optional[str] = None, use_cache: bool = False, + targets: Optional[Sequence[str]] = None, output: bool = False, + tf_var_file: Optional[Union[PathType, Sequence[PathType]]] = None, + state: Optional[PathType] = None, + plan_out: Optional[PathType] = None, **kw: Any) -> Union[str, TerraformPlanOutput]: - """ - Run Terraform plan command, optionally returning parsed plan output. + """Run Terraform plan command, optionally returning parsed plan output. Args: input: Ask for input for variables if not directly set. - no_color: If specified, output won't contain any color. + color: Include color escape sequences in output. refresh: Update state prior to checking for differences. tf_vars: Dict of variables in the Terraform configuration. - targets: List of resources to target. Operation will be limited to this resource - and its dependencies - output: Determines if output will be returned. - tf_var_file: Path to terraform variable configuration file relative to `self.tfdir`. + targets: List of resources to target. Operation will be limited to this + resource and its dependencies. + output: Determines if parsed `TerraformPlanOutput` will be returned. + tf_var_file: Path (or sequence of paths) to terraform variable + configuration files relative to `self.tfdir` or absolute. state: Path to state file to use when reading the prior state snapshot. + plan_out: Optional path where the generated binary plan file should be + saved (`-out`). When provided, the plan file is kept on disk; when + omitted and `output=True`, a temporary plan file is used and unlinked. """ cmd_args = parse_args(input=input, color=color, refresh=refresh, tf_vars=tf_vars, targets=targets, - tf_var_file=tf_var_file, state=state, **kw) + tf_var_file=tf_var_file, state=state, + plan_out=plan_out, **kw) if not output: return self.execute_command('plan', *cmd_args).out - with tempfile.NamedTemporaryFile() as fp: - fp.close() - temp_file = fp.name - cmd_args.append(f'-out={temp_file}') - self.execute_command('plan', *cmd_args) - result = self.execute_command('show', '-no-color', '-json', temp_file) + if plan_out is not None: + self.execute_command('plan', *cmd_args) + result = self.execute_command('show', '-no-color', '-json', str(plan_out)) + else: + with tempfile.NamedTemporaryFile() as fp: + temp_file = fp.name + cmd_args.append(f'-out={temp_file}') + try: + self.execute_command('plan', *cmd_args) + result = self.execute_command('show', '-no-color', '-json', temp_file) + finally: + Path(temp_file).unlink(missing_ok=True) try: return self._plan_formatter(result.out) except json.JSONDecodeError as e: - raise TerraformTestError(f'Error decoding plan output: {e}') + raise TerraformTestError(f'Error decoding plan output: {e}') from e - @_cache def apply(self, input: bool = False, color: bool = False, auto_approve: bool = True, tf_vars: Optional[Dict[str, Any]] = None, - targets: Optional[List[str]] = None, - tf_var_file: Optional[Union[str, List[str]]] = None, - use_cache: bool = False, **kw: Any) -> str: - """ - Run Terraform apply command. + targets: Optional[Sequence[str]] = None, + tf_var_file: Optional[Union[PathType, Sequence[PathType]]] = None, + plan_file: Optional[PathType] = None, **kw: Any) -> str: + """Run Terraform apply command. Args: input: Ask for input for variables if not directly set. - no_color: If specified, output won't contain any color. + color: Include color escape sequences in output. auto_approve: Skip interactive approval of plan before applying. tf_vars: Dict of variables in the Terraform configuration. - targets: List of resources to target. Operation will be limited to this resource - and its dependencies - tf_var_file: Path to terraform variable configuration file relative to `self.tfdir`. + targets: List of resources to target. Operation will be limited to this + resource and its dependencies. + tf_var_file: Path (or sequence of paths) to terraform variable + configuration files relative to `self.tfdir` or absolute. + plan_file: Optional saved binary plan file (created with `plan_out`) to + apply directly. """ cmd_args = parse_args(input=input, color=color, auto_approve=auto_approve, tf_vars=tf_vars, targets=targets, tf_var_file=tf_var_file, **kw) + if plan_file is not None: + cmd_args.append(str(plan_file)) return self.execute_command('apply', *cmd_args).out - @_cache def output(self, name: Optional[str] = None, color: bool = False, - json_format: bool = True, use_cache: bool = False, - **kw: Any) -> Union[str, dict]: + json_format: bool = True, + **kw: Any) -> Union[str, TerraformValueDict]: """Run Terraform output command.""" cmd_args = [] if name: @@ -655,24 +605,24 @@ def output(self, name: Optional[str] = None, color: bool = False, try: output = self._output_formatter(output) except json.JSONDecodeError as e: - _LOGGER.warning(f'error decoding output: {e}') + _LOGGER.warning('error decoding output: %s', e) return output - @_cache - def destroy(self, color: bool = False, auto_approve: bool = True, - tf_vars: Optional[Dict[str, Any]] = None, - targets: Optional[List[str]] = None, - tf_var_file: Optional[Union[str, List[str]]] = None, - use_cache: bool = False, **kw: Any) -> str: + def destroy(self, input: bool = False, color: bool = False, + auto_approve: bool = True, tf_vars: Optional[Dict[str, + Any]] = None, + targets: Optional[Sequence[str]] = None, + tf_var_file: Optional[Union[PathType, Sequence[PathType]]] = None, + **kw: Any) -> str: """Run Terraform destroy command.""" - cmd_args = parse_args(color=color, auto_approve=auto_approve, + cmd_args = parse_args(input=input, color=color, auto_approve=auto_approve, tf_vars=tf_vars, targets=targets, tf_var_file=tf_var_file, **kw) return self.execute_command('destroy', *cmd_args).out def refresh(self, color: bool = False, lock: bool = False, tf_vars: Optional[Dict[str, Any]] = None, - targets: Optional[List[str]] = None, **kw: Any) -> str: + targets: Optional[Sequence[str]] = None, **kw: Any) -> str: """Run Terraform refresh command.""" cmd_args = parse_args(color=color, lock=lock, tf_vars=tf_vars, targets=targets, **kw) @@ -682,39 +632,53 @@ def state_pull(self) -> Union[str, TerraformState]: """Pull state.""" state = self.execute_command('state', 'pull') try: - state = TerraformState(json.loads(state.out)) + return TerraformState(json.loads(state.out)) except json.JSONDecodeError as e: - _LOGGER.warning(f'error decoding state: {e}') - return state + _LOGGER.warning('error decoding state: %s', e) + return state.out - def execute_command(self, cmd: str, *cmd_args: str) -> TerraformCommandOutput: + def execute_command(self, cmd: str, *cmd_args: Any) -> TerraformCommandOutput: """Run arbitrary Terraform command.""" _LOGGER.debug([cmd, cmd_args]) - cmdline = [self.binary, cmd] - cmdline += cmd_args + cmdline = [str(self.binary), cmd, *(str(a) for a in cmd_args)] _LOGGER.info(cmdline) - retcode = None - full_output_lines = [] + full_output_lines: List[str] = [] + err_chunks: List[str] = [] try: - stderr_mode = subprocess.STDOUT if os.name == 'nt' else subprocess.PIPE - p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=stderr_mode, - cwd=self.tfdir, env=self.env, + p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, cwd=self.tfdir, env=self.env, universal_newlines=True, encoding='utf-8', errors='ignore') - while True: - output = p.stdout.readline() - if output == '' and p.poll() is not None: - break - if output: - _LOGGER.info(output.strip()) - full_output_lines.append(output) - retcode = p.poll() - p.wait() except FileNotFoundError as e: - raise TerraformTestError(f'Terraform executable not found: {e}') - _, err = p.communicate() - full_output = "".join(full_output_lines) - if retcode in [1, 11]: + if not self.tfdir.is_dir(): + raise TerraformTestError( + f'Terraform directory not found: {self.tfdir}') from e + raise TerraformTestError(f'Terraform executable not found: {e}') from e + + def _drain_stderr(pipe: Any) -> None: + try: + for line in pipe: + err_chunks.append(line) + finally: + pipe.close() + + stderr_thread = threading.Thread(target=_drain_stderr, args=(p.stderr,), + daemon=True) + stderr_thread.start() + assert p.stdout is not None + try: + for output in p.stdout: + _LOGGER.info(output.strip()) + full_output_lines.append(output) + finally: + p.stdout.close() + retcode = p.wait() + stderr_thread.join() + full_output = ''.join(full_output_lines) + err = ''.join(err_chunks) + allowed_codes = (0, 2) if (cmd == 'plan' and + '-detailed-exitcode' in cmdline[2:]) else (0,) + if retcode not in allowed_codes: message = f'Error running command {cmd}: {retcode} {full_output} {err}' _LOGGER.critical(message) raise TerraformTestError(message, err) diff --git a/tools/REQUIREMENTS.txt b/tools/REQUIREMENTS.txt index e414ba1..6fd2ba4 100644 --- a/tools/REQUIREMENTS.txt +++ b/tools/REQUIREMENTS.txt @@ -1,3 +1,4 @@ click -ghapi iso8601 +marko +requests