Skip to content

Commit

Permalink
Figure.savefig: Raise a FileNotFoundError if the parent directory doe…
Browse files Browse the repository at this point in the history
…sn't exist (GenericMappingTools#2160)

Co-authored-by: Wei Ji <23487320+weiji14@users.noreply.github.com>
  • Loading branch information
2 people authored and Josh Sixsmith committed Dec 21, 2022
1 parent 16d7537 commit f779f45
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pygmt/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import base64
import os
import warnings
from pathlib import Path
from tempfile import TemporaryDirectory

try:
Expand Down Expand Up @@ -251,6 +252,13 @@ def psconvert(self, icc_gray=False, **kwargs):
)
prefix_arg = f'-F"{prefix}"'

# check if the parent directory exists
prefix_path = Path(prefix).parent
if not prefix_path.exists():
raise FileNotFoundError(
f"No such directory: '{prefix_path}', please create it first."
)

with Session() as lib:
lib.call_module(
module="psconvert", args=f"{prefix_arg} {build_arg_string(kwargs)}"
Expand Down
11 changes: 11 additions & 0 deletions pygmt/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ def test_figure_savefig_exists():
os.remove(fname)


def test_figure_savefig_directory_nonexists():
"""
Make sure that Figure.savefig() raises a FileNotFoundError when the parent
directory doesn't exist.
"""
fig = Figure()
fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af")
with pytest.raises(FileNotFoundError, match="No such directory:"):
fig.savefig("a-nonexist-directory/test_figure_savefig_directory_nonexists.png")


def test_figure_savefig_unknown_extension():
"""
Check that an error is raised when an unknown extension is passed.
Expand Down

0 comments on commit f779f45

Please sign in to comment.