From 0cdb87de8bd813deff42224cf73203db56a4e699 Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Wed, 20 Mar 2024 17:23:34 +0800 Subject: [PATCH] Migrate from os.path to pathlib (#3119) --- examples/gallery/images/image.py | 4 +-- examples/tutorials/basics/text.py | 4 +-- pygmt/figure.py | 13 ++++--- pygmt/helpers/tempfile.py | 9 +++-- pygmt/helpers/testing.py | 26 +++++++------- pygmt/src/grdfilter.py | 4 +-- pygmt/src/x2sys_cross.py | 2 +- pygmt/tests/test_accessor.py | 3 +- pygmt/tests/test_clib.py | 6 ++-- pygmt/tests/test_clib_virtualfiles.py | 5 ++- pygmt/tests/test_contour.py | 5 ++- pygmt/tests/test_figure.py | 16 ++++----- pygmt/tests/test_grd2cpt.py | 4 +-- pygmt/tests/test_grdcontour.py | 5 ++- pygmt/tests/test_grdtrack.py | 4 +-- pygmt/tests/test_helpers.py | 26 ++++++++------ pygmt/tests/test_info.py | 12 +++---- pygmt/tests/test_makecpt.py | 4 +-- pygmt/tests/test_plot.py | 4 +-- pygmt/tests/test_plot3d.py | 4 +-- pygmt/tests/test_psconvert.py | 20 +++++------ pygmt/tests/test_session_management.py | 15 ++++---- pygmt/tests/test_sphinx_gallery.py | 10 +++--- pygmt/tests/test_text.py | 8 ++--- pygmt/tests/test_x2sys_cross.py | 49 +++++++++++++------------- pygmt/tests/test_x2sys_init.py | 18 +++++----- 26 files changed, 131 insertions(+), 149 deletions(-) diff --git a/examples/gallery/images/image.py b/examples/gallery/images/image.py index 52d6b197fa5..1806ae55577 100644 --- a/examples/gallery/images/image.py +++ b/examples/gallery/images/image.py @@ -11,7 +11,7 @@ """ # %% -import os +from pathlib import Path import pygmt @@ -28,6 +28,6 @@ ) # clean up the downloaded image in the current directory -os.remove("gmt-logo.png") +Path("gmt-logo.png").unlink() fig.show() diff --git a/examples/tutorials/basics/text.py b/examples/tutorials/basics/text.py index 4ad92091de1..1f225bb39c3 100644 --- a/examples/tutorials/basics/text.py +++ b/examples/tutorials/basics/text.py @@ -7,7 +7,7 @@ """ # %% -import os +from pathlib import Path import pygmt @@ -88,7 +88,7 @@ fig.text(textfiles="examples.txt", angle=True, font=True, justify=True) # Cleanups -os.remove("examples.txt") +Path("examples.txt").unlink() fig.show() diff --git a/pygmt/figure.py b/pygmt/figure.py index 98f06291c6b..f908cff1b93 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -67,10 +67,9 @@ class Figure: >>> fig.basemap(region=[0, 360, -90, 90], projection="W15c", frame=True) >>> fig.savefig("my-figure.png") >>> # Make sure the figure file is generated and clean it up - >>> import os - >>> os.path.exists("my-figure.png") - True - >>> os.remove("my-figure.png") + >>> from pathlib import Path + >>> assert Path("my-figure.png").exists() + >>> Path("my-figure.png").unlink() The plot region can be specified through ISO country codes (for example, ``"JP"`` for Japan): @@ -380,8 +379,8 @@ def savefig( # noqa: PLR0912 # Remove the .pgw world file if exists # Not necessary after GMT 6.5.0. # See upstream fix https://github.com/GenericMappingTools/gmt/pull/7865 - if ext == "tiff" and fname.with_suffix(".pgw").exists(): - fname.with_suffix(".pgw").unlink() + if ext == "tiff": + fname.with_suffix(".pgw").unlink(missing_ok=True) # Rename if file extension doesn't match the input file suffix if ext != suffix[1:]: @@ -495,7 +494,7 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs): If ``as_bytes=False``, this is the file name of the preview image file. Else, it is the file content loaded as a bytes string. """ - fname = os.path.join(self._preview_dir.name, f"{self._name}.{fmt}") + fname = Path(self._preview_dir.name) / f"{self._name}.{fmt}" self.savefig(fname, dpi=dpi, **kwargs) if as_bytes: with open(fname, "rb") as image: diff --git a/pygmt/helpers/tempfile.py b/pygmt/helpers/tempfile.py index 62a3daf5447..bed79f352ae 100644 --- a/pygmt/helpers/tempfile.py +++ b/pygmt/helpers/tempfile.py @@ -2,9 +2,9 @@ Utilities for dealing with temporary file management. """ -import os import uuid from contextlib import contextmanager +from pathlib import Path from tempfile import NamedTemporaryFile import numpy as np @@ -72,8 +72,7 @@ def __exit__(self, *args): """ Remove the temporary file. """ - if os.path.exists(self.name): - os.remove(self.name) + Path(self.name).unlink(missing_ok=True) def read(self, keep_tabs=False): """ @@ -133,7 +132,7 @@ def tempfile_from_geojson(geojson): with GMTTempFile(suffix=".gmt") as tmpfile: import geopandas as gpd - os.remove(tmpfile.name) # ensure file is deleted first + Path(tmpfile.name).unlink() # Ensure file is deleted first ogrgmt_kwargs = {"filename": tmpfile.name, "driver": "OGR_GMT", "mode": "w"} try: # OGR_GMT only supports 32-bit integers. We need to map int/int64 @@ -185,7 +184,7 @@ def tempfile_from_image(image): A temporary GeoTIFF file holding the image data. E.g. '1a2b3c4d5.tif'. """ with GMTTempFile(suffix=".tif") as tmpfile: - os.remove(tmpfile.name) # ensure file is deleted first + Path(tmpfile.name).unlink() # Ensure file is deleted first try: image.rio.to_raster(raster_path=tmpfile.name) except AttributeError as e: # object has no attribute 'rio' diff --git a/pygmt/helpers/testing.py b/pygmt/helpers/testing.py index 1a1c72cb334..28027e82f64 100644 --- a/pygmt/helpers/testing.py +++ b/pygmt/helpers/testing.py @@ -4,8 +4,8 @@ import importlib import inspect -import os import string +from pathlib import Path from pygmt.exceptions import GMTImageComparisonFailure from pygmt.io import load_dataarray @@ -39,6 +39,7 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag >>> import pytest >>> import shutil >>> from pygmt import Figure + >>> from pathlib import Path >>> @check_figures_equal(result_dir="tmp_result_images") ... def test_check_figures_equal(): @@ -50,7 +51,7 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag ... ) ... return fig_ref, fig_test >>> test_check_figures_equal() - >>> assert len(os.listdir("tmp_result_images")) == 0 + >>> assert len(list(Path("tmp_result_images").iterdir())) == 0 >>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass >>> @check_figures_equal(result_dir="tmp_result_images") @@ -63,12 +64,9 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag >>> with pytest.raises(GMTImageComparisonFailure): ... test_check_figures_unequal() >>> for suffix in ["", "-expected", "-failed-diff"]: - ... assert os.path.exists( - ... os.path.join( - ... "tmp_result_images", - ... f"test_check_figures_unequal{suffix}.png", - ... ) - ... ) + ... assert ( + ... Path("tmp_result_images") / f"test_check_figures_unequal{suffix}.png" + ... ).exists() >>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass """ allowed_chars = set(string.digits + string.ascii_letters + "_-[]()") @@ -78,7 +76,7 @@ def decorator(func): import pytest from matplotlib.testing.compare import compare_images - os.makedirs(result_dir, exist_ok=True) + Path(result_dir).mkdir(parents=True, exist_ok=True) old_sig = inspect.signature(func) @pytest.mark.parametrize("ext", extensions) @@ -93,8 +91,8 @@ def wrapper(*args, ext="png", request=None, **kwargs): file_name = func.__name__ try: fig_ref, fig_test = func(*args, **kwargs) - ref_image_path = os.path.join(result_dir, f"{file_name}-expected.{ext}") - test_image_path = os.path.join(result_dir, f"{file_name}.{ext}") + ref_image_path = Path(result_dir) / f"{file_name}-expected.{ext}" + test_image_path = Path(result_dir) / f"{file_name}.{ext}" fig_ref.savefig(ref_image_path) fig_test.savefig(test_image_path) @@ -107,11 +105,11 @@ def wrapper(*args, ext="png", request=None, **kwargs): in_decorator=True, ) if err is None: # Images are the same - os.remove(ref_image_path) - os.remove(test_image_path) + ref_image_path.unlink() + test_image_path.unlink() else: # Images are not the same for key in ["actual", "expected", "diff"]: - err[key] = os.path.relpath(err[key]) + err[key] = Path(err[key]).relative_to(".") raise GMTImageComparisonFailure( f"images not close (RMS {err['rms']:.3f}):\n" f"\t{err['actual']}\n" diff --git a/pygmt/src/grdfilter.py b/pygmt/src/grdfilter.py index a4a544819ad..a6e49c65001 100644 --- a/pygmt/src/grdfilter.py +++ b/pygmt/src/grdfilter.py @@ -114,7 +114,7 @@ def grdfilter(grid, **kwargs): Examples -------- - >>> import os + >>> from pathlib import Path >>> import pygmt >>> # Apply a filter of 600 km (full width) to the @earth_relief_30m_g file >>> # and return a filtered field (saved as netCDF) @@ -126,7 +126,7 @@ def grdfilter(grid, **kwargs): ... spacing=0.5, ... outgrid="filtered_pacific.nc", ... ) - >>> os.remove("filtered_pacific.nc") # Cleanup file + >>> Path("filtered_pacific.nc").unlink() # Cleanup file >>> # Apply a Gaussian smoothing filter of 600 km to the input DataArray >>> # and return a filtered DataArray with the smoothed field >>> grid = pygmt.datasets.load_earth_relief() diff --git a/pygmt/src/x2sys_cross.py b/pygmt/src/x2sys_cross.py index a8988a00af8..c530c964025 100644 --- a/pygmt/src/x2sys_cross.py +++ b/pygmt/src/x2sys_cross.py @@ -53,7 +53,7 @@ def tempfile_from_dftrack(track, suffix): ) yield tmpfilename finally: - os.remove(tmpfilename) + Path(tmpfilename).unlink() @fmt_docstring diff --git a/pygmt/tests/test_accessor.py b/pygmt/tests/test_accessor.py index a12c01e9265..ed047c2ec28 100644 --- a/pygmt/tests/test_accessor.py +++ b/pygmt/tests/test_accessor.py @@ -2,7 +2,6 @@ Test the behaviour of the GMTDataArrayAccessor class. """ -import os import sys from pathlib import Path @@ -101,7 +100,7 @@ def test_accessor_sliced_datacube(): assert grid.gmt.registration == 0 # gridline registration assert grid.gmt.gtype == 1 # geographic coordinate type finally: - os.remove(fname) + Path(fname).unlink() def test_accessor_grid_source_file_not_exist(): diff --git a/pygmt/tests/test_clib.py b/pygmt/tests/test_clib.py index 78121b13cda..2f655435ee4 100644 --- a/pygmt/tests/test_clib.py +++ b/pygmt/tests/test_clib.py @@ -2,7 +2,6 @@ Test the wrappers for the C API. """ -import os from contextlib import contextmanager from pathlib import Path @@ -22,7 +21,7 @@ ) from pygmt.helpers import GMTTempFile -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" @contextmanager @@ -136,11 +135,10 @@ def test_call_module(): """ Run a command to see if call_module works. """ - data_fname = os.path.join(TEST_DATA_DIR, "points.txt") out_fname = "test_call_module.txt" with clib.Session() as lib: with GMTTempFile() as out_fname: - lib.call_module("info", f"{data_fname} -C ->{out_fname.name}") + lib.call_module("info", f"{POINTS_DATA} -C ->{out_fname.name}") assert Path(out_fname.name).stat().st_size > 0 output = out_fname.read().strip() assert output == "11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338" diff --git a/pygmt/tests/test_clib_virtualfiles.py b/pygmt/tests/test_clib_virtualfiles.py index ce71553fc24..7e7822f99e5 100644 --- a/pygmt/tests/test_clib_virtualfiles.py +++ b/pygmt/tests/test_clib_virtualfiles.py @@ -2,9 +2,9 @@ Test the C API functions related to virtual files. """ -import os from importlib.util import find_spec from itertools import product +from pathlib import Path import numpy as np import pandas as pd @@ -15,8 +15,7 @@ from pygmt.helpers import GMTTempFile from pygmt.tests.test_clib import mock -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" @pytest.fixture(scope="module", name="data") diff --git a/pygmt/tests/test_contour.py b/pygmt/tests/test_contour.py index 416ad5c8a3e..6cca6ecbf7c 100644 --- a/pygmt/tests/test_contour.py +++ b/pygmt/tests/test_contour.py @@ -2,7 +2,7 @@ Test Figure.contour. """ -import os +from pathlib import Path import numpy as np import pandas as pd @@ -10,8 +10,7 @@ import xarray as xr from pygmt import Figure -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" @pytest.fixture(scope="module", name="data") diff --git a/pygmt/tests/test_figure.py b/pygmt/tests/test_figure.py index d33be107eda..042c9876e71 100644 --- a/pygmt/tests/test_figure.py +++ b/pygmt/tests/test_figure.py @@ -5,7 +5,6 @@ """ import importlib -import os from pathlib import Path import numpy as np @@ -82,10 +81,8 @@ def test_figure_savefig_exists(): fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af") prefix = "test_figure_savefig_exists" for fmt in "bmp eps jpg jpeg pdf png ppm tif PNG JPG JPEG Png".split(): - fname = f"{prefix}.{fmt}" + fname = Path(f"{prefix}.{fmt}") fig.savefig(fname) - - fname = Path(fname) assert fname.exists() fname.unlink() @@ -201,10 +198,10 @@ def test_figure_savefig_transparent(): with pytest.raises(GMTInvalidInput): fig.savefig(fname, transparent=True) # png should not raise an error - fname = f"{prefix}.png" + fname = Path(f"{prefix}.png") fig.savefig(fname, transparent=True) - assert os.path.exists(fname) - os.remove(fname) + assert fname.exists() + fname.unlink() def test_figure_savefig_filename_with_spaces(): @@ -215,8 +212,9 @@ def test_figure_savefig_filename_with_spaces(): fig.basemap(region=[0, 1, 0, 1], projection="X1c/1c", frame=True) with GMTTempFile(prefix="pygmt-filename with spaces", suffix=".png") as imgfile: fig.savefig(fname=imgfile.name) - assert r"\040" not in os.path.abspath(imgfile.name) - assert Path(imgfile.name).stat().st_size > 0 + imgpath = Path(imgfile.name).resolve() + assert r"\040" not in str(imgpath) + assert imgpath.stat().st_size > 0 def test_figure_savefig(): diff --git a/pygmt/tests/test_grd2cpt.py b/pygmt/tests/test_grd2cpt.py index 76d19905259..c2d9a257cc1 100644 --- a/pygmt/tests/test_grd2cpt.py +++ b/pygmt/tests/test_grd2cpt.py @@ -2,7 +2,7 @@ Test pygmt.grd2cpt. """ -import os +from pathlib import Path import pytest from pygmt import Figure, grd2cpt @@ -55,7 +55,7 @@ def test_grd2cpt_output_to_cpt_file(grid): """ with GMTTempFile(suffix=".cpt") as cptfile: grd2cpt(grid=grid, output=cptfile.name) - assert os.path.getsize(cptfile.name) > 0 + assert Path(cptfile.name).stat().st_size > 0 def test_grd2cpt_unrecognized_data_type(): diff --git a/pygmt/tests/test_grdcontour.py b/pygmt/tests/test_grdcontour.py index c40439bdc7b..2cedd80dc14 100644 --- a/pygmt/tests/test_grdcontour.py +++ b/pygmt/tests/test_grdcontour.py @@ -2,7 +2,7 @@ Test Figure.grdcontour. """ -import os +from pathlib import Path import numpy as np import pytest @@ -10,8 +10,7 @@ from pygmt.exceptions import GMTInvalidInput from pygmt.helpers.testing import load_static_earth_relief -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -TEST_CONTOUR_FILE = os.path.join(TEST_DATA_DIR, "contours.txt") +TEST_CONTOUR_FILE = Path(__file__).parent / "data" / "contours.txt" @pytest.fixture(scope="module", name="grid") diff --git a/pygmt/tests/test_grdtrack.py b/pygmt/tests/test_grdtrack.py index fdb25d9e5f7..e139171d948 100644 --- a/pygmt/tests/test_grdtrack.py +++ b/pygmt/tests/test_grdtrack.py @@ -2,7 +2,6 @@ Test pygmt.grdtrack. """ -import os from pathlib import Path import numpy as np @@ -14,8 +13,7 @@ from pygmt.helpers import GMTTempFile, data_kind from pygmt.helpers.testing import load_static_earth_relief -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "track.txt") +POINTS_DATA = Path(__file__).parent / "data" / "track.txt" @pytest.fixture(scope="module", name="dataarray") diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index 29cc61fe8b7..9b25c71aa0b 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -2,7 +2,7 @@ Test the helper functions/classes/etc used in wrapping GMT. """ -import os +from pathlib import Path import numpy as np import pytest @@ -90,9 +90,9 @@ def test_gmttempfile(): Check that file is really created and deleted. """ with GMTTempFile() as tmpfile: - assert os.path.exists(tmpfile.name) + assert Path(tmpfile.name).exists() # File should be deleted when leaving the with block - assert not os.path.exists(tmpfile.name) + assert not Path(tmpfile.name).exists() def test_gmttempfile_unique(): @@ -110,17 +110,21 @@ def test_gmttempfile_prefix_suffix(): Make sure the prefix and suffix of temporary files are user specifiable. """ with GMTTempFile() as tmpfile: - assert os.path.basename(tmpfile.name).startswith("pygmt-") - assert os.path.basename(tmpfile.name).endswith(".txt") + tmpname = Path(tmpfile.name).name + assert tmpname.startswith("pygmt-") + assert tmpname.endswith(".txt") with GMTTempFile(prefix="user-prefix-") as tmpfile: - assert os.path.basename(tmpfile.name).startswith("user-prefix-") - assert os.path.basename(tmpfile.name).endswith(".txt") + tmpname = Path(tmpfile.name).name + assert tmpname.startswith("user-prefix-") + assert tmpname.endswith(".txt") with GMTTempFile(suffix=".log") as tmpfile: - assert os.path.basename(tmpfile.name).startswith("pygmt-") - assert os.path.basename(tmpfile.name).endswith(".log") + tmpname = Path(tmpfile.name).name + assert tmpname.startswith("pygmt-") + assert tmpname.endswith(".log") with GMTTempFile(prefix="user-prefix-", suffix=".log") as tmpfile: - assert os.path.basename(tmpfile.name).startswith("user-prefix-") - assert os.path.basename(tmpfile.name).endswith(".log") + tmpname = Path(tmpfile.name).name + assert tmpname.startswith("user-prefix-") + assert tmpname.endswith(".log") def test_gmttempfile_read(): diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py index b812e1457ce..a14030cb772 100644 --- a/pygmt/tests/test_info.py +++ b/pygmt/tests/test_info.py @@ -2,9 +2,8 @@ Test pygmt.info. """ -import os -import pathlib import sys +from pathlib import Path, PurePosixPath, PureWindowsPath import numpy as np import numpy.testing as npt @@ -15,8 +14,7 @@ from pygmt.exceptions import GMTInvalidInput from pygmt.helpers.testing import skip_if_no -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" def test_info(): @@ -36,16 +34,16 @@ def test_info(): @pytest.mark.parametrize( "table", [ - pathlib.Path(POINTS_DATA), + Path(POINTS_DATA), pytest.param( - pathlib.PureWindowsPath(POINTS_DATA), + PureWindowsPath(POINTS_DATA), marks=pytest.mark.skipif( sys.platform != "win32", reason="PureWindowsPath is only available on Windows", ), ), pytest.param( - pathlib.PurePosixPath(POINTS_DATA), + PurePosixPath(POINTS_DATA), marks=pytest.mark.skipif( sys.platform == "win32", reason="PurePosixPath is not available on Windows", diff --git a/pygmt/tests/test_makecpt.py b/pygmt/tests/test_makecpt.py index eaba2589f04..39733c7cfc5 100644 --- a/pygmt/tests/test_makecpt.py +++ b/pygmt/tests/test_makecpt.py @@ -2,7 +2,6 @@ Test pygmt.makecpt. """ -import os from pathlib import Path import numpy as np @@ -11,8 +10,7 @@ from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import GMTTempFile -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" @pytest.fixture(scope="module", name="points") diff --git a/pygmt/tests/test_plot.py b/pygmt/tests/test_plot.py index 83bc356692f..76158bfe038 100644 --- a/pygmt/tests/test_plot.py +++ b/pygmt/tests/test_plot.py @@ -3,7 +3,6 @@ """ import datetime -import os from pathlib import Path import numpy as np @@ -14,8 +13,7 @@ from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import GMTTempFile -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" @pytest.fixture(scope="module", name="data") diff --git a/pygmt/tests/test_plot3d.py b/pygmt/tests/test_plot3d.py index ad91f06f8fa..c37c899a30b 100644 --- a/pygmt/tests/test_plot3d.py +++ b/pygmt/tests/test_plot3d.py @@ -2,7 +2,6 @@ Test Figure.plot3d. """ -import os from pathlib import Path import numpy as np @@ -11,8 +10,7 @@ from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import GMTTempFile -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") +POINTS_DATA = Path(__file__).parent / "data" / "points.txt" @pytest.fixture(scope="module", name="data") diff --git a/pygmt/tests/test_psconvert.py b/pygmt/tests/test_psconvert.py index 6cc82cc50e9..f0460be452b 100644 --- a/pygmt/tests/test_psconvert.py +++ b/pygmt/tests/test_psconvert.py @@ -2,7 +2,7 @@ Test Figure.psconvert. """ -import os +from pathlib import Path import pytest from pygmt import Figure @@ -18,9 +18,9 @@ def test_psconvert(): fig.basemap(region="10/70/-3/8", projection="X4i/3i", frame="a") prefix = "test_psconvert" fig.psconvert(prefix=prefix, fmt="f", crop=True) - fname = prefix + ".pdf" - assert os.path.exists(fname) - os.remove(fname) + fname = Path(prefix + ".pdf") + assert fname.exists() + fname.unlink() def test_psconvert_twice(): @@ -32,14 +32,14 @@ def test_psconvert_twice(): prefix = "test_psconvert_twice" # Make a PDF fig.psconvert(prefix=prefix, fmt="f") - fname = prefix + ".pdf" - assert os.path.exists(fname) - os.remove(fname) + fname = Path(prefix + ".pdf") + assert fname.exists() + fname.unlink() # Make a PNG fig.psconvert(prefix=prefix, fmt="g") - fname = prefix + ".png" - assert os.path.exists(fname) - os.remove(fname) + fname = Path(prefix + ".png") + assert fname.exists() + fname.unlink() def test_psconvert_without_prefix(): diff --git a/pygmt/tests/test_session_management.py b/pygmt/tests/test_session_management.py index 0fbe6f8e45b..77a3970787f 100644 --- a/pygmt/tests/test_session_management.py +++ b/pygmt/tests/test_session_management.py @@ -3,7 +3,6 @@ """ import multiprocessing as mp -import os from importlib import reload from pathlib import Path @@ -25,8 +24,8 @@ def test_begin_end(): lib.call_module("basemap", "-R10/70/-3/8 -JX4i/3i -Ba") end() begin() # Restart the global session - assert os.path.exists("pygmt-session.pdf") - os.remove("pygmt-session.pdf") + assert Path("pygmt-session.pdf").exists() + Path("pygmt-session.pdf").unlink() def test_gmt_compat_6_is_applied(capsys): @@ -54,12 +53,12 @@ def test_gmt_compat_6_is_applied(capsys): finally: end() # Clean up the global "gmt.conf" in the current directory - assert os.path.exists("gmt.conf") - os.remove("gmt.conf") - assert os.path.exists("pygmt-session.pdf") - os.remove("pygmt-session.pdf") + assert Path("gmt.conf").exists() + Path("gmt.conf").unlink() + assert Path("pygmt-session.pdf").exists() + Path("pygmt-session.pdf").unlink() # Make sure no global "gmt.conf" in the current directory - assert not os.path.exists("gmt.conf") + assert not Path("gmt.conf").exists() begin() # Restart the global session diff --git a/pygmt/tests/test_sphinx_gallery.py b/pygmt/tests/test_sphinx_gallery.py index 205f0f3e3e5..c40d4732a0b 100644 --- a/pygmt/tests/test_sphinx_gallery.py +++ b/pygmt/tests/test_sphinx_gallery.py @@ -2,7 +2,7 @@ Test the sphinx-gallery scraper and code required to make it work. """ -import os +from pathlib import Path from tempfile import TemporaryDirectory import pytest @@ -27,13 +27,13 @@ def test_pygmtscraper(): assert len(SHOWED_FIGURES) == 1 assert SHOWED_FIGURES[0] is fig scraper = PyGMTScraper() - with TemporaryDirectory(dir=os.getcwd()) as tmpdir: + with TemporaryDirectory(dir=Path.cwd()) as tmpdir: conf = {"src_dir": "meh"} - fname = os.path.join(tmpdir, "meh.png") + fname = Path(tmpdir) / "meh.png" block_vars = {"image_path_iterator": (i for i in [fname])} - assert not os.path.exists(fname) + assert not fname.exists() scraper(None, block_vars, conf) - assert os.path.exists(fname) + assert fname.exists() assert not SHOWED_FIGURES finally: SHOWED_FIGURES.extend(showed) diff --git a/pygmt/tests/test_text.py b/pygmt/tests/test_text.py index 7ef50224c38..3969c451e68 100644 --- a/pygmt/tests/test_text.py +++ b/pygmt/tests/test_text.py @@ -2,7 +2,7 @@ Test Figure.text. """ -import os +from pathlib import Path import numpy as np import pytest @@ -10,9 +10,9 @@ from pygmt.exceptions import GMTCLibError, GMTInvalidInput from pygmt.helpers import GMTTempFile -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") -POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt") -CITIES_DATA = os.path.join(TEST_DATA_DIR, "cities.txt") +TEST_DATA_DIR = Path(__file__).parent / "data" +POINTS_DATA = TEST_DATA_DIR / "points.txt" +CITIES_DATA = TEST_DATA_DIR / "cities.txt" @pytest.fixture(scope="module", name="projection") diff --git a/pygmt/tests/test_x2sys_cross.py b/pygmt/tests/test_x2sys_cross.py index 226fbc06e6d..49256953707 100644 --- a/pygmt/tests/test_x2sys_cross.py +++ b/pygmt/tests/test_x2sys_cross.py @@ -3,7 +3,6 @@ """ import copy -import os from pathlib import Path from tempfile import TemporaryDirectory @@ -25,7 +24,7 @@ def _fixture_mock_x2sys_home(monkeypatch): Set the X2SYS_HOME environment variable to the current working directory for the test session. """ - monkeypatch.setenv("X2SYS_HOME", os.getcwd()) + monkeypatch.setenv("X2SYS_HOME", Path.cwd()) @pytest.fixture(scope="module", name="tracks") @@ -44,16 +43,17 @@ def test_x2sys_cross_input_file_output_file(): Run x2sys_cross by passing in a filename, and output internal crossovers to an ASCII txt file. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tmpdir_p = Path(tmpdir) + tag = tmpdir_p.name x2sys_init(tag=tag, fmtfile="xyz", force=True) - outfile = os.path.join(tmpdir, "tmp_coe.txt") + outfile = tmpdir_p / "tmp_coe.txt" output = x2sys_cross( tracks=["@tut_ship.xyz"], tag=tag, coe="i", outfile=outfile ) assert output is None # check that output is None since outfile is set - assert Path(outfile).stat().st_size > 0 # check that outfile exists at path + assert outfile.stat().st_size > 0 # check that outfile exists at path _ = pd.read_csv(outfile, sep="\t", header=2) # ensure ASCII text file loads ok @@ -67,8 +67,8 @@ def test_x2sys_cross_input_file_output_dataframe(): Run x2sys_cross by passing in a filename, and output internal crossovers to a pandas.DataFrame. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tag = Path(tmpdir).name x2sys_init(tag=tag, fmtfile="xyz", force=True) output = x2sys_cross(tracks=["@tut_ship.xyz"], tag=tag, coe="i") @@ -86,8 +86,8 @@ def test_x2sys_cross_input_dataframe_output_dataframe(tracks): Run x2sys_cross by passing in one dataframe, and output internal crossovers to a pandas.DataFrame. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tag = Path(tmpdir).name x2sys_init(tag=tag, fmtfile="xyz", force=True) output = x2sys_cross(tracks=tracks, tag=tag, coe="i") @@ -107,16 +107,15 @@ def test_x2sys_cross_input_two_dataframes(): Run x2sys_cross by passing in two pandas.DataFrame tables with a time column, and output external crossovers to a pandas.DataFrame. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tmpdir_p = Path(tmpdir) + tag = tmpdir_p.name x2sys_init( tag=tag, fmtfile="xyz", suffix="xyzt", units=["de", "se"], force=True ) # Add a time row to the x2sys fmtfile - with open( - file=os.path.join(tmpdir, "xyz.fmt"), mode="a", encoding="utf8" - ) as fmtfile: + with open(tmpdir_p / "xyz.fmt", mode="a", encoding="utf8") as fmtfile: fmtfile.write("time\ta\tN\t0\t1\t0\t%g\n") # Create pandas.DataFrame track tables @@ -144,8 +143,8 @@ def test_x2sys_cross_input_dataframe_with_nan(tracks): Run x2sys_cross by passing in one dataframe with NaN values, and output internal crossovers to a pandas.DataFrame. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tag = Path(tmpdir).name x2sys_init( tag=tag, fmtfile="xyz", suffix="xyzt", units=["de", "se"], force=True ) @@ -169,15 +168,15 @@ def test_x2sys_cross_input_two_filenames(): Run x2sys_cross by passing in two filenames, and output external crossovers to a pandas.DataFrame. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tag = Path(tmpdir).name x2sys_init(tag=tag, fmtfile="xyz", force=True) # Create temporary xyz files for i in range(2): rng = np.random.default_rng(seed=i) with open( - os.path.join(os.getcwd(), f"track_{i}.xyz"), mode="w", encoding="utf8" + Path.cwd() / f"track_{i}.xyz", mode="w", encoding="utf8" ) as fname: np.savetxt(fname=fname, X=rng.random((10, 3))) @@ -188,7 +187,7 @@ def test_x2sys_cross_input_two_filenames(): columns = list(output.columns) assert columns[:6] == ["x", "y", "i_1", "i_2", "dist_1", "dist_2"] assert columns[6:] == ["head_1", "head_2", "vel_1", "vel_2", "z_X", "z_M"] - _ = [os.remove(f"track_{i}.xyz") for i in range(2)] # cleanup track files + _ = [Path(f"track_{i}.xyz").unlink() for i in range(2)] # cleanup track files def test_x2sys_cross_invalid_tracks_input_type(tracks): @@ -212,8 +211,8 @@ def test_x2sys_cross_region_interpolation_numpoints(): Test that x2sys_cross's region (R), interpolation (l) and numpoints (W) arguments work. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tag = Path(tmpdir).name x2sys_init(tag=tag, fmtfile="xyz", force=True) output = x2sys_cross( tracks=["@tut_ship.xyz"], @@ -240,8 +239,8 @@ def test_x2sys_cross_trackvalues(): """ Test that x2sys_cross's trackvalues (Z) argument work. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tag = Path(tmpdir).name x2sys_init(tag=tag, fmtfile="xyz", force=True) output = x2sys_cross(tracks=["@tut_ship.xyz"], tag=tag, trackvalues=True) diff --git a/pygmt/tests/test_x2sys_init.py b/pygmt/tests/test_x2sys_init.py index 808c3f68315..c0664110eda 100644 --- a/pygmt/tests/test_x2sys_init.py +++ b/pygmt/tests/test_x2sys_init.py @@ -2,7 +2,7 @@ Test pygmt.x2sys_init. """ -import os +from pathlib import Path from tempfile import TemporaryDirectory import pytest @@ -15,7 +15,7 @@ def _fixture_mock_x2sys_home(monkeypatch): Set the X2SYS_HOME environment variable to the current working directory for the test session. """ - monkeypatch.setenv("X2SYS_HOME", os.getcwd()) + monkeypatch.setenv("X2SYS_HOME", Path.cwd()) @pytest.mark.usefixtures("mock_x2sys_home") @@ -24,13 +24,14 @@ def test_x2sys_init_region_spacing(): Test that x2sys_init's region (R) and spacing (I) sequence arguments accept a list properly. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tmpdir_p = Path(tmpdir) + tag = tmpdir_p.name x2sys_init( tag=tag, fmtfile="xyz", force=True, region=[0, 10, 20, 30], spacing=[5, 5] ) - with open(os.path.join(tmpdir, f"{tag}.tag"), encoding="utf8") as tagpath: + with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath: tail_line = tagpath.readlines()[-1] assert "-R0/10/20/30" in tail_line assert "-I5/5" in tail_line @@ -42,8 +43,9 @@ def test_x2sys_init_units_gap(): """ Test that x2sys_init's units (N) and gap (W) arguments accept a list properly. """ - with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: - tag = os.path.basename(tmpdir) + with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir: + tmpdir_p = Path(tmpdir) + tag = tmpdir_p.name x2sys_init( tag=tag, fmtfile="xyz", @@ -52,7 +54,7 @@ def test_x2sys_init_units_gap(): gap=["tseconds", "de"], ) - with open(os.path.join(tmpdir, f"{tag}.tag"), encoding="utf8") as tagpath: + with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath: tail_line = tagpath.readlines()[-1] assert "-Nse -Nde" in tail_line assert "-Wtseconds -Wde" in tail_line