def test_hash_file(self): with TemporaryDirectory() as temp_dir: path = Path(temp_dir) / 'temp.txt' path.write_text('abcdef') expected = 'bef57ec7f53a6d40beb640a780a639c83bc29ac8a9816f1fc6c5c6dcd93c4721' actual = utils.hash_file(path) self.assertEqual(actual, expected)
def secure_hash(env, rel_path): """ Return a secure hash of the contents of the file, using SHA-256. Returns the hash as a hexadecimal string. Args: env: a Jinja2 Environment object. rel_path: a path relative to the output directory configured in the Jinja2 Environment object. This can be any path-like object. """ path = get_output_path(env, rel_path) sha = utils.hash_file(path) return sha
def format_output( output_dir, build_time, election_title=None, results_title=None, rel_home_page=None, zip_file_path=None, initial_data=None, ): """ Print and return the output data. """ if initial_data is None: initial_data = {} output_dir = Path(output_dir) # Rename the variable for clarity. output_data = initial_data if election_title is not None: output_data['election_title'] = election_title if results_title is not None: output_data['results_title'] = results_title if rel_home_page is not None: output_data['rel_home_page'] = rel_home_page if zip_file_path is not None: path = output_dir / zip_file_path zip_size = path.stat().st_size zip_hash = utils.hash_file(path) output_data['zip_file'] = { 'path': str(zip_file_path), 'bytes': zip_size, 'hash': str(zip_hash), } output_data.update( build_time=build_time.isoformat(), output_dir=str(output_dir), ) # TODO: allow changing the stdout output format (e.g. YAML or text)? output = json.dumps(output_data, **DEFAULT_JSON_DUMPS_ARGS) return (output_data, output)