Skip to content

Commit

Permalink
quilt3: simplify write_yaml() a bit (#3877)
Browse files Browse the repository at this point in the history
  • Loading branch information
sir-sigurd authored Feb 13, 2024
1 parent 8c37e88 commit 8f66afb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
7 changes: 2 additions & 5 deletions api/python/quilt3/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,15 +298,12 @@ def write_yaml(data, yaml_path, keep_backup=False):
try:
if path.exists():
path.rename(backup_path)
if not path.parent.exists():
path.parent.mkdir(parents=True)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('w') as config_file:
yaml.dump(data, config_file)
except Exception: # intentionally wide catch -- reraised immediately.
if backup_path.exists():
if path.exists():
path.unlink()
backup_path.rename(path)
backup_path.replace(path)
raise

if backup_path.exists() and not keep_backup:
Expand Down
15 changes: 15 additions & 0 deletions api/python/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ def test_write_yaml(tmpdir):
assert fname.read_text('utf-8') == 'testing: bar\n'


@pytest.mark.parametrize("keep_backup", [False, True])
def test_write_yaml_exception(tmp_path, keep_backup):
fname = tmp_path / "some_file.yml"
fname.write_text("42")

exc = Exception("test exception")
with mock.patch("quilt3.util.yaml.dump", side_effect=exc):
with pytest.raises(Exception) as exc_info:
util.write_yaml("test", fname)

assert exc_info.value == exc
assert fname.read_text("utf-8") == "42"
assert list(tmp_path.iterdir()) == [fname]


def test_read_yaml(tmpdir):
# Read a string
parsed_string = util.read_yaml(TEST_YAML)
Expand Down

0 comments on commit 8f66afb

Please sign in to comment.