From 10b4357e5193b0aa05a08137577ae92476c0bb23 Mon Sep 17 00:00:00 2001 From: Sriram Madapusi Vasudevan <3770774+TheSriram@users.noreply.github.com> Date: Wed, 20 Nov 2019 12:30:21 -0800 Subject: [PATCH] fix: only create config file on write (#1559) --- samcli/lib/config/samconfig.py | 12 +++++++----- tests/unit/lib/config/test_samconfig.py | 6 +++++- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/samcli/lib/config/samconfig.py b/samcli/lib/config/samconfig.py index 4ca390c9e7..f2fb8d7dce 100644 --- a/samcli/lib/config/samconfig.py +++ b/samcli/lib/config/samconfig.py @@ -36,8 +36,6 @@ def __init__(self, config_dir, filename=None): could automatically support auto-resolving multiple config files within same directory. """ self.filepath = Path(config_dir, filename or DEFAULT_CONFIG_FILE_NAME) - if not self.filepath.exists(): - open(self.filepath, "a+").close() def get_all(self, cmd_names, section, env=DEFAULT_ENV): """ @@ -153,15 +151,19 @@ def _read(self): if self.document: return self.document - txt = self.filepath.read_text() - self.document = tomlkit.loads(txt) + try: + txt = self.filepath.read_text() + self.document = tomlkit.loads(txt) + except OSError: + self.document = tomlkit.document() return self.document def _write(self): if not self.document: return - + if not self.exists(): + open(self.filepath, "a+").close() self.filepath.write_text(tomlkit.dumps(self.document)) @staticmethod diff --git a/tests/unit/lib/config/test_samconfig.py b/tests/unit/lib/config/test_samconfig.py index c39e8f494d..54575c1198 100644 --- a/tests/unit/lib/config/test_samconfig.py +++ b/tests/unit/lib/config/test_samconfig.py @@ -10,7 +10,6 @@ class TestSamConfig(TestCase): def setUp(self): self.config_dir = os.getcwd() self.samconfig = SamConfig(self.config_dir) - open(self.samconfig.path(), "w").close() def tearDown(self): if self.samconfig.exists(): @@ -19,6 +18,8 @@ def tearDown(self): def _setup_config(self): self.samconfig.put(cmd_names=["local", "start", "api"], section="parameters", key="port", value=5401) self.samconfig.flush() + self.assertTrue(self.samconfig.exists()) + self.assertTrue(self.samconfig.sanity_check()) def test_init(self): self.assertEqual(self.samconfig.filepath, Path(self.config_dir, DEFAULT_CONFIG_FILE_NAME)) @@ -32,3 +33,6 @@ def test_check_config_get(self): def test_check_config_exists(self): self._setup_config() self.assertTrue(self.samconfig.exists()) + + def test_check_sanity(self): + self.assertTrue(self.samconfig.sanity_check())