Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Figure.savefig: Raise a FileNotFoundError if the parent directory doesn't exist #2160

Merged
merged 4 commits into from
Oct 29, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 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 @@ -241,6 +242,12 @@ def psconvert(self, icc_gray=False, **kwargs):
else:
kwargs["N"] += "+i"

# check if the parent directory exists
if kwargs.get("F") and not Path(kwargs.get("F")).parent.exists():
raise FileNotFoundError(
f"No such directory: '{Path(kwargs.get('F')).parent}'"
seisman marked this conversation as resolved.
Show resolved Hide resolved
)

# Manually handle prefix -F argument so spaces aren't converted to \040
# by build_arg_string function. For more information, see
# https://github.com/GenericMappingTools/pygmt/pull/1487
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