Skip to content

Commit

Permalink
tag v1.8.3
Browse files Browse the repository at this point in the history
  • Loading branch information
ludoo committed Apr 16, 2023
1 parent 99e231c commit 9651a05
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 24 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

<!-- None < 2023-01-26 11:16:58+00:00 -->

## [1.8.3] - 2023-04-16

- [[#70](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/pull/70)] Parse state flag ([andrewesweet](https://github.com/andrewesweet))

## [1.8.2] - 2023-01-26
<!-- 2023-01-26 11:16:58+00:00 < 2022-12-01 06:54:32+00:00 -->

- [[#69](https://github.com/GoogleCloudPlatform/terraform-python-testing-helper/pull/69)] [feature] added support to pass a complex dict ([MrImpossibru](https://github.com/MrImpossibru)) <!-- 2023-01-26 10:26:38+00:00 -->

Expand Down
51 changes: 27 additions & 24 deletions tftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
from pathlib import Path
from typing import List

__version__ = '1.8.2'
__version__ = '1.8.3'

_LOGGER = logging.getLogger('tftest')

Expand Down Expand Up @@ -107,8 +107,7 @@ def parse_args(init_vars=None, tf_vars=None, targets=None, **kw):
]
for arg in _TG_KV_ARGS:
if kw.get(f"tg_{arg}"):
cmd_args += [f'--terragrunt-{arg.replace("_", "-")}',
kw[f"tg_{arg}"]]
cmd_args += [f'--terragrunt-{arg.replace("_", "-")}', kw[f"tg_{arg}"]]
if kw.get('tg_parallelism'):
cmd_args.append(f'--terragrunt-parallelism {kw["tg_parallelism"]}')
if isinstance(kw.get('tg_override_attr'), dict):
Expand Down Expand Up @@ -149,9 +148,10 @@ def parse_args(init_vars=None, tf_vars=None, targets=None, **kw):
cmd_args += list(
itertools.chain.from_iterable(
("-var",
"{}={}".format(k, json.dumps(v) if isinstance(v, (dict, list)) else v))
for k, v in tf_vars.items()
))
"{}={}".format(k,
json.dumps(v) if isinstance(v, (dict,
list)) else v))
for k, v in tf_vars.items()))
if targets:
cmd_args += [("-target={}".format(t)) for t in targets]
if kw.get('tf_var_file'):
Expand Down Expand Up @@ -329,8 +329,7 @@ def __init__(self, tfdir, basedir=None, binary='terraform', env=None,
self.env = os.environ.copy()
self.tg_run_all = False
self._plan_formatter = lambda out: TerraformPlanOutput(json.loads(out))
self._output_formatter = lambda out: TerraformValueDict(
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(os.path.dirname(
Expand Down Expand Up @@ -365,13 +364,11 @@ def remove_readonly(func, path, excinfo):
for tg_dir in glob.glob(path, recursive=True):
if os.path.isdir(tg_dir):
shutil.rmtree(tg_dir, onerror=remove_readonly)
_LOGGER.debug(
'Restoring original TF files after prevent destroy changes')
_LOGGER.debug('Restoring original TF files after prevent destroy changes')
if restore_files:
for bkp_file in Path(tfdir).rglob('*.bkp'):
try:
shutil.copy(str(bkp_file),
f'{str(bkp_file).strip(".bkp")}')
shutil.copy(str(bkp_file), f'{str(bkp_file).strip(".bkp")}')
except (IOError, OSError):
_LOGGER.exception(
f'Unable to restore terraform file {bkp_file.resolve()}')
Expand All @@ -384,12 +381,12 @@ def _abspath(self, path):
"""Make relative path absolute from base dir."""
return path if os.path.isabs(path) else os.path.join(self._basedir, path)

def _dirhash(self, directory, hash, ignore_hidden=False, exclude_directories=[], excluded_extensions=[]):
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())
dir_iter = sorted(Path(directory).iterdir(), key=lambda p: str(p).lower())
except FileNotFoundError:
return hash
for path in dir_iter:
Expand All @@ -403,7 +400,8 @@ def _dirhash(self, directory, hash, ignore_hidden=False, exclude_directories=[],
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)
exclude_directories=exclude_directories,
excluded_extensions=excluded_extensions)
return hash

def generate_cache_hash(self, method_kwargs):
Expand All @@ -423,18 +421,23 @@ def generate_cache_hash(self, method_kwargs):
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]]
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()
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"
return sha1(
json.dumps(params, sort_keys=True,
default=str).encode("cp037")).hexdigest() + ".pickle"

def _cache(func):

Expand Down Expand Up @@ -597,7 +600,8 @@ def workspace(self, name=None):

@_cache
def plan(self, input=False, color=False, refresh=True, tf_vars=None,
targets=None, output=False, tf_var_file=None, state=None, use_cache=False, **kw):
targets=None, output=False, tf_var_file=None, state=None,
use_cache=False, **kw):
"""
Run Terraform plan command, optionally returning parsed plan output.
Expand Down Expand Up @@ -629,8 +633,7 @@ def plan(self, input=False, color=False, refresh=True, tf_vars=None,
try:
return self._plan_formatter(result.out)
except json.JSONDecodeError as e:
raise TerraformTestError(
'Error decoding plan output: {}'.format(e))
raise TerraformTestError('Error decoding plan output: {}'.format(e))

@_cache
def apply(self, input=False, color=False, auto_approve=True, tf_vars=None,
Expand Down

0 comments on commit 9651a05

Please sign in to comment.