From 7192f3ea94ddb53b8388afa1717e586bcf752b6a Mon Sep 17 00:00:00 2001 From: Emil Styrke Date: Sat, 24 Oct 2020 14:16:47 +0200 Subject: [PATCH] Generate snapshot declarations before opening output file If there is an error while generating the declarations, the output file will be truncated. This will cause existing snapshots to disappear, as well as make further runs fail because of an invalid snapshot file. --- snapshottest/module.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/snapshottest/module.py b/snapshottest/module.py index e31b46c..55c6abf 100644 --- a/snapshottest/module.py +++ b/snapshottest/module.py @@ -150,20 +150,20 @@ def save(self): pretty = Formatter(self.imports) - with codecs.open(self.filepath, "w", encoding="utf-8") as snapshot_file: - snapshots_declarations = [ - """snapshots['{}'] = {}""".format(key, pretty(self.snapshots[key])) - for key in sorted(self.snapshots.keys()) + snapshots_declarations = [ + """snapshots['{}'] = {}""".format(key, pretty(self.snapshots[key])) + for key in sorted(self.snapshots.keys()) + ] + + imports = "\n".join( + [ + "from {} import {}".format( + module, ", ".join(sorted(module_imports)) + ) + for module, module_imports in sorted(self.imports.items()) ] - - imports = "\n".join( - [ - "from {} import {}".format( - module, ", ".join(sorted(module_imports)) - ) - for module, module_imports in sorted(self.imports.items()) - ] - ) + ) + with codecs.open(self.filepath, "w", encoding="utf-8") as snapshot_file: snapshot_file.write( """# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc