From bbd84d134f25c21718b168360e13708d33d6528c Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Thu, 21 Jan 2021 03:33:59 -0500 Subject: [PATCH] Add docformatter to format plain text in docstrings (#642) * Add docformatter to format docstrings following a subset of PEP 257 * Add --make-summary-multi-line * Install docformatter to make /format work * Sort dependencies alphabetically in environment.yml and requirements-dev.txt * Format all docstrings Co-authored-by: Wei Ji <23487320+weiji14@users.noreply.github.com> --- .github/workflows/ci_tests.yaml | 4 +- .github/workflows/format-command.yml | 2 +- CONTRIBUTING.md | 5 +- Makefile | 8 +- environment.yml | 21 ++-- pygmt/__init__.py | 13 +- pygmt/base_plotting.py | 27 ++-- pygmt/clib/conversion.py | 4 - pygmt/clib/loading.py | 4 - pygmt/clib/session.py | 35 ++---- pygmt/datasets/earth_relief.py | 7 +- pygmt/datasets/tutorial.py | 2 - pygmt/figure.py | 11 +- pygmt/filtering.py | 2 +- pygmt/gridding.py | 2 +- pygmt/gridops.py | 3 +- pygmt/helpers/decorators.py | 11 +- pygmt/helpers/tempfile.py | 2 - pygmt/helpers/utils.py | 5 - pygmt/mathops.py | 2 +- pygmt/modules.py | 2 - pygmt/sampling.py | 3 +- pygmt/tests/test_accessor.py | 5 +- pygmt/tests/test_basemap.py | 44 +++++-- pygmt/tests/test_blockmedian.py | 12 +- pygmt/tests/test_clib.py | 168 ++++++++++++++++++------- pygmt/tests/test_clib_loading.py | 18 ++- pygmt/tests/test_clib_put_matrix.py | 12 +- pygmt/tests/test_clib_put_strings.py | 8 +- pygmt/tests/test_clib_put_vector.py | 20 ++- pygmt/tests/test_coast.py | 42 +++++-- pygmt/tests/test_colorbar.py | 13 +- pygmt/tests/test_config.py | 14 ++- pygmt/tests/test_contour.py | 24 +++- pygmt/tests/test_datasets.py | 44 +++++-- pygmt/tests/test_figure.py | 41 ++++-- pygmt/tests/test_grdcontour.py | 31 +++-- pygmt/tests/test_grdcut.py | 26 ++-- pygmt/tests/test_grdimage.py | 25 ++-- pygmt/tests/test_grdinfo.py | 14 ++- pygmt/tests/test_grdtrack.py | 22 ++-- pygmt/tests/test_grdview.py | 14 ++- pygmt/tests/test_helpers.py | 42 +++++-- pygmt/tests/test_image.py | 4 +- pygmt/tests/test_info.py | 48 +++++-- pygmt/tests/test_legend.py | 4 +- pygmt/tests/test_logo.py | 10 +- pygmt/tests/test_makecpt.py | 38 +++--- pygmt/tests/test_meca.py | 14 +-- pygmt/tests/test_plot.py | 79 +++++++++--- pygmt/tests/test_plot3d.py | 68 +++++++--- pygmt/tests/test_session_management.py | 2 + pygmt/tests/test_sphinx_gallery.py | 4 +- pygmt/tests/test_surface.py | 16 +-- pygmt/tests/test_text.py | 52 +++++--- pygmt/tests/test_which.py | 10 +- pygmt/tests/test_x2sys_cross.py | 14 +-- pygmt/tests/test_x2sys_init.py | 8 +- requirements-dev.txt | 21 ++-- 59 files changed, 789 insertions(+), 417 deletions(-) diff --git a/.github/workflows/ci_tests.yaml b/.github/workflows/ci_tests.yaml index ac01aaffbda..c46a91e0e08 100644 --- a/.github/workflows/ci_tests.yaml +++ b/.github/workflows/ci_tests.yaml @@ -32,10 +32,10 @@ jobs: - name: Install packages run: | - pip install black blackdoc flake8 pylint isort + pip install black blackdoc docformatter flake8 pylint isort sudo apt-get install dos2unix - - name: Formatting check (black and flake8) + - name: Formatting check (black, blackdoc, docformatter, flake8 and isort) run: make check - name: Linting (pylint) diff --git a/.github/workflows/format-command.yml b/.github/workflows/format-command.yml index 33cd2b40ba4..2fb42a220b5 100644 --- a/.github/workflows/format-command.yml +++ b/.github/workflows/format-command.yml @@ -26,7 +26,7 @@ jobs: # Install formatting tools - name: Install formatting tools run: | - pip install black blackdoc flake8 isort + pip install black blackdoc docformatter flake8 isort sudo apt-get install dos2unix # Run "make format" and commit the change to the PR branch diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f874de52ed4..9e04f65e0b6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -249,10 +249,11 @@ We use some tools: - [Black](https://github.com/ambv/black) - [blackdoc](https://github.com/keewis/blackdoc) +- [docformatter](https://github.com/myint/docformatter) - [isort](https://pycqa.github.io/isort/) to format the code so we don't have to think about it. -Black loosely follows the [PEP8](http://pep8.org) guide but with a few differences. +Black and blackdoc loosely follows the [PEP8](http://pep8.org) guide but with a few differences. Regardless, you won't have to worry about formatting the code yourself. Before committing, run it to automatically format your code: @@ -273,7 +274,7 @@ common errors. The [`Makefile`](Makefile) contains rules for running both checks: ```bash -make check # Runs flake8, black, blackdoc and isort (in check mode) +make check # Runs black, blackdoc, docformatter, flake8 and isort (in check mode) make lint # Runs pylint, which is a bit slower ``` diff --git a/Makefile b/Makefile index 145ddf336d4..9ca801ecb84 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,8 @@ PYTEST_COV_ARGS=--cov=$(PROJECT) --cov-config=../pyproject.toml \ --pyargs ${PYTEST_EXTRA} BLACK_FILES=$(PROJECT) setup.py doc/conf.py examples BLACKDOC_OPTIONS=--line-length 79 +DOCFORMATTER_FILES=$(PROJECT) setup.py doc/conf.py examples +DOCFORMATTER_OPTIONS=--recursive --pre-summary-newline --make-summary-multi-line --wrap-summaries 79 --wrap-descriptions 79 FLAKE8_FILES=$(PROJECT) setup.py doc/conf.py LINT_FILES=$(PROJECT) setup.py doc/conf.py @@ -14,8 +16,8 @@ help: @echo "" @echo " install install in editable mode" @echo " test run the test suite (including doctests) and report coverage" - @echo " format run black and blackdoc to automatically format the code" - @echo " check run code style and quality checks (black, blackdoc, isort and flake8)" + @echo " format run black, blackdoc, docformatter and isort to automatically format the code" + @echo " check run code style and quality checks (black, blackdoc, docformatter, flake8 and isort)" @echo " lint run pylint for a deeper (and slower) quality check" @echo " clean clean up build and generated files" @echo " distclean clean up build and generated files, including project metadata files" @@ -37,11 +39,13 @@ test: format: isort . + docformatter --in-place $(DOCFORMATTER_OPTIONS) $(DOCFORMATTER_FILES) black $(BLACK_FILES) blackdoc $(BLACKDOC_OPTIONS) $(BLACK_FILES) check: isort . --check + docformatter --check $(DOCFORMATTER_OPTIONS) $(DOCFORMATTER_FILES) black --check $(BLACK_FILES) blackdoc --check $(BLACKDOC_OPTIONS) $(BLACK_FILES) flake8 $(FLAKE8_FILES) diff --git a/environment.yml b/environment.yml index 1a62bdd5495..5a475ceee86 100644 --- a/environment.yml +++ b/environment.yml @@ -11,19 +11,20 @@ dependencies: - xarray - netCDF4 - packaging - - ipython - - matplotlib - - jupyter - - pytest>=6.0 - - pytest-cov - - pytest-mpl - - coverage[toml] - black - blackdoc + - coverage[toml] + - docformatter + - flake8 + - ipython - isort>=5 + - jupyter + - matplotlib + - nbsphinx - pylint - - flake8 + - pytest-cov + - pytest-mpl + - pytest>=6.0 - sphinx - - sphinx_rtd_theme=0.4.3 - sphinx-gallery - - nbsphinx + - sphinx_rtd_theme=0.4.3 diff --git a/pygmt/__init__.py b/pygmt/__init__.py index 2b2b2f256d5..a565677f6c2 100644 --- a/pygmt/__init__.py +++ b/pygmt/__init__.py @@ -67,7 +67,9 @@ def show_versions(): import sys def _get_module_version(modname): - """Get version information of a Python module.""" + """ + Get version information of a Python module. + """ try: if modname in sys.modules: module = sys.modules[modname] @@ -82,7 +84,9 @@ def _get_module_version(modname): return None def _get_ghostscript_version(): - """Get ghostscript version.""" + """ + Get ghostscript version. + """ os_name = sys.platform if os_name.startswith("linux") or os_name == "darwin": cmds = ["gs"] @@ -102,7 +106,9 @@ def _get_ghostscript_version(): return None def _get_gmt_version(): - """Get GMT version.""" + """ + Get GMT version. + """ try: version = subprocess.check_output( ["gmt", "--version"], universal_newlines=True @@ -164,7 +170,6 @@ def test(doctest=True, verbose=True, coverage=False, figures=True): AssertionError If pytest returns a non-zero error code indicating that some tests have failed. - """ import pytest diff --git a/pygmt/base_plotting.py b/pygmt/base_plotting.py index a8b9d5c3014..e41d2f25298 100644 --- a/pygmt/base_plotting.py +++ b/pygmt/base_plotting.py @@ -1,5 +1,6 @@ """ Base class with plot generating commands. + Does not define any special non-GMT methods (savefig, show, etc). """ import contextlib @@ -52,7 +53,6 @@ def _preprocess(self, **kwargs): # pylint: disable=no-self-use >>> base = BasePlotting() >>> base._preprocess(resolution="low") {'resolution': 'low'} - """ return kwargs @@ -266,7 +266,6 @@ def colorbar(self, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) with Session() as lib: @@ -295,7 +294,7 @@ def colorbar(self, **kwargs): @kwargs_to_strings(R="sequence", L="sequence", A="sequence_plus", p="sequence") def grdcontour(self, grid, **kwargs): """ - Convert grids or images to contours and plot them on maps + Convert grids or images to contours and plot them on maps. Takes a grid file name or an xarray.DataArray object as input. @@ -511,7 +510,6 @@ def grdimage(self, grid, **kwargs): {p} {t} {x} - """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) @@ -624,7 +622,6 @@ def grdview(self, grid, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) @@ -827,7 +824,6 @@ def plot(self, x=None, y=None, data=None, sizes=None, direction=None, **kwargs): {t} *transparency* can also be a 1d array to set varying transparency for symbols. - """ kwargs = self._preprocess(**kwargs) @@ -900,7 +896,7 @@ def plot3d( self, x=None, y=None, z=None, data=None, sizes=None, direction=None, **kwargs ): """ - Plot lines, polygons, and symbols in 3-D + Plot lines, polygons, and symbols in 3-D. Takes a matrix, (x,y,z) triplets, or a file name as input and plots lines, polygons, or symbols at those locations in 3-D. @@ -1010,7 +1006,6 @@ def plot3d( {t} *transparency* can also be a 1d array to set varying transparency for symbols. - """ kwargs = self._preprocess(**kwargs) @@ -1132,7 +1127,6 @@ def contour(self, x=None, y=None, z=None, data=None, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) @@ -1208,7 +1202,6 @@ def basemap(self, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) if not ("B" in kwargs or "L" in kwargs or "Td" in kwargs or "Tm" in kwargs): @@ -1267,7 +1260,6 @@ def logo(self, **kwargs): {V} {XY} {t} - """ kwargs = self._preprocess(**kwargs) with Session() as lib: @@ -1715,17 +1707,20 @@ def meca( # pylint: disable=too-many-statements def set_pointer(data_pointers, spec): - """Set optional parameter pointers based on DataFrame or dict, if - those parameters are present in the DataFrame or dict.""" + """ + Set optional parameter pointers based on DataFrame or dict, if + those parameters are present in the DataFrame or dict. + """ for param in list(data_pointers.keys()): if param in spec: # set pointer based on param name data_pointers[param] = spec[param] def update_pointers(data_pointers): - """Updates variables based on the location of data, as the - following data can be passed as parameters or it can be - contained in `spec`.""" + """ + Updates variables based on the location of data, as the following + data can be passed as parameters or it can be contained in `spec`. + """ # update all pointers longitude = data_pointers["longitude"] latitude = data_pointers["latitude"] diff --git a/pygmt/clib/conversion.py b/pygmt/clib/conversion.py index 9209c4003ca..24c6c4470f3 100644 --- a/pygmt/clib/conversion.py +++ b/pygmt/clib/conversion.py @@ -79,7 +79,6 @@ def dataarray_to_matrix(grid): [-150.5, -78.5, -80.5, -48.5] >>> print(inc) [2.0, 2.0] - """ if len(grid.dims) != 2: raise GMTInvalidInput( @@ -158,7 +157,6 @@ def vectors_to_arrays(vectors): >>> data = [[1, 2], (3, 4), range(5, 7)] >>> all(isinstance(i, np.ndarray) for i in vectors_to_arrays(data)) True - """ arrays = [as_c_contiguous(np.asarray(i)) for i in vectors] return arrays @@ -200,7 +198,6 @@ def as_c_contiguous(array): True >>> as_c_contiguous(x).flags.c_contiguous True - """ if not array.flags.c_contiguous: return array.copy(order="C") @@ -238,7 +235,6 @@ def kwargs_to_ctypes_array(argument, kwargs, dtype): ... ) >>> print(should_be_none) None - """ if argument in kwargs: return dtype(*kwargs[argument]) diff --git a/pygmt/clib/loading.py b/pygmt/clib/loading.py index 16e82d4b0c1..be14b65b296 100644 --- a/pygmt/clib/loading.py +++ b/pygmt/clib/loading.py @@ -30,7 +30,6 @@ def load_libgmt(): GMTCLibNotFoundError If there was any problem loading the library (couldn't find it or couldn't access the functions). - """ lib_fullnames = clib_full_names() error = True @@ -64,7 +63,6 @@ def clib_names(os_name): ------- libnames : list of str List of possible names of GMT's shared library. - """ if os_name.startswith("linux"): libnames = ["libgmt.so"] @@ -93,7 +91,6 @@ def clib_full_names(env=None): ------- lib_fullnames: list of str List of possible full names of GMT's shared library. - """ if env is None: env = os.environ @@ -127,7 +124,6 @@ def check_libgmt(libgmt): Raises ------ GMTCLibError - """ # Check if a few of the functions we need are in the library functions = ["Create_Session", "Get_Enum", "Call_Module", "Destroy_Session"] diff --git a/pygmt/clib/session.py b/pygmt/clib/session.py index ab4035efb4e..3d655fc5f6b 100644 --- a/pygmt/clib/session.py +++ b/pygmt/clib/session.py @@ -1,7 +1,8 @@ """ Defines the Session class to create and destroy a GMT API session and provides -access to the API functions. Uses ctypes to wrap most of the core functions -from the C API. +access to the API functions. + +Uses ctypes to wrap most of the core functions from the C API. """ import ctypes as ctp import sys @@ -132,7 +133,6 @@ def session_pointer(self): GMTCLibNoSessionError If trying to access without a currently open GMT session (i.e., outside of the context manager). - """ if not hasattr(self, "_session_pointer") or self._session_pointer is None: raise GMTCLibNoSessionError("No currently open GMT API session.") @@ -147,7 +147,9 @@ def session_pointer(self, session): @property def info(self): - "Dictionary with the GMT version and default paths and parameters." + """ + Dictionary with the GMT version and default paths and parameters. + """ if not hasattr(self, "_info"): self._info = { "version": self.get_default("API_VERSION"), @@ -177,7 +179,6 @@ def __enter__(self): If the version reported by libgmt is less than ``Session.required_version``. Will destroy the session before raising the exception. - """ self.create("pygmt-session") # Need to store the version info because 'get_default' won't work after @@ -202,7 +203,7 @@ def __exit__(self, exc_type, exc_value, traceback): def __getitem__(self, name): """ - Get the value of a GMT constant (C enum) from gmt_resources.h + Get the value of a GMT constant (C enum) from gmt_resources.h. Used to set configuration values for other API calls. Wraps ``GMT_Get_Enum``. @@ -222,7 +223,6 @@ def __getitem__(self, name): ------ GMTCLibError If the constant doesn't exist. - """ c_get_enum = self.get_libgmt_func( "GMT_Get_Enum", argtypes=[ctp.c_void_p, ctp.c_char_p], restype=ctp.c_int @@ -277,7 +277,6 @@ def get_libgmt_func(self, name, argtypes=None, restype=None): ... >>> type(func) ._FuncPtr'> - """ if not hasattr(self, "_libgmt"): self._libgmt = load_libgmt() @@ -313,7 +312,6 @@ def create(self, name): ---------- name : str A name for this session. Doesn't really affect the outcome. - """ try: # Won't raise an exception if there is a currently open session @@ -343,8 +341,10 @@ def create(self, name): def print_func(file_pointer, message): # pylint: disable=unused-argument """ Callback function that the GMT C API will use to print log and - error messages. We'll capture the messages and print them to stderr - so that they will show up on the Jupyter notebook. + error messages. + + We'll capture the messages and print them to stderr so that they + will show up on the Jupyter notebook. """ message = message.decode().strip() self._error_log.append(message) @@ -446,7 +446,6 @@ def get_default(self, name): ------ GMTCLibError If the parameter doesn't exist. - """ c_get_default = self.get_libgmt_func( "GMT_Get_Default", @@ -489,7 +488,6 @@ def call_module(self, module, args): ------ GMTCLibError If the returned status code of the function is non-zero. - """ c_call_module = self.get_libgmt_func( "GMT_Call_Module", @@ -547,7 +545,6 @@ def create_data(self, family, geometry, mode, **kwargs): data_ptr : int A ctypes pointer (an integer) to the allocated ``GMT_Dataset`` object. - """ c_create_data = self.get_libgmt_func( "GMT_Create_Data", @@ -717,7 +714,6 @@ def _check_dtype_and_dim(self, array, ndim): ... gmttype == ses["GMT_FLOAT"] ... True - """ # check the array has the given dimension if array.ndim != ndim: @@ -771,7 +767,6 @@ def put_vector(self, dataset, column, vector): GMTCLibError If given invalid input or ``GMT_Put_Vector`` exits with status != 0. - """ c_put_vector = self.get_libgmt_func( "GMT_Put_Vector", @@ -833,7 +828,6 @@ def put_strings(self, dataset, family, strings): GMTCLibError If given invalid input or ``GMT_Put_Strings`` exits with status != 0. - """ c_put_strings = self.get_libgmt_func( "GMT_Put_Strings", @@ -896,7 +890,6 @@ def put_matrix(self, dataset, matrix, pad=0): GMTCLibError If given invalid input or ``GMT_Put_Matrix`` exits with status != 0. - """ c_put_matrix = self.get_libgmt_func( "GMT_Put_Matrix", @@ -950,7 +943,6 @@ def write_data(self, family, geometry, mode, wesn, output, data): GMTCLibError For invalid input arguments or if the GMT API functions returns a non-zero status code. - """ c_write_data = self.get_libgmt_func( "GMT_Write_Data", @@ -1047,7 +1039,6 @@ def open_virtual_file(self, family, geometry, direction, data): ... print(ofile.read().strip()) ... : N = 5 <0/4> <5/9> - """ c_open_virtualfile = self.get_libgmt_func( "GMT_Open_VirtualFile", @@ -1144,7 +1135,6 @@ def virtualfile_from_vectors(self, *vectors): ... print(fout.read().strip()) ... : N = 3 <1/3> <4/6> <7/9> - """ # Conversion to a C-contiguous array needs to be done here and not in # put_vector or put_strings because we need to maintain a reference to @@ -1258,7 +1248,6 @@ def virtualfile_from_matrix(self, matrix): ... print(fout.read().strip()) ... : N = 4 <0/9> <1/10> <2/11> - """ # Conversion to a C-contiguous array needs to be done here and not in # put_matrix because we need to maintain a reference to the copy while @@ -1342,7 +1331,6 @@ def virtualfile_from_grid(self, grid): ... -180 180 -90 90 -8182 5651.5 1 1 360 180 1 1 >>> # The output is: w e s n z0 z1 dx dy n_columns n_rows reg gtype - """ _gtype = {0: "GMT_GRID_IS_CARTESIAN", 1: "GMT_GRID_IS_GEO"}[grid.gmt.gtype] _reg = {0: "GMT_GRID_NODE_REG", 1: "GMT_GRID_PIXEL_REG"}[grid.gmt.registration] @@ -1426,7 +1414,6 @@ def extract_region(self): ... >>> print(", ".join(["{:.2f}".format(x) for x in wesn])) -165.00, -150.00, 15.00, 25.00 - """ c_extract_region = self.get_libgmt_func( "GMT_Extract_Region", diff --git a/pygmt/datasets/earth_relief.py b/pygmt/datasets/earth_relief.py index 30ceff5d2c8..1e5a13176c7 100644 --- a/pygmt/datasets/earth_relief.py +++ b/pygmt/datasets/earth_relief.py @@ -1,6 +1,8 @@ """ -Function to download the Earth relief datasets from the GMT data server, -and load as DataArray. The grids are available in various resolutions. +Function to download the Earth relief datasets from the GMT data server, and +load as DataArray. + +The grids are available in various resolutions. """ import xarray as xr from pygmt.exceptions import GMTInvalidInput @@ -64,7 +66,6 @@ def load_earth_relief(resolution="01d", region=None, registration=None): >>> grid = load_earth_relief( ... "05m", region=[120, 160, 30, 60], registration="gridline" ... ) - """ # earth relief data stored as single grids for low resolutions diff --git a/pygmt/datasets/tutorial.py b/pygmt/datasets/tutorial.py index 20bec174e2e..210065b1760 100644 --- a/pygmt/datasets/tutorial.py +++ b/pygmt/datasets/tutorial.py @@ -21,7 +21,6 @@ def load_japan_quakes(): data : pandas.Dataframe The data table. Columns are year, month, day, latitude, longitude, depth (in km), and magnitude of the earthquakes. - """ fname = which("@tut_quakes.ngdc", download="c") data = pd.read_csv(fname, header=1, sep=r"\s+") @@ -98,7 +97,6 @@ def load_usgs_quakes(): data : pandas.Dataframe The data table. Use ``print(data.describe())`` to see the available columns. - """ fname = which("@usgs_quakes_22.txt", download="c") data = pd.read_csv(fname) diff --git a/pygmt/figure.py b/pygmt/figure.py index ee912efe3e1..c638a64e83a 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -58,7 +58,6 @@ class Figure(BasePlotting): >>> # The fig.region attribute shows the WESN bounding box for the figure >>> print(", ".join("{:.2f}".format(i) for i in fig.region)) 122.94, 145.82, 20.53, 45.52 - """ def __init__(self): @@ -97,7 +96,9 @@ def _preprocess(self, **kwargs): @property def region(self): - "The geographic WESN bounding box for the current figure." + """ + The geographic WESN bounding box for the current figure. + """ self._activate_figure() with Session() as lib: wesn = lib.extract_region() @@ -163,7 +164,6 @@ def psconvert(self, **kwargs): formats. For example, ``'ef'`` creates both an EPS and a PDF file. Using ``'F'`` creates a multi-page PDF file from the list of input PS or PDF files. It requires the *prefix* option. - """ kwargs = self._preprocess(**kwargs) # Default cropping the figure to True @@ -208,7 +208,6 @@ def savefig( dpi : int Set raster resolution in dpi. Default is 720 for PDF, 300 for others. - """ # All supported formats fmts = dict(png="g", pdf="f", jpg="j", bmp="b", eps="e", tif="t", kml="g") @@ -263,7 +262,6 @@ def show(self, dpi=300, width=500, method="static"): ------- img : IPython.display.Image Only if ``method != 'external'``. - """ # Module level variable to know which figures had their show method # called. Needed for the sphinx-gallery scraper. @@ -346,7 +344,6 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs): preview : str or bytes 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, "{}.{}".format(self._name, fmt)) self.savefig(fname, dpi=dpi, **kwargs) @@ -359,6 +356,7 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs): def _repr_png_(self): """ Show a PNG preview if the object is returned in an interactive shell. + For the Jupyter notebook or IPython Qt console. """ png = self._preview(fmt="png", dpi=70, anti_alias=True, as_bytes=True) @@ -367,6 +365,7 @@ def _repr_png_(self): def _repr_html_(self): """ Show the PNG image embedded in HTML with a controlled width. + Looks better than the raw PNG. """ raw_png = self._preview(fmt="png", dpi=300, anti_alias=True, as_bytes=True) diff --git a/pygmt/filtering.py b/pygmt/filtering.py index 6b777cf1ee0..ed4e82f5c29 100644 --- a/pygmt/filtering.py +++ b/pygmt/filtering.py @@ -1,5 +1,5 @@ """ -GMT modules for Filtering of 1-D and 2-D Data +GMT modules for Filtering of 1-D and 2-D Data. """ import pandas as pd from pygmt.clib import Session diff --git a/pygmt/gridding.py b/pygmt/gridding.py index 7e559e3f50b..7129913d0c3 100644 --- a/pygmt/gridding.py +++ b/pygmt/gridding.py @@ -1,5 +1,5 @@ """ -GMT modules for Gridding of Data Tables +GMT modules for Gridding of Data Tables. """ import xarray as xr from pygmt.clib import Session diff --git a/pygmt/gridops.py b/pygmt/gridops.py index 13abb7b6449..697eccc3fe8 100644 --- a/pygmt/gridops.py +++ b/pygmt/gridops.py @@ -1,5 +1,5 @@ """ -GMT modules for grid operations +GMT modules for grid operations. """ import xarray as xr @@ -227,7 +227,6 @@ def grdfilter(grid, **kwargs): >>> # and returns a filtered data array with the smoothed field. >>> grid = pygmt.datasets.load_earth_relief() >>> smooth_field = pygmt.grdfilter(grid=grid, filter="g600", distance="4") - """ kind = data_kind(grid) diff --git a/pygmt/helpers/decorators.py b/pygmt/helpers/decorators.py index b74bc277d9d..f40800d367a 100644 --- a/pygmt/helpers/decorators.py +++ b/pygmt/helpers/decorators.py @@ -184,7 +184,6 @@ def fmt_docstring(module_func): - J = projection - R = region - """ filler_text = {} @@ -356,7 +355,6 @@ def kwargs_to_strings(convert_bools=True, **conversions): ... ] ... ) {'R': '2005-01-01T08:00:00.000000000/2015-01-01T12:00:00.123456'} - """ valid_conversions = [ "sequence", @@ -380,11 +378,15 @@ def kwargs_to_strings(convert_bools=True, **conversions): # Make the actual decorator function def converter(module_func): - "The decorator that creates our new function with the conversions" + """ + The decorator that creates our new function with the conversions. + """ @functools.wraps(module_func) def new_module(*args, **kwargs): - "New module instance that converts the arguments first" + """ + New module instance that converts the arguments first. + """ if convert_bools: kwargs = remove_bools(kwargs) for arg, fmt in conversions.items(): @@ -429,7 +431,6 @@ def remove_bools(kwargs): ------- new_kwargs : dict A copy of `kwargs` with the booleans parsed. - """ new_kwargs = {} for arg, value in kwargs.items(): diff --git a/pygmt/helpers/tempfile.py b/pygmt/helpers/tempfile.py index e5fecd4db78..6b14d769015 100644 --- a/pygmt/helpers/tempfile.py +++ b/pygmt/helpers/tempfile.py @@ -19,7 +19,6 @@ def unique_name(): ------- name : str A unique name generated by :func:`uuid.uuid4` - """ return uuid.uuid4().hex @@ -103,6 +102,5 @@ def loadtxt(self, **kwargs): ------- ndarray Data read from the text file. - """ return np.loadtxt(self.name, **kwargs) diff --git a/pygmt/helpers/utils.py b/pygmt/helpers/utils.py index 83625c08257..920579fd1d8 100644 --- a/pygmt/helpers/utils.py +++ b/pygmt/helpers/utils.py @@ -54,7 +54,6 @@ def data_kind(data, x=None, y=None, z=None): 'file' >>> data_kind(data=xr.DataArray(np.random.rand(4, 3))) 'grid' - """ if data is None and x is None and y is None: raise GMTInvalidInput("No input data provided.") @@ -97,7 +96,6 @@ def dummy_context(arg): ... print(temp) ... some argument - """ yield arg @@ -144,7 +142,6 @@ def build_arg_string(kwargs): ... ) ... ) -Bxaf -Byaf -BWSen -I1/1p,blue -I2/0.25p,blue -JX4i -R1/2/3/4 - """ sorted_args = [] for key in sorted(kwargs): @@ -190,7 +187,6 @@ def is_nonstr_iter(value): True >>> is_nonstr_iter(np.array(["abc", "def", "ghi"])) True - """ return isinstance(value, Iterable) and not isinstance(value, str) @@ -206,7 +202,6 @@ def launch_external_viewer(fname): ---------- fname : str The file name of the file (preferably a full path). - """ # Redirect stdout and stderr to devnull so that the terminal isn't filled # with noise diff --git a/pygmt/mathops.py b/pygmt/mathops.py index 4730c855d1d..bc8c2c21012 100644 --- a/pygmt/mathops.py +++ b/pygmt/mathops.py @@ -1,5 +1,5 @@ """ -GMT modules for Mathematical operations on tables or grids +GMT modules for Mathematical operations on tables or grids. """ from pygmt.clib import Session from pygmt.exceptions import GMTInvalidInput diff --git a/pygmt/modules.py b/pygmt/modules.py index 6946459697f..2c591b6a0f4 100644 --- a/pygmt/modules.py +++ b/pygmt/modules.py @@ -36,7 +36,6 @@ def grdinfo(grid, **kwargs): ------- info : str A string with information about the grid. - """ kind = data_kind(grid, None, None) with GMTTempFile() as outfile: @@ -180,7 +179,6 @@ def which(fname, **kwargs): ------ FileNotFoundError If the file is not found. - """ with GMTTempFile() as tmpfile: arg_str = " ".join([fname, build_arg_string(kwargs), "->" + tmpfile.name]) diff --git a/pygmt/sampling.py b/pygmt/sampling.py index 1fd92bfa0c4..d2f6f6e2fd7 100644 --- a/pygmt/sampling.py +++ b/pygmt/sampling.py @@ -1,5 +1,5 @@ """ -GMT modules for Sampling of 1-D and 2-D Data +GMT modules for Sampling of 1-D and 2-D Data. """ import pandas as pd from pygmt.clib import Session @@ -66,7 +66,6 @@ def grdtrack(points, grid, newcolname=None, outfile=None, **kwargs): - pandas.DataFrame table with (x, y, ..., newcolname) if outfile is not set - None if outfile is set (track output will be stored in outfile) - """ with GMTTempFile(suffix=".csv") as tmpfile: diff --git a/pygmt/tests/test_accessor.py b/pygmt/tests/test_accessor.py index 31f18558eca..32fa3e4001b 100644 --- a/pygmt/tests/test_accessor.py +++ b/pygmt/tests/test_accessor.py @@ -1,5 +1,5 @@ """ -Test the behaviour of the GMTDataArrayAccessor class +Test the behaviour of the GMTDataArrayAccessor class. """ import pytest import xarray as xr @@ -56,7 +56,8 @@ def test_accessor_set_geographic_cartesian_roundtrip(): def test_accessor_set_non_boolean(): """ - Check that setting non boolean values on registration and gtype do not work + Check that setting non boolean values on registration and gtype do not + work. """ grid = xr.DataArray(data=[[0.1, 0.2], [0.3, 0.4]]) diff --git a/pygmt/tests/test_basemap.py b/pygmt/tests/test_basemap.py index 98c8b410ad4..316d6b7aa33 100644 --- a/pygmt/tests/test_basemap.py +++ b/pygmt/tests/test_basemap.py @@ -8,7 +8,9 @@ def test_basemap_required_args(): - "fig.basemap fails when not given required arguments" + """ + fig.basemap fails when not given required arguments. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.basemap(R="10/70/-3/8", J="X4i/3i") @@ -16,7 +18,9 @@ def test_basemap_required_args(): @pytest.mark.mpl_image_compare def test_basemap(): - "Create a simple basemap plot" + """ + Create a simple basemap plot. + """ fig = Figure() fig.basemap(R="10/70/-3/8", J="X4i/3i", B="afg") return fig @@ -24,7 +28,9 @@ def test_basemap(): @pytest.mark.mpl_image_compare def test_basemap_list_region(): - "Create a simple basemap plot passing the region as a list" + """ + Create a simple basemap plot passing the region as a list. + """ fig = Figure() fig.basemap(R=[-20, 50, 200, 500], J="X3i/3i", B="a") return fig @@ -32,7 +38,9 @@ def test_basemap_list_region(): @pytest.mark.mpl_image_compare def test_basemap_loglog(): - "Create a loglog basemap plot" + """ + Create a loglog basemap plot. + """ fig = Figure() fig.basemap( R="1/10000/1e20/1e25", @@ -46,7 +54,9 @@ def test_basemap_loglog(): @pytest.mark.mpl_image_compare def test_basemap_power_axis(): - "Create a power axis basemap plot" + """ + Create a power axis basemap plot. + """ fig = Figure() fig.basemap( R=[0, 100, 0, 5000], J="x1p0.5/-0.001", B=['x1p+l"Crustal age"', "y500+lDepth"] @@ -56,7 +66,9 @@ def test_basemap_power_axis(): @check_figures_equal() def test_basemap_polar(): - "Create a polar basemap plot" + """ + Create a polar basemap plot. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.basemap(R="0/360/0/1000", J="P6i", B="afg") @@ -67,7 +79,9 @@ def test_basemap_polar(): @pytest.mark.mpl_image_compare def test_basemap_winkel_tripel(): - "Create a Winkel Tripel basemap plot" + """ + Create a Winkel Tripel basemap plot. + """ fig = Figure() fig.basemap(R="90/450/-90/90", J="R270/25c", B="afg") return fig @@ -75,7 +89,9 @@ def test_basemap_winkel_tripel(): @pytest.mark.mpl_image_compare def test_basemap_aliases(): - "Make sure the argument aliases work" + """ + Make sure the argument aliases work. + """ fig = Figure() fig.basemap(region=[0, 360, -90, 90], projection="W7i", frame=True) return fig @@ -83,7 +99,9 @@ def test_basemap_aliases(): @check_figures_equal() def test_basemap_rose(): - "Create a map with coast and use basemap to add a rose" + """ + Create a map with coast and use basemap to add a rose. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.coast(R="127.5/128.5/26/27", W="1/0.5p") fig_ref.basemap(Td="jBR+w5c") @@ -94,7 +112,9 @@ def test_basemap_rose(): @check_figures_equal() def test_basemap_compass(): - "Create a map with coast and use basemap to add a compass" + """ + Create a map with coast and use basemap to add a compass. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.coast(R="127.5/128.5/26/27", W="1/0.5p") fig_ref.basemap(Tm="jBR+w5c+d11.5") @@ -105,7 +125,9 @@ def test_basemap_compass(): @check_figures_equal() def test_basemap_map_scale(): - "Create a map with coast and use basemap to add a map scale" + """ + Create a map with coast and use basemap to add a map scale. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.coast(R="127.5/128.5/26/27", W="1/0.5p") fig_ref.basemap(L="jMB+c1+w10k+l+f") diff --git a/pygmt/tests/test_blockmedian.py b/pygmt/tests/test_blockmedian.py index 61e7661bb14..ff0dd1cf059 100644 --- a/pygmt/tests/test_blockmedian.py +++ b/pygmt/tests/test_blockmedian.py @@ -1,5 +1,5 @@ """ -Tests for blockmedian +Tests for blockmedian. """ import os @@ -14,7 +14,7 @@ def test_blockmedian_input_dataframe(): """ - Run blockmedian by passing in a pandas.DataFrame as input + Run blockmedian by passing in a pandas.DataFrame as input. """ dataframe = load_sample_bathymetry() output = blockmedian(table=dataframe, spacing="5m", region=[245, 255, 20, 30]) @@ -29,7 +29,7 @@ def test_blockmedian_input_dataframe(): def test_blockmedian_wrong_kind_of_input_table_matrix(): """ Run blockmedian using table input that is not a pandas.DataFrame but still - a matrix + a matrix. """ dataframe = load_sample_bathymetry() invalid_table = dataframe.values @@ -41,7 +41,7 @@ def test_blockmedian_wrong_kind_of_input_table_matrix(): def test_blockmedian_wrong_kind_of_input_table_grid(): """ Run blockmedian using table input that is not a pandas.DataFrame or file - but a grid + but a grid. """ dataframe = load_sample_bathymetry() invalid_table = dataframe.bathymetry.to_xarray() @@ -52,7 +52,7 @@ def test_blockmedian_wrong_kind_of_input_table_grid(): def test_blockmedian_input_filename(): """ - Run blockmedian by passing in an ASCII text file as input + Run blockmedian by passing in an ASCII text file as input. """ with GMTTempFile() as tmpfile: output = blockmedian( @@ -72,7 +72,7 @@ def test_blockmedian_input_filename(): def test_blockmedian_without_outfile_setting(): """ - Run blockmedian by not passing in outfile parameter setting + Run blockmedian by not passing in outfile parameter setting. """ with pytest.raises(GMTInvalidInput): blockmedian(table="@tut_ship.xyz", spacing="5m", region=[245, 255, 20, 30]) diff --git a/pygmt/tests/test_clib.py b/pygmt/tests/test_clib.py index d53833704c0..0ee33e1961f 100644 --- a/pygmt/tests/test_clib.py +++ b/pygmt/tests/test_clib.py @@ -68,7 +68,9 @@ def mock_get_libgmt_func(name, argtypes=None, restype=None): def test_getitem(): - "Test that I can get correct constants from the C lib" + """ + Test that I can get correct constants from the C lib. + """ ses = clib.Session() assert ses["GMT_SESSION_EXTERNAL"] != -99999 assert ses["GMT_MODULE_CMD"] != -99999 @@ -79,7 +81,9 @@ def test_getitem(): def test_create_destroy_session(): - "Test that create and destroy session are called without errors" + """ + Test that create and destroy session are called without errors. + """ # Create two session and make sure they are not pointing to the same memory session1 = clib.Session() session1.create(name="test_session1") @@ -103,7 +107,9 @@ def test_create_destroy_session(): def test_create_session_fails(): - "Check that an exception is raised when failing to create a session" + """ + Check that an exception is raised when failing to create a session. + """ ses = clib.Session() with mock(ses, "GMT_Create_Session", returns=None): with pytest.raises(GMTCLibError): @@ -115,7 +121,9 @@ def test_create_session_fails(): def test_destroy_session_fails(): - "Fail to destroy session when given bad input" + """ + Fail to destroy session when given bad input. + """ ses = clib.Session() with pytest.raises(GMTCLibNoSessionError): ses.destroy() @@ -127,7 +135,9 @@ def test_destroy_session_fails(): def test_call_module(): - "Run a command to see if call_module works" + """ + 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: @@ -139,21 +149,27 @@ def test_call_module(): def test_call_module_invalid_arguments(): - "Fails for invalid module arguments" + """ + Fails for invalid module arguments. + """ with clib.Session() as lib: with pytest.raises(GMTCLibError): lib.call_module("info", "bogus-data.bla") def test_call_module_invalid_name(): - "Fails when given bad input" + """ + Fails when given bad input. + """ with clib.Session() as lib: with pytest.raises(GMTCLibError): lib.call_module("meh", "") def test_call_module_error_message(): - "Check is the GMT error message was captured." + """ + Check is the GMT error message was captured. + """ with clib.Session() as lib: try: lib.call_module("info", "bogus-data.bla") @@ -163,7 +179,9 @@ def test_call_module_error_message(): def test_method_no_session(): - "Fails when not in a session" + """ + Fails when not in a session. + """ # Create an instance of Session without "with" so no session is created. lib = clib.Session() with pytest.raises(GMTCLibNoSessionError): @@ -173,7 +191,9 @@ def test_method_no_session(): def test_parse_constant_single(): - "Parsing a single family argument correctly." + """ + Parsing a single family argument correctly. + """ lib = clib.Session() for family in FAMILIES: parsed = lib._parse_constant(family, valid=FAMILIES) @@ -181,7 +201,9 @@ def test_parse_constant_single(): def test_parse_constant_composite(): - "Parsing a composite constant argument (separated by |) correctly." + """ + Parsing a composite constant argument (separated by |) correctly. + """ lib = clib.Session() test_cases = ((family, via) for family in FAMILIES for via in VIAS) for family, via in test_cases: @@ -192,7 +214,9 @@ def test_parse_constant_composite(): def test_parse_constant_fails(): - "Check if the function fails when given bad input" + """ + Check if the function fails when given bad input. + """ lib = clib.Session() test_cases = [ "SOME_random_STRING", @@ -218,7 +242,9 @@ def test_parse_constant_fails(): def test_create_data_dataset(): - "Run the function to make sure it doesn't fail badly." + """ + Run the function to make sure it doesn't fail badly. + """ with clib.Session() as lib: # Dataset from vectors data_vector = lib.create_data( @@ -238,7 +264,9 @@ def test_create_data_dataset(): def test_create_data_grid_dim(): - "Create a grid ignoring range and inc." + """ + Create a grid ignoring range and inc. + """ with clib.Session() as lib: # Grids from matrices using dim lib.create_data( @@ -250,7 +278,9 @@ def test_create_data_grid_dim(): def test_create_data_grid_range(): - "Create a grid specifying range and inc instead of dim." + """ + Create a grid specifying range and inc instead of dim. + """ with clib.Session() as lib: # Grids from matrices using range and int lib.create_data( @@ -263,7 +293,9 @@ def test_create_data_grid_range(): def test_create_data_fails(): - "Check that create_data raises exceptions for invalid input and output" + """ + Check that create_data raises exceptions for invalid input and output. + """ # Passing in invalid mode with pytest.raises(GMTInvalidInput): with clib.Session() as lib: @@ -300,7 +332,9 @@ def test_create_data_fails(): def test_virtual_file(): - "Test passing in data via a virtual file with a Dataset" + """ + Test passing in data via a virtual file with a Dataset. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() shape = (5, 3) for dtype in dtypes: @@ -330,8 +364,8 @@ def test_virtual_file(): def test_virtual_file_fails(): """ - Check that opening and closing virtual files raises an exception for - non-zero return codes + Check that opening and closing virtual files raises an exception for non- + zero return codes. """ vfargs = ( "GMT_IS_DATASET|GMT_VIA_MATRIX", @@ -361,7 +395,9 @@ def test_virtual_file_fails(): def test_virtual_file_bad_direction(): - "Test passing an invalid direction argument" + """ + Test passing an invalid direction argument. + """ with clib.Session() as lib: vfargs = ( "GMT_IS_DATASET|GMT_VIA_MATRIX", @@ -375,7 +411,9 @@ def test_virtual_file_bad_direction(): def test_virtualfile_from_vectors(): - "Test the automation for transforming vectors to virtual file dataset" + """ + Test the automation for transforming vectors to virtual file dataset. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() size = 10 for dtype in dtypes: @@ -398,7 +436,7 @@ def test_virtualfile_from_vectors(): def test_virtualfile_from_vectors_one_string_or_object_column(dtype): """ Test passing in one column with string or object dtype into virtual file - dataset + dataset. """ size = 5 x = np.arange(size, dtype=np.int32) @@ -417,7 +455,7 @@ def test_virtualfile_from_vectors_one_string_or_object_column(dtype): def test_virtualfile_from_vectors_two_string_or_object_columns(dtype): """ Test passing in two columns of string or object dtype into virtual file - dataset + dataset. """ size = 5 x = np.arange(size, dtype=np.int32) @@ -436,7 +474,9 @@ def test_virtualfile_from_vectors_two_string_or_object_columns(dtype): def test_virtualfile_from_vectors_transpose(): - "Test transforming matrix columns to virtual file dataset" + """ + Test transforming matrix columns to virtual file dataset. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() shape = (7, 5) for dtype in dtypes: @@ -454,7 +494,9 @@ def test_virtualfile_from_vectors_transpose(): def test_virtualfile_from_vectors_diff_size(): - "Test the function fails for arrays of different sizes" + """ + Test the function fails for arrays of different sizes. + """ x = np.arange(5) y = np.arange(6) with clib.Session() as lib: @@ -464,7 +506,9 @@ def test_virtualfile_from_vectors_diff_size(): def test_virtualfile_from_matrix(): - "Test transforming a matrix to virtual file dataset" + """ + Test transforming a matrix to virtual file dataset. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() shape = (7, 5) for dtype in dtypes: @@ -482,7 +526,9 @@ def test_virtualfile_from_matrix(): def test_virtualfile_from_matrix_slice(): - "Test transforming a slice of a larger array to virtual file dataset" + """ + Test transforming a slice of a larger array to virtual file dataset. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() shape = (10, 6) for dtype in dtypes: @@ -503,7 +549,9 @@ def test_virtualfile_from_matrix_slice(): def test_virtualfile_from_vectors_pandas(): - "Pass vectors to a dataset using pandas Series" + """ + Pass vectors to a dataset using pandas Series. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() size = 13 for dtype in dtypes: @@ -530,7 +578,9 @@ def test_virtualfile_from_vectors_pandas(): def test_virtualfile_from_vectors_arraylike(): - "Pass array-like vectors to a dataset" + """ + Pass array-like vectors to a dataset. + """ size = 13 x = list(range(0, size, 1)) y = tuple(range(size, size * 2, 1)) @@ -548,7 +598,9 @@ def test_virtualfile_from_vectors_arraylike(): def test_extract_region_fails(): - "Check that extract region fails if nothing has been plotted." + """ + Check that extract region fails if nothing has been plotted. + """ Figure() with pytest.raises(GMTCLibError): with clib.Session() as lib: @@ -556,7 +608,9 @@ def test_extract_region_fails(): def test_extract_region_two_figures(): - "Extract region should handle multiple figures existing at the same time" + """ + Extract region should handle multiple figures existing at the same time. + """ # Make two figures before calling extract_region to make sure that it's # getting from the current figure, not the last figure. fig1 = Figure() @@ -583,7 +637,9 @@ def test_extract_region_two_figures(): def test_write_data_fails(): - "Check that write data raises an exception for non-zero return codes" + """ + Check that write data raises an exception for non-zero return codes. + """ # It's hard to make the C API function fail without causing a Segmentation # Fault. Can't test this if by giving a bad file name because if # output=='', GMT will just write to stdout and spaces are valid file @@ -602,7 +658,9 @@ def test_write_data_fails(): def test_dataarray_to_matrix_works(): - "Check that dataarray_to_matrix returns correct output" + """ + Check that dataarray_to_matrix returns correct output. + """ data = np.diag(v=np.arange(3)) x = np.linspace(start=0, stop=4, num=3) y = np.linspace(start=5, stop=9, num=3) @@ -615,7 +673,9 @@ def test_dataarray_to_matrix_works(): def test_dataarray_to_matrix_negative_x_increment(): - "Check if dataarray_to_matrix returns correct output with flipped x" + """ + Check if dataarray_to_matrix returns correct output with flipped x. + """ data = np.diag(v=np.arange(3)) x = np.linspace(start=4, stop=0, num=3) y = np.linspace(start=5, stop=9, num=3) @@ -628,7 +688,9 @@ def test_dataarray_to_matrix_negative_x_increment(): def test_dataarray_to_matrix_negative_y_increment(): - "Check that dataarray_to_matrix returns correct output with flipped y" + """ + Check that dataarray_to_matrix returns correct output with flipped y. + """ data = np.diag(v=np.arange(3)) x = np.linspace(start=0, stop=4, num=3) y = np.linspace(start=9, stop=5, num=3) @@ -641,7 +703,9 @@ def test_dataarray_to_matrix_negative_y_increment(): def test_dataarray_to_matrix_negative_x_and_y_increment(): - "Check that dataarray_to_matrix returns correct output with flipped x/y" + """ + Check that dataarray_to_matrix returns correct output with flipped x/y. + """ data = np.diag(v=np.arange(3)) x = np.linspace(start=4, stop=0, num=3) y = np.linspace(start=9, stop=5, num=3) @@ -654,7 +718,9 @@ def test_dataarray_to_matrix_negative_x_and_y_increment(): def test_dataarray_to_matrix_dims_fails(): - "Check that it fails for > 2 dims" + """ + Check that it fails for > 2 dims. + """ # Make a 3D regular grid data = np.ones((10, 12, 11), dtype="float32") x = np.arange(11) @@ -666,7 +732,9 @@ def test_dataarray_to_matrix_dims_fails(): def test_dataarray_to_matrix_inc_fails(): - "Check that it fails for variable increments" + """ + Check that it fails for variable increments. + """ data = np.ones((4, 5), dtype="float64") x = np.linspace(0, 1, 5) y = np.logspace(2, 3, 4) @@ -676,7 +744,9 @@ def test_dataarray_to_matrix_inc_fails(): def test_get_default(): - "Make sure get_default works without crashing and gives reasonable results" + """ + Make sure get_default works without crashing and gives reasonable results. + """ with clib.Session() as lib: assert lib.get_default("API_GRID_LAYOUT") in ["rows", "columns"] assert int(lib.get_default("API_CORES")) >= 1 @@ -684,14 +754,18 @@ def test_get_default(): def test_get_default_fails(): - "Make sure get_default raises an exception for invalid names" + """ + Make sure get_default raises an exception for invalid names. + """ with clib.Session() as lib: with pytest.raises(GMTCLibError): lib.get_default("NOT_A_VALID_NAME") def test_info_dict(): - "Make sure the clib.Session.info dict is working." + """ + Make sure the clib.Session.info dict is working. + """ # Check if there are no errors or segfaults from getting all of the # properties. with clib.Session() as lib: @@ -699,7 +773,9 @@ def test_info_dict(): # Mock GMT_Get_Default to return always the same string def mock_defaults(api, name, value): # pylint: disable=unused-argument - "Put 'bla' in the value buffer" + """ + Put 'bla' in the value buffer. + """ value.value = b"bla" return 0 @@ -714,11 +790,15 @@ def mock_defaults(api, name, value): # pylint: disable=unused-argument def test_fails_for_wrong_version(): - "Make sure the clib.Session raises an exception if GMT is too old" + """ + Make sure the clib.Session raises an exception if GMT is too old. + """ # Mock GMT_Get_Default to return an old version def mock_defaults(api, name, value): # pylint: disable=unused-argument - "Return an old version" + """ + Return an old version. + """ if name == b"API_VERSION": value.value = b"5.4.3" else: diff --git a/pygmt/tests/test_clib_loading.py b/pygmt/tests/test_clib_loading.py index 67b3452443d..54fb89b3f5f 100644 --- a/pygmt/tests/test_clib_loading.py +++ b/pygmt/tests/test_clib_loading.py @@ -1,5 +1,5 @@ """ -Test the functions that load libgmt +Test the functions that load libgmt. """ import os @@ -9,18 +9,24 @@ def test_check_libgmt(): - "Make sure check_libgmt fails when given a bogus library" + """ + Make sure check_libgmt fails when given a bogus library. + """ with pytest.raises(GMTCLibError): check_libgmt(dict()) def test_load_libgmt(): - "Test that loading libgmt works and doesn't crash." + """ + Test that loading libgmt works and doesn't crash. + """ check_libgmt(load_libgmt()) def test_load_libgmt_fail(): - "Test that loading fails when given a bad library path." + """ + Test that loading fails when given a bad library path. + """ # save the old value (if any) before setting a fake "GMT_LIBRARY_PATH" old_gmt_library_path = os.environ.get("GMT_LIBRARY_PATH") @@ -36,7 +42,9 @@ def test_load_libgmt_fail(): def test_clib_names(): - "Make sure we get the correct library name for different OS names" + """ + Make sure we get the correct library name for different OS names. + """ for linux in ["linux", "linux2", "linux3"]: assert clib_names(linux) == ["libgmt.so"] assert clib_names("darwin") == ["libgmt.dylib"] diff --git a/pygmt/tests/test_clib_put_matrix.py b/pygmt/tests/test_clib_put_matrix.py index 31371e6ed1d..46e9ebd9d5c 100644 --- a/pygmt/tests/test_clib_put_matrix.py +++ b/pygmt/tests/test_clib_put_matrix.py @@ -12,7 +12,9 @@ def test_put_matrix(): - "Check that assigning a numpy 2d array to a dataset works" + """ + Check that assigning a numpy 2d array to a dataset works. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() shape = (3, 4) for dtype in dtypes: @@ -43,7 +45,9 @@ def test_put_matrix(): def test_put_matrix_fails(): - "Check that put_matrix raises an exception if return code is not zero" + """ + Check that put_matrix raises an exception if return code is not zero. + """ # It's hard to make put_matrix fail on the C API level because of all the # checks on input arguments. Mock the C API function just to make sure it # works. @@ -54,7 +58,9 @@ def test_put_matrix_fails(): def test_put_matrix_grid(): - "Check that assigning a numpy 2d array to an ASCII and NetCDF grid works" + """ + Check that assigning a numpy 2d array to an ASCII and NetCDF grid works. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() wesn = [10, 15, 30, 40, 0, 0] inc = [1, 1] diff --git a/pygmt/tests/test_clib_put_strings.py b/pygmt/tests/test_clib_put_strings.py index a2509b18e9d..9c9ba871429 100644 --- a/pygmt/tests/test_clib_put_strings.py +++ b/pygmt/tests/test_clib_put_strings.py @@ -14,7 +14,9 @@ def test_put_strings(): - "Check that assigning a numpy array of dtype str to a dataset works" + """ + Check that assigning a numpy array of dtype str to a dataset works. + """ with clib.Session() as lib: dataset = lib.create_data( family="GMT_IS_DATASET|GMT_VIA_VECTOR", @@ -52,7 +54,9 @@ def test_put_strings(): def test_put_strings_fails(): - "Check that put_strings raises an exception if return code is not zero" + """ + Check that put_strings raises an exception if return code is not zero. + """ with clib.Session() as lib: with pytest.raises(GMTCLibError): lib.put_strings( diff --git a/pygmt/tests/test_clib_put_vector.py b/pygmt/tests/test_clib_put_vector.py index 8e526b3fc9b..72a4c858898 100644 --- a/pygmt/tests/test_clib_put_vector.py +++ b/pygmt/tests/test_clib_put_vector.py @@ -12,7 +12,9 @@ def test_put_vector(): - "Check that assigning a numpy array to a dataset works" + """ + Check that assigning a numpy array to a dataset works. + """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() for dtype in dtypes: with clib.Session() as lib: @@ -48,7 +50,9 @@ def test_put_vector(): def test_put_vector_mixed_dtypes(): - """Passing a numpy array of mixed dtypes to a dataset. + """ + Passing a numpy array of mixed dtypes to a dataset. + See https://github.com/GenericMappingTools/pygmt/issues/255 """ dtypes = "float32 float64 int32 int64 uint32 uint64".split() @@ -87,7 +91,9 @@ def test_put_vector_mixed_dtypes(): def test_put_vector_invalid_dtype(): - "Check that it fails with an exception for invalid data types" + """ + Check that it fails with an exception for invalid data types. + """ with clib.Session() as lib: dataset = lib.create_data( family="GMT_IS_DATASET|GMT_VIA_VECTOR", @@ -101,7 +107,9 @@ def test_put_vector_invalid_dtype(): def test_put_vector_wrong_column(): - "Check that it fails with an exception when giving an invalid column" + """ + Check that it fails with an exception when giving an invalid column. + """ with clib.Session() as lib: dataset = lib.create_data( family="GMT_IS_DATASET|GMT_VIA_VECTOR", @@ -115,7 +123,9 @@ def test_put_vector_wrong_column(): def test_put_vector_2d_fails(): - "Check that it fails with an exception for multidimensional arrays" + """ + Check that it fails with an exception for multidimensional arrays. + """ with clib.Session() as lib: dataset = lib.create_data( family="GMT_IS_DATASET|GMT_VIA_VECTOR", diff --git a/pygmt/tests/test_coast.py b/pygmt/tests/test_coast.py index a75d5eeae93..69635aa30f6 100644 --- a/pygmt/tests/test_coast.py +++ b/pygmt/tests/test_coast.py @@ -1,5 +1,5 @@ """ -Tests for coast +Tests for coast. """ import pytest from pygmt import Figure @@ -9,7 +9,9 @@ @pytest.mark.mpl_image_compare def test_coast(): - "Simple plot from the GMT docs" + """ + Simple plot from the GMT docs. + """ fig = Figure() fig.coast( R="-30/30/-40/40", @@ -28,7 +30,9 @@ def test_coast(): @check_figures_equal() def test_coast_iceland(): - "Test passing in R as a list" + """ + Test passing in R as a list. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast(R="-30/-10/60/65", J="m1c", B="", G="p28+r100") @@ -40,7 +44,9 @@ def test_coast_iceland(): @check_figures_equal() def test_coast_aliases(): - "Test that all aliases work" + """ + Test that all aliases work. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.coast( R="-30/30/-40/40", @@ -85,7 +91,9 @@ def test_coast_aliases(): @pytest.mark.mpl_image_compare def test_coast_world_mercator(): - "Test passing generating a global Mercator map with coastlines" + """ + Test passing generating a global Mercator map with coastlines. + """ fig = Figure() fig.coast( region=[-180, 180, -80, 80], @@ -99,7 +107,9 @@ def test_coast_world_mercator(): def test_coast_required_args(): - "Test if fig.coast fails when not given required arguments" + """ + Test if fig.coast fails when not given required arguments. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.coast(region="EG") @@ -107,7 +117,9 @@ def test_coast_required_args(): @check_figures_equal() def test_coast_dcw_single(): - "Test passing a single country code to dcw" + """ + Test passing a single country code to dcw. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast(R="-10/15/25/44", J="M15c", B="a", G="brown", E="ES+gbisque+pblue") @@ -123,7 +135,9 @@ def test_coast_dcw_single(): @check_figures_equal() def test_coast_dcw_multiple(): - "Test passing multiple country code to dcw" + """ + Test passing multiple country code to dcw. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast(R="-10/15/25/44", J="M15c", B="a", G="brown", E="ES,IT+gbisque+pblue") @@ -139,7 +153,9 @@ def test_coast_dcw_multiple(): @check_figures_equal() def test_coast_dcw_list(): - "Test passing a list of country codes and fill options to dcw" + """ + Test passing a list of country codes and fill options to dcw. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast( @@ -161,7 +177,9 @@ def test_coast_dcw_list(): @check_figures_equal() def test_coast_dcw_continent(): - "Test passing a continent code to dcw" + """ + Test passing a continent code to dcw. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast(R="-10/15/25/44", J="M15c", B="a", G="brown", E="=AF+gbisque+pblue") @@ -177,7 +195,9 @@ def test_coast_dcw_continent(): @check_figures_equal() def test_coast_dcw_state(): - "Test passing a US state code to dcw" + """ + Test passing a US state code to dcw. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast( diff --git a/pygmt/tests/test_colorbar.py b/pygmt/tests/test_colorbar.py index 1ba529e8724..865df5d00e8 100644 --- a/pygmt/tests/test_colorbar.py +++ b/pygmt/tests/test_colorbar.py @@ -1,5 +1,5 @@ """ -Tests colorbar +Tests colorbar. """ import pytest from pygmt import Figure @@ -19,7 +19,8 @@ def test_colorbar_using_paper_coordinates(): @pytest.mark.mpl_image_compare def test_colorbar_using_paper_coordinates_horizontal(): """ - Create colorbar positioned at 0cm,0cm with length 2cm oriented horizontally + Create colorbar positioned at 0cm,0cm with length 2cm oriented + horizontally. """ fig = Figure() fig.colorbar(cmap="rainbow", position="x0c/0c+w2c+h") @@ -158,7 +159,7 @@ def test_colorbar_scaled_z_values(): @check_figures_equal() def test_colorbar_shading_boolean(): """ - Create colorbar and set shading with a Boolean value + Create colorbar and set shading with a Boolean value. """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image @@ -173,7 +174,7 @@ def test_colorbar_shading_boolean(): @check_figures_equal() def test_colorbar_shading_float(): """ - Create colorbar and set shading with a single float variable + Create colorbar and set shading with a single float variable. """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image @@ -188,7 +189,7 @@ def test_colorbar_shading_float(): @check_figures_equal() def test_colorbar_shading_string(): """ - Create colorbar and set shading by passing the low/high values as a string + Create colorbar and set shading by passing the low/high values as a string. """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image @@ -203,7 +204,7 @@ def test_colorbar_shading_string(): @check_figures_equal() def test_colorbar_shading_list(): """ - Create colorbar and set shading by passing the high/low values as a list + Create colorbar and set shading by passing the high/low values as a list. """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image diff --git a/pygmt/tests/test_config.py b/pygmt/tests/test_config.py index 9a229ce7e55..30a25c330f1 100644 --- a/pygmt/tests/test_config.py +++ b/pygmt/tests/test_config.py @@ -1,5 +1,5 @@ """ -Tests for gmt config +Tests for gmt config. """ import pytest from pygmt import Figure, config @@ -43,7 +43,9 @@ def test_config(): def test_config_font_one(): """ Test that setting `FONT` config changes all `FONT_*` settings except - `FONT_LOGO`. Specifically, this test only checks that `FONT_ANNOT_PRIMARY`, + `FONT_LOGO`. + + Specifically, this test only checks that `FONT_ANNOT_PRIMARY`, `FONT_ANNOT_SECONDARY`, `FONT_LABEL`, and `FONT_TITLE` are modified. """ fig = Figure() @@ -123,8 +125,8 @@ def test_config_map_grid_cross_size(): @pytest.mark.mpl_image_compare def test_config_map_grid_pen(): """ - Test that setting `MAP_GRID_PEN` config changes both - `MAP_GRID_PEN_PRIMARY` and `MAP_GRID_PEN_SECONDARY`. + Test that setting `MAP_GRID_PEN` config changes both `MAP_GRID_PEN_PRIMARY` + and `MAP_GRID_PEN_SECONDARY`. """ fig = Figure() with config(MAP_GRID_PEN="thick,red"): @@ -157,8 +159,8 @@ def test_config_map_tick_length(): @pytest.mark.mpl_image_compare def test_config_map_tick_pen(): """ - Test that setting `MAP_TICK_PEN` config changes both - `MAP_TICK_PEN_PRIMARY` and `MAP_TICK_PEN_SECONDARY`. + Test that setting `MAP_TICK_PEN` config changes both `MAP_TICK_PEN_PRIMARY` + and `MAP_TICK_PEN_SECONDARY`. """ fig = Figure() with config(MAP_TICK_PEN="thick,red"): diff --git a/pygmt/tests/test_contour.py b/pygmt/tests/test_contour.py index bc322349099..9fc2c2694f6 100644 --- a/pygmt/tests/test_contour.py +++ b/pygmt/tests/test_contour.py @@ -16,18 +16,24 @@ @pytest.fixture(scope="module") def data(): - "Load the point data from the test file" + """ + Load the point data from the test file. + """ return np.loadtxt(POINTS_DATA) @pytest.fixture(scope="module") def region(): - "The data region" + """ + The data region. + """ return [10, 70, -5, 10] def test_contour_fail_no_data(data): - "Should raise an exception if no data is given" + """ + Should raise an exception if no data is given. + """ # Contour should raise an exception if no or not sufficient data # is given fig = Figure() @@ -66,7 +72,9 @@ def test_contour_fail_no_data(data): @pytest.mark.mpl_image_compare def test_contour_vec(region): - "Plot an x-centered gaussian kernel with different y scale" + """ + Plot an x-centered gaussian kernel with different y scale. + """ fig = Figure() x, y = np.meshgrid( np.linspace(region[0], region[1]), np.linspace(region[2], region[3]) @@ -81,7 +89,9 @@ def test_contour_vec(region): @pytest.mark.mpl_image_compare def test_contour_matrix(data, region): - "Plot data" + """ + Plot data. + """ fig = Figure() fig.contour(data=data, projection="X3i", region=region, frame="ag", pen="") return fig @@ -89,7 +99,9 @@ def test_contour_matrix(data, region): @pytest.mark.mpl_image_compare def test_contour_from_file(region): - "Plot using the data file name instead of loaded data" + """ + Plot using the data file name instead of loaded data. + """ fig = Figure() fig.contour( data=POINTS_DATA, projection="X4i", region=region, frame="af", pen="#ffcb87" diff --git a/pygmt/tests/test_datasets.py b/pygmt/tests/test_datasets.py index 19567a14ca2..72bdcca3d20 100644 --- a/pygmt/tests/test_datasets.py +++ b/pygmt/tests/test_datasets.py @@ -15,7 +15,9 @@ def test_japan_quakes(): - "Check that the dataset loads without errors" + """ + Check that the dataset loads without errors. + """ data = load_japan_quakes() assert data.shape == (115, 7) summary = data.describe() @@ -28,7 +30,9 @@ def test_japan_quakes(): def test_ocean_ridge_points(): - "Check that the @ridge.txt dataset loads without errors" + """ + Check that the @ridge.txt dataset loads without errors. + """ data = load_ocean_ridge_points() assert data.shape == (4146, 2) summary = data.describe() @@ -39,7 +43,9 @@ def test_ocean_ridge_points(): def test_sample_bathymetry(): - "Check that the @tut_ship.xyz dataset loads without errors" + """ + Check that the @tut_ship.xyz dataset loads without errors. + """ data = load_sample_bathymetry() assert data.shape == (82970, 3) summary = data.describe() @@ -52,13 +58,17 @@ def test_sample_bathymetry(): def test_usgs_quakes(): - "Check that the dataset loads without errors" + """ + Check that the dataset loads without errors. + """ data = load_usgs_quakes() assert data.shape == (1197, 22) def test_earth_relief_fails(): - "Make sure earth relief fails for invalid resolutions" + """ + Make sure earth relief fails for invalid resolutions. + """ resolutions = "1m 1d bla 60d 001m 03".split() resolutions.append(60) for resolution in resolutions: @@ -68,7 +78,9 @@ def test_earth_relief_fails(): # Only test 01d and 30m to avoid downloading large datasets in CI def test_earth_relief_01d(): - "Test some properties of the earth relief 01d data" + """ + Test some properties of the earth relief 01d data. + """ data = load_earth_relief(resolution="01d", registration="gridline") assert data.shape == (181, 361) npt.assert_allclose(data.lat, np.arange(-90, 91, 1)) @@ -78,13 +90,17 @@ def test_earth_relief_01d(): def test_earth_relief_01d_with_region(): - "Test loading low-resolution earth relief with 'region'" + """ + Test loading low-resolution earth relief with 'region'. + """ with pytest.raises(NotImplementedError): load_earth_relief("01d", region=[0, 180, 0, 90]) def test_earth_relief_30m(): - "Test some properties of the earth relief 30m data" + """ + Test some properties of the earth relief 30m data. + """ data = load_earth_relief(resolution="30m", registration="gridline") assert data.shape == (361, 721) npt.assert_allclose(data.lat, np.arange(-90, 90.5, 0.5)) @@ -94,7 +110,9 @@ def test_earth_relief_30m(): def test_earth_relief_05m_with_region(): - "Test loading a subregion of high-resolution earth relief grid" + """ + Test loading a subregion of high-resolution earth relief grid. + """ data = load_earth_relief( resolution="05m", region=[120, 160, 30, 60], registration="gridline" ) @@ -109,12 +127,16 @@ def test_earth_relief_05m_with_region(): def test_earth_relief_05m_without_region(): - "Test loading high-resolution earth relief without passing 'region'" + """ + Test loading high-resolution earth relief without passing 'region'. + """ with pytest.raises(GMTInvalidInput): load_earth_relief("05m") def test_earth_relief_incorrect_registration(): - "Test loading earth relief with incorrect registration type" + """ + Test loading earth relief with incorrect registration type. + """ with pytest.raises(GMTInvalidInput): load_earth_relief(registration="improper_type") diff --git a/pygmt/tests/test_figure.py b/pygmt/tests/test_figure.py index 0935fd68569..f4ef5e02ee6 100644 --- a/pygmt/tests/test_figure.py +++ b/pygmt/tests/test_figure.py @@ -1,6 +1,7 @@ """ -Test the behaviors of the Figure class -Doesn't include the plotting commands, which have their own test files. +Test the behavior of the Figure class. + +Doesn't include the plotting commands which have their own test files. """ import os @@ -12,7 +13,9 @@ def test_figure_region(): - "Extract the plot region for the figure" + """ + Extract the plot region for the figure. + """ region = [0, 1, 2, 3] fig = Figure() fig.basemap(region=region, projection="X1id/1id", frame=True) @@ -20,7 +23,9 @@ def test_figure_region(): def test_figure_region_multiple(): - "Make sure the region argument is for the current figure" + """ + Make sure the region argument is for the current figure. + """ region1 = [-10, 2, 0.355, 67] fig1 = Figure() fig1.basemap(region=region1, projection="X1id/1id", frame=True) @@ -33,7 +38,9 @@ def test_figure_region_multiple(): def test_figure_region_country_codes(): - "Extract the plot region for the figure using country codes" + """ + Extract the plot region for the figure using country codes. + """ fig = Figure() fig.basemap(region="JP", projection="M3i", frame=True) npt.assert_allclose( @@ -45,7 +52,9 @@ def test_figure_region_country_codes(): def test_figure_savefig_exists(): - "Make sure the saved figure has the right name" + """ + Make sure the saved figure has the right name. + """ fig = Figure() fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af") prefix = "test_figure_savefig_exists" @@ -57,7 +66,9 @@ def test_figure_savefig_exists(): def test_figure_savefig_transparent(): - "Check if fails when transparency is not supported" + """ + Check if fails when transparency is not supported. + """ fig = Figure() fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af") prefix = "test_figure_savefig_transparent" @@ -73,11 +84,15 @@ def test_figure_savefig_transparent(): def test_figure_savefig(): - "Check if the arguments being passed to psconvert are correct" + """ + Check if the arguments being passed to psconvert are correct. + """ kwargs_saved = [] def mock_psconvert(*args, **kwargs): # pylint: disable=unused-argument - "Just record the arguments" + """ + Just record the arguments. + """ kwargs_saved.append(kwargs) fig = Figure() @@ -109,7 +124,9 @@ def mock_psconvert(*args, **kwargs): # pylint: disable=unused-argument def test_figure_show(): - "Test that show creates the correct file name and deletes the temp dir" + """ + Test that show creates the correct file name and deletes the temp dir. + """ fig = Figure() fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af") img = fig.show(width=800) @@ -118,7 +135,9 @@ def test_figure_show(): @pytest.mark.mpl_image_compare def test_shift_origin(): - "Test if fig.shift_origin works" + """ + Test if fig.shift_origin works. + """ fig = Figure() # First call shift_origin without projection and region. # Test the issue https://github.com/GenericMappingTools/pygmt/issues/514 diff --git a/pygmt/tests/test_grdcontour.py b/pygmt/tests/test_grdcontour.py index 864c8d9887b..b208be55d6e 100644 --- a/pygmt/tests/test_grdcontour.py +++ b/pygmt/tests/test_grdcontour.py @@ -1,5 +1,5 @@ """ -Test Figure.grdcontour +Test Figure.grdcontour. """ import os @@ -16,14 +16,16 @@ @pytest.fixture(scope="module", name="grid") def fixture_grid(): - "Load the grid data from the sample earth_relief file" + """ + Load the grid data from the sample earth_relief file. + """ return load_earth_relief(registration="gridline") @check_figures_equal() def test_grdcontour(grid): - """Plot a contour image using an xarray grid - with fixed contour interval + """ + Plot a contour image using an xarray grid with fixed contour interval. """ fig_ref, fig_test = Figure(), Figure() kwargs = dict(interval="1000", projection="W0/6i") @@ -34,8 +36,9 @@ def test_grdcontour(grid): @check_figures_equal() def test_grdcontour_labels(grid): - """Plot a contour image using a xarray grid - with contour labels and alternate colors + """ + Plot a contour image using a xarray grid with contour labels and alternate + colors. """ fig_ref, fig_test = Figure(), Figure() kwargs = dict( @@ -52,7 +55,9 @@ def test_grdcontour_labels(grid): @check_figures_equal() def test_grdcontour_slice(grid): - "Plot an contour image using an xarray grid that has been sliced" + """ + Plot an contour image using an xarray grid that has been sliced. + """ fig_ref, fig_test = Figure(), Figure() @@ -67,7 +72,9 @@ def test_grdcontour_slice(grid): @pytest.mark.mpl_image_compare def test_grdcontour_file(): - "Plot a contour image using grid file input" + """ + Plot a contour image using grid file input. + """ fig = Figure() fig.grdcontour( "@earth_relief_01d_g", @@ -82,7 +89,9 @@ def test_grdcontour_file(): @check_figures_equal() def test_grdcontour_interval_file_full_opts(): - """ Plot based on external contour level file """ + """ + Plot based on external contour level file. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image comargs_ref = { @@ -113,7 +122,9 @@ def test_grdcontour_interval_file_full_opts(): def test_grdcontour_fails(): - "Should fail for unrecognized input" + """ + Should fail for unrecognized input. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.grdcontour(np.arange(20).reshape((4, 5))) diff --git a/pygmt/tests/test_grdcut.py b/pygmt/tests/test_grdcut.py index 6543734ce2e..d3e5d5fbc00 100644 --- a/pygmt/tests/test_grdcut.py +++ b/pygmt/tests/test_grdcut.py @@ -1,5 +1,5 @@ """ -Tests for grdcut +Tests for grdcut. """ import os @@ -14,12 +14,16 @@ @pytest.fixture(scope="module", name="grid") def fixture_grid(): - "Load the grid data from the sample earth_relief file" + """ + Load the grid data from the sample earth_relief file. + """ return load_earth_relief(registration="pixel") def test_grdcut_file_in_file_out(): - "grduct an input grid file, and output to a grid file" + """ + grdcut an input grid file, and output to a grid file. + """ with GMTTempFile(suffix=".nc") as tmpfile: result = grdcut("@earth_relief_01d", outgrid=tmpfile.name, region="0/180/0/90") assert result is None # return value is None @@ -29,7 +33,9 @@ def test_grdcut_file_in_file_out(): def test_grdcut_file_in_dataarray_out(): - "grdcut an input grid file, and output as DataArray" + """ + grdcut an input grid file, and output as DataArray. + """ outgrid = grdcut("@earth_relief_01d", region="0/180/0/90") assert isinstance(outgrid, xr.DataArray) assert outgrid.gmt.registration == 1 # Pixel registration @@ -48,7 +54,9 @@ def test_grdcut_file_in_dataarray_out(): def test_grdcut_dataarray_in_file_out(grid): - "grdcut an input DataArray, and output to a grid file" + """ + grdcut an input DataArray, and output to a grid file. + """ with GMTTempFile(suffix=".nc") as tmpfile: result = grdcut(grid, outgrid=tmpfile.name, region="0/180/0/90") assert result is None # grdcut returns None if output to a file @@ -57,7 +65,9 @@ def test_grdcut_dataarray_in_file_out(grid): def test_grdcut_dataarray_in_dataarray_out(grid): - "grdcut an input DataArray, and output as DataArray" + """ + grdcut an input DataArray, and output as DataArray. + """ outgrid = grdcut(grid, region="0/180/0/90") assert isinstance(outgrid, xr.DataArray) # check information of the output grid @@ -74,6 +84,8 @@ def test_grdcut_dataarray_in_dataarray_out(grid): def test_grdcut_fails(): - "Check that grdcut fails correctly" + """ + Check that grdcut fails correctly. + """ with pytest.raises(GMTInvalidInput): grdcut(np.arange(10).reshape((5, 2))) diff --git a/pygmt/tests/test_grdimage.py b/pygmt/tests/test_grdimage.py index 7eb99b045ba..2927c95e1d1 100644 --- a/pygmt/tests/test_grdimage.py +++ b/pygmt/tests/test_grdimage.py @@ -1,5 +1,5 @@ """ -Test Figure.grdimage +Test Figure.grdimage. """ import sys @@ -18,14 +18,16 @@ @pytest.fixture(scope="module", name="grid") def fixture_grid(): - "Load the grid data from the sample earth_relief file" + """ + Load the grid data from the sample earth_relief file. + """ return load_earth_relief(registration="gridline") @pytest.fixture(scope="module", name="xrgrid") def fixture_xrgrid(): """ - Create a sample xarray.DataArray grid for testing + Create a sample xarray.DataArray grid for testing. """ longitude = np.arange(0, 360, 1) latitude = np.arange(-89, 90, 1) @@ -45,7 +47,9 @@ def fixture_xrgrid(): @pytest.mark.mpl_image_compare def test_grdimage(grid): - "Plot an image using an xarray grid" + """ + Plot an image using an xarray grid. + """ fig = Figure() fig.grdimage(grid, cmap="earth", projection="W0/6i") return fig @@ -53,7 +57,9 @@ def test_grdimage(grid): @pytest.mark.mpl_image_compare def test_grdimage_slice(grid): - "Plot an image using an xarray grid that has been sliced" + """ + Plot an image using an xarray grid that has been sliced. + """ grid_ = grid.sel(lat=slice(-30, 30)) fig = Figure() fig.grdimage(grid_, cmap="earth", projection="M6i") @@ -62,7 +68,9 @@ def test_grdimage_slice(grid): @pytest.mark.mpl_image_compare def test_grdimage_file(): - "Plot an image using file input" + """ + Plot an image using file input. + """ fig = Figure() fig.grdimage( "@earth_relief_01d_g", @@ -112,7 +120,9 @@ def test_grdimage_shading_xarray(grid, shading): def test_grdimage_fails(): - "Should fail for unrecognized input" + """ + Should fail for unrecognized input. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.grdimage(np.arange(20).reshape((4, 5))) @@ -122,6 +132,7 @@ def test_grdimage_fails(): def test_grdimage_over_dateline(xrgrid): """ Ensure no gaps are plotted over the 180 degree international dateline. + Specifically checking that `xrgrid.gmt.gtype = 1` sets `GMT_GRID_IS_GEO`, and that `xrgrid.gmt.registration = 0` sets `GMT_GRID_NODE_REG`. Note that there would be a gap over the dateline if a pixel registered grid is used. diff --git a/pygmt/tests/test_grdinfo.py b/pygmt/tests/test_grdinfo.py index dd7c49e0125..889cb7aef92 100644 --- a/pygmt/tests/test_grdinfo.py +++ b/pygmt/tests/test_grdinfo.py @@ -1,5 +1,5 @@ """ -Tests for grdinfo +Tests for grdinfo. """ import numpy as np import pytest @@ -9,19 +9,25 @@ def test_grdinfo(): - "Make sure grd info works as expected" + """ + Make sure grd info works as expected. + """ grid = load_earth_relief(registration="gridline") result = grdinfo(grid, L=0, C="n") assert result.strip() == "-180 180 -90 90 -8592.5 5559 1 1 361 181 0 1" def test_grdinfo_file(): - "Test grdinfo with file input" + """ + Test grdinfo with file input. + """ result = grdinfo("@earth_relief_01d", L=0, C="n") assert result.strip() == "-180 180 -90 90 -8182 5651.5 1 1 360 180 1 1" def test_grdinfo_fails(): - "Check that grdinfo fails correctly" + """ + Check that grdinfo fails correctly. + """ with pytest.raises(GMTInvalidInput): grdinfo(np.arange(10).reshape((5, 2))) diff --git a/pygmt/tests/test_grdtrack.py b/pygmt/tests/test_grdtrack.py index df0b7086b02..8ed74adcd47 100644 --- a/pygmt/tests/test_grdtrack.py +++ b/pygmt/tests/test_grdtrack.py @@ -1,5 +1,5 @@ """ -Tests for grdtrack +Tests for grdtrack. """ import os @@ -17,7 +17,9 @@ @pytest.fixture(scope="module", name="dataarray") def fixture_dataarray(): - "Load the grid data from the sample earth_relief file" + """ + Load the grid data from the sample earth_relief file. + """ return load_earth_relief(registration="gridline").sel( lat=slice(-49, -42), lon=slice(-118, -107) ) @@ -27,7 +29,7 @@ def fixture_dataarray(): def test_grdtrack_input_dataframe_and_dataarray(dataarray): """ Run grdtrack by passing in a pandas.DataFrame and xarray.DataArray as - inputs + inputs. """ dataframe = load_ocean_ridge_points() @@ -42,7 +44,7 @@ def test_grdtrack_input_dataframe_and_dataarray(dataarray): @pytest.mark.xfail(reason="The reason why it fails is unclear now") def test_grdtrack_input_csvfile_and_dataarray(dataarray): """ - Run grdtrack by passing in a csvfile and xarray.DataArray as inputs + Run grdtrack by passing in a csvfile and xarray.DataArray as inputs. """ csvfile = which("@ridge.txt", download="c") @@ -61,7 +63,7 @@ def test_grdtrack_input_csvfile_and_dataarray(dataarray): def test_grdtrack_input_dataframe_and_ncfile(): """ - Run grdtrack by passing in a pandas.DataFrame and netcdf file as inputs + Run grdtrack by passing in a pandas.DataFrame and netcdf file as inputs. """ dataframe = load_ocean_ridge_points() ncfile = which("@earth_relief_01d", download="a") @@ -76,7 +78,7 @@ def test_grdtrack_input_dataframe_and_ncfile(): def test_grdtrack_input_csvfile_and_ncfile(): """ - Run grdtrack by passing in a csvfile and netcdf file as inputs + Run grdtrack by passing in a csvfile and netcdf file as inputs. """ csvfile = which("@ridge.txt", download="c") ncfile = which("@earth_relief_01d", download="a") @@ -97,7 +99,7 @@ def test_grdtrack_input_csvfile_and_ncfile(): def test_grdtrack_wrong_kind_of_points_input(dataarray): """ Run grdtrack using points input that is not a pandas.DataFrame (matrix) or - file + file. """ dataframe = load_ocean_ridge_points() invalid_points = dataframe.longitude.to_xarray() @@ -110,7 +112,7 @@ def test_grdtrack_wrong_kind_of_points_input(dataarray): def test_grdtrack_wrong_kind_of_grid_input(dataarray): """ Run grdtrack using grid input that is not as xarray.DataArray (grid) or - file + file. """ dataframe = load_ocean_ridge_points() invalid_grid = dataarray.to_dataset() @@ -122,7 +124,7 @@ def test_grdtrack_wrong_kind_of_grid_input(dataarray): def test_grdtrack_without_newcolname_setting(dataarray): """ - Run grdtrack by not passing in newcolname parameter setting + Run grdtrack by not passing in newcolname parameter setting. """ dataframe = load_ocean_ridge_points() @@ -132,7 +134,7 @@ def test_grdtrack_without_newcolname_setting(dataarray): def test_grdtrack_without_outfile_setting(dataarray): """ - Run grdtrack by not passing in outfile parameter setting + Run grdtrack by not passing in outfile parameter setting. """ csvfile = which("@ridge.txt", download="c") diff --git a/pygmt/tests/test_grdview.py b/pygmt/tests/test_grdview.py index c5d09d575d2..9ddff041bb6 100644 --- a/pygmt/tests/test_grdview.py +++ b/pygmt/tests/test_grdview.py @@ -1,5 +1,5 @@ """ -Tests grdview +Tests grdview. """ import pytest from pygmt import Figure, grdcut, which @@ -10,14 +10,16 @@ @pytest.fixture(scope="module", name="region") def fixture_region(): - "Test region as lonmin, lonmax, latmin, latmax" + """ + Test region as lonmin, lonmax, latmin, latmax. + """ return (-116, -109, -47, -44) @pytest.fixture(scope="module", name="gridfile") def fixture_gridfile(region): """ - Load the NetCDF grid file from the sample earth_relief file + Load the NetCDF grid file from the sample earth_relief file. """ with GMTTempFile(suffix=".nc") as tmpfile: grdcut(grid="@earth_relief_01d_g", region=region, outgrid=tmpfile.name) @@ -27,7 +29,7 @@ def fixture_gridfile(region): @pytest.fixture(scope="module", name="xrgrid") def fixture_xrgrid(region): """ - Load the xarray.DataArray grid from the sample earth_relief file + Load the xarray.DataArray grid from the sample earth_relief file. """ return grdcut(grid="@earth_relief_01d_g", region=region) @@ -176,8 +178,8 @@ def test_grdview_on_a_plane_with_colored_frontal_facade(gridfile, xrgrid): @check_figures_equal() def test_grdview_with_perspective_and_zaxis_frame(gridfile, xrgrid, region): """ - Run grdview by passing in a grid and plotting an annotated vertical - z-axis frame on a Transverse Mercator (T) projection. + Run grdview by passing in a grid and plotting an annotated vertical z-axis + frame on a Transverse Mercator (T) projection. """ fig_ref, fig_test = Figure(), Figure() projection = f"T{(region[0]+region[1])/2}/{abs((region[2]+region[3])/2)}" diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index e04f3304616..5f33291798f 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -1,5 +1,5 @@ """ -Tests the helper functions/classes/etc used in wrapping GMT +Tests the helper functions/classes/etc used in wrapping GMT. """ import os @@ -27,29 +27,39 @@ ], ) def test_data_kind_fails(data, x, y): - "Make sure data_kind raises exceptions when it should" + """ + Make sure data_kind raises exceptions when it should. + """ with pytest.raises(GMTInvalidInput): data_kind(data=data, x=x, y=y) def test_unique_name(): - "Make sure the names are really unique" + """ + Make sure the names are really unique. + """ names = [unique_name() for i in range(100)] assert len(names) == len(set(names)) def test_kwargs_to_strings_fails(): - "Make sure it fails for invalid conversion types." + """ + Make sure it fails for invalid conversion types. + """ with pytest.raises(GMTInvalidInput): kwargs_to_strings(bla="blablabla") def test_kwargs_to_strings_no_bools(): - "Test that not converting bools works" + """ + Test that not converting bools works. + """ @kwargs_to_strings(convert_bools=False) def my_module(**kwargs): - "Function that does nothing" + """ + Function that does nothing. + """ return kwargs # The module should return the exact same arguments it was given @@ -58,7 +68,9 @@ def my_module(**kwargs): def test_gmttempfile(): - "Check that file is really created and deleted." + """ + Check that file is really created and deleted. + """ with GMTTempFile() as tmpfile: assert os.path.exists(tmpfile.name) # File should be deleted when leaving the with block @@ -66,7 +78,9 @@ def test_gmttempfile(): def test_gmttempfile_unique(): - "Check that generating multiple files creates unique names" + """ + Check that generating multiple files creates unique names. + """ with GMTTempFile() as tmp1: with GMTTempFile() as tmp2: with GMTTempFile() as tmp3: @@ -74,7 +88,9 @@ def test_gmttempfile_unique(): def test_gmttempfile_prefix_suffix(): - "Make sure the prefix and suffix of temporary files are user specifiable" + """ + 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") @@ -90,7 +106,9 @@ def test_gmttempfile_prefix_suffix(): def test_gmttempfile_read(): - "Make sure GMTTempFile.read() works" + """ + Make sure GMTTempFile.read() works. + """ with GMTTempFile() as tmpfile: with open(tmpfile.name, "w") as ftmp: ftmp.write("in.dat: N = 2\t<1/3>\t<2/4>\n") @@ -99,7 +117,9 @@ def test_gmttempfile_read(): def test_args_in_kwargs(): - "Test that args_in_kwargs function returns correct Boolean responses." + """ + Test that args_in_kwargs function returns correct Boolean responses. + """ kwargs = {"A": 1, "B": 2, "C": 3} # Passing list of arguments with passing values in the beginning passing_args_1 = ["B", "C", "D"] diff --git a/pygmt/tests/test_image.py b/pygmt/tests/test_image.py index dc0f65ab3ec..3140ba6cbba 100644 --- a/pygmt/tests/test_image.py +++ b/pygmt/tests/test_image.py @@ -13,7 +13,9 @@ @pytest.mark.skipif(sys.platform == "win32", reason="crashes on Windows") @pytest.mark.mpl_image_compare def test_image(): - "Place images on map" + """ + Place images on map. + """ fig = Figure() fig.image(TEST_IMG, D="x0/0+w1i", F="+pthin,blue") return fig diff --git a/pygmt/tests/test_info.py b/pygmt/tests/test_info.py index 5ffc4070099..4c8884e17f6 100644 --- a/pygmt/tests/test_info.py +++ b/pygmt/tests/test_info.py @@ -1,5 +1,5 @@ """ -Tests for gmtinfo +Tests for gmtinfo. """ import os @@ -16,7 +16,9 @@ def test_info(): - "Make sure info works on file name inputs" + """ + Make sure info works on file name inputs. + """ output = info(table=POINTS_DATA) expected_output = ( f"{POINTS_DATA}: N = 20 " @@ -28,7 +30,9 @@ def test_info(): def test_info_dataframe(): - "Make sure info works on pandas.DataFrame inputs" + """ + Make sure info works on pandas.DataFrame inputs. + """ table = pd.read_csv(POINTS_DATA, sep=" ", header=None) output = info(table=table) expected_output = ( @@ -42,7 +46,9 @@ def test_info_dataframe(): "after https://github.com/GenericMappingTools/gmt/issues/4241 is resolved", ) def test_info_pandas_dataframe_time_column(): - "Make sure info works on pandas.DataFrame inputs with a time column" + """ + Make sure info works on pandas.DataFrame inputs with a time column. + """ table = pd.DataFrame( data={ "z": [10, 13, 12, 15, 14], @@ -61,7 +67,9 @@ def test_info_pandas_dataframe_time_column(): "after https://github.com/GenericMappingTools/gmt/issues/4241 is resolved", ) def test_info_xarray_dataset_time_column(): - "Make sure info works on xarray.Dataset 1D inputs with a time column" + """ + Make sure info works on xarray.Dataset 1D inputs with a time column. + """ table = xr.Dataset( coords={"index": [0, 1, 2, 3, 4]}, data_vars={ @@ -77,7 +85,9 @@ def test_info_xarray_dataset_time_column(): def test_info_2d_array(): - "Make sure info works on 2D numpy.ndarray inputs" + """ + Make sure info works on 2D numpy.ndarray inputs. + """ table = np.loadtxt(POINTS_DATA) output = info(table=table) expected_output = ( @@ -87,14 +97,18 @@ def test_info_2d_array(): def test_info_1d_array(): - "Make sure info works on 1D numpy.ndarray inputs" + """ + Make sure info works on 1D numpy.ndarray inputs. + """ output = info(table=np.arange(20)) expected_output = ": N = 20 <0/19>\n" assert output == expected_output def test_info_per_column(): - "Make sure the per_column option works" + """ + Make sure the per_column option works. + """ output = info(table=POINTS_DATA, per_column=True) npt.assert_allclose( actual=output, desired=[11.5309, 61.7074, -2.9289, 7.8648, 0.1412, 0.9338] @@ -102,13 +116,17 @@ def test_info_per_column(): def test_info_spacing(): - "Make sure the spacing option works" + """ + Make sure the spacing option works. + """ output = info(table=POINTS_DATA, spacing=0.1) npt.assert_allclose(actual=output, desired=[11.5, 61.8, -3, 7.9]) def test_info_spacing_bounding_box(): - "Make sure the spacing option for writing a bounding box works" + """ + Make sure the spacing option for writing a bounding box works. + """ output = info(table=POINTS_DATA, spacing="b") npt.assert_allclose( actual=output, @@ -123,13 +141,17 @@ def test_info_spacing_bounding_box(): def test_info_per_column_spacing(): - "Make sure the per_column and spacing options work together" + """ + Make sure the per_column and spacing options work together. + """ output = info(table=POINTS_DATA, per_column=True, spacing=0.1) npt.assert_allclose(actual=output, desired=[11.5, 61.8, -3, 7.9, 0.1412, 0.9338]) def test_info_nearest_multiple(): - "Make sure the nearest_multiple option works" + """ + Make sure the nearest_multiple option works. + """ output = info(table=POINTS_DATA, nearest_multiple=0.1) npt.assert_allclose(actual=output, desired=[11.5, 61.8, 0.1]) @@ -137,7 +159,7 @@ def test_info_nearest_multiple(): def test_info_fails(): """ Make sure info raises an exception if not given either a file name, pandas - DataFrame, or numpy ndarray + DataFrame, or numpy ndarray. """ with pytest.raises(GMTInvalidInput): info(table=xr.DataArray(21)) diff --git a/pygmt/tests/test_legend.py b/pygmt/tests/test_legend.py index 6e543d12d9a..60479814b0d 100644 --- a/pygmt/tests/test_legend.py +++ b/pygmt/tests/test_legend.py @@ -1,5 +1,5 @@ """ -Tests for legend +Tests for legend. """ import pytest from pygmt import Figure @@ -130,7 +130,7 @@ def test_legend_specfile(): def test_legend_fails(): """ - Test legend fails with invalid spec + Test legend fails with invalid spec. """ fig = Figure() with pytest.raises(GMTInvalidInput): diff --git a/pygmt/tests/test_logo.py b/pygmt/tests/test_logo.py index 2a9ffde1ad0..f5a15571f76 100644 --- a/pygmt/tests/test_logo.py +++ b/pygmt/tests/test_logo.py @@ -1,5 +1,5 @@ """ -Tests for fig.logo +Tests for fig.logo. """ from pygmt import Figure from pygmt.helpers.testing import check_figures_equal @@ -7,7 +7,9 @@ @check_figures_equal() def test_logo(): - "Plot a GMT logo of a 2 inch width as a stand-alone plot" + """ + Plot a GMT logo of a 2 inch width as a stand-alone plot. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.logo(D="x0/0+w2i") @@ -17,7 +19,9 @@ def test_logo(): @check_figures_equal() def test_logo_on_a_map(): - "Plot a GMT logo in the upper right corner of a map" + """ + Plot a GMT logo in the upper right corner of a map. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.coast(R="-90/-70/0/20", J="M6i", G="chocolate", B="") diff --git a/pygmt/tests/test_makecpt.py b/pygmt/tests/test_makecpt.py index 5a457363ab2..0cb8517ceb5 100644 --- a/pygmt/tests/test_makecpt.py +++ b/pygmt/tests/test_makecpt.py @@ -1,5 +1,5 @@ """ -Tests for makecpt +Tests for makecpt. """ import os @@ -17,26 +17,32 @@ @pytest.fixture(scope="module", name="points") def fixture_points(): - "Load the points data from the test file" + """ + Load the points data from the test file. + """ return np.loadtxt(POINTS_DATA) @pytest.fixture(scope="module", name="region") def fixture_region(): - "The data region" + """ + The data region. + """ return [10, 70, -5, 10] @pytest.fixture(scope="module", name="grid") def fixture_grid(): - "Load the grid data from the sample earth_relief file" + """ + Load the grid data from the sample earth_relief file. + """ return load_earth_relief(registration="gridline") @pytest.mark.mpl_image_compare def test_makecpt_to_plot_points(points, region): """ - Use static color palette table to change color of points + Use static color palette table to change color of points. """ fig = Figure() makecpt(cmap="rainbow") @@ -54,7 +60,7 @@ def test_makecpt_to_plot_points(points, region): @pytest.mark.mpl_image_compare def test_makecpt_to_plot_grid(grid): """ - Use static color palette table to change color of grid + Use static color palette table to change color of grid. """ fig = Figure() makecpt(cmap="relief") @@ -66,7 +72,7 @@ def test_makecpt_to_plot_grid(grid): def test_makecpt_to_plot_grid_scaled_with_series(grid): """ Use static color palette table scaled to a min/max series to change color - of grid + of grid. """ # Use single-character arguments for the reference image fig_ref = Figure() @@ -81,7 +87,7 @@ def test_makecpt_to_plot_grid_scaled_with_series(grid): def test_makecpt_output_to_cpt_file(): """ - Save the generated static color palette table to a .cpt file + Save the generated static color palette table to a .cpt file. """ with GMTTempFile(suffix=".cpt") as cptfile: makecpt(output=cptfile.name) @@ -90,7 +96,7 @@ def test_makecpt_output_to_cpt_file(): def test_makecpt_blank_output(): """ - Use incorrect setting by passing in blank file name to output parameter + Use incorrect setting by passing in blank file name to output parameter. """ with pytest.raises(GMTInvalidInput): makecpt(output="") @@ -98,7 +104,7 @@ def test_makecpt_blank_output(): def test_makecpt_invalid_output(): """ - Use incorrect setting by passing in invalid type to output parameter + Use incorrect setting by passing in invalid type to output parameter. """ with pytest.raises(GMTInvalidInput): makecpt(output=["some.cpt"]) @@ -107,7 +113,7 @@ def test_makecpt_invalid_output(): @pytest.mark.mpl_image_compare def test_makecpt_truncated_to_zlow_zhigh(grid): """ - Use static color palette table that is truncated to z-low and z-high + Use static color palette table that is truncated to z-low and z-high. """ fig = Figure() makecpt(cmap="rainbow", truncate=[0.15, 0.85], series=[-4500, 4500]) @@ -118,7 +124,7 @@ def test_makecpt_truncated_to_zlow_zhigh(grid): @pytest.mark.mpl_image_compare def test_makecpt_truncated_at_zlow_only(grid): """ - Use static color palette table that is truncated at z-low only + Use static color palette table that is truncated at z-low only. """ fig = Figure() makecpt(cmap="rainbow", truncate=[0.5, None], series=[-4500, 4500]) @@ -129,7 +135,7 @@ def test_makecpt_truncated_at_zlow_only(grid): @pytest.mark.mpl_image_compare def test_makecpt_truncated_at_zhigh_only(grid): """ - Use static color palette table that is truncated at z-high only + Use static color palette table that is truncated at z-high only. """ fig = Figure() makecpt(cmap="rainbow", truncate=[None, 0.5], series=[-4500, 4500]) @@ -140,7 +146,7 @@ def test_makecpt_truncated_at_zhigh_only(grid): @pytest.mark.mpl_image_compare def test_makecpt_reverse_color_only(grid): """ - Use static color palette table with its colors reversed + Use static color palette table with its colors reversed. """ fig = Figure() makecpt(cmap="earth", reverse=True) @@ -151,7 +157,7 @@ def test_makecpt_reverse_color_only(grid): @pytest.mark.mpl_image_compare def test_makecpt_reverse_zsign_only(grid): """ - Use static color palette table with its z-value sign reversed + Use static color palette table with its z-value sign reversed. """ fig = Figure() makecpt(cmap="earth", reverse="z") @@ -163,7 +169,7 @@ def test_makecpt_reverse_zsign_only(grid): def test_makecpt_reverse_color_and_zsign(grid): """ Use static color palette table with both its colors and z-value sign - reversed + reversed. """ fig = Figure() makecpt(cmap="earth", reverse="cz") diff --git a/pygmt/tests/test_meca.py b/pygmt/tests/test_meca.py index 762d581e076..24715cd92a2 100644 --- a/pygmt/tests/test_meca.py +++ b/pygmt/tests/test_meca.py @@ -1,5 +1,5 @@ """ -Tests for meca +Tests for meca. """ import os @@ -66,8 +66,8 @@ def test_meca_spec_dict_list(): @pytest.mark.mpl_image_compare def test_meca_spec_dataframe(): """ - Test supplying a pandas DataFrame containing focal mechanisms and - locations to the `spec` argument. + Test supplying a pandas DataFrame containing focal mechanisms and locations + to the `spec` argument. """ fig = Figure() @@ -92,8 +92,8 @@ def test_meca_spec_dataframe(): @pytest.mark.mpl_image_compare def test_meca_spec_1d_array(): """ - Test supplying a 1D numpy array containing focal mechanisms and - locations to the `spec` argument. + Test supplying a 1D numpy array containing focal mechanisms and locations + to the `spec` argument. """ fig = Figure() @@ -134,8 +134,8 @@ def test_meca_spec_1d_array(): @pytest.mark.mpl_image_compare def test_meca_spec_2d_array(): """ - Test supplying a 2D numpy array containing focal mechanisms and - locations to the `spec` argument. + Test supplying a 2D numpy array containing focal mechanisms and locations + to the `spec` argument. """ fig = Figure() diff --git a/pygmt/tests/test_plot.py b/pygmt/tests/test_plot.py index 9e2ba9885d9..040a89111c4 100644 --- a/pygmt/tests/test_plot.py +++ b/pygmt/tests/test_plot.py @@ -20,19 +20,25 @@ @pytest.fixture(scope="module") def data(): - "Load the point data from the test file" + """ + Load the point data from the test file. + """ return np.loadtxt(POINTS_DATA) @pytest.fixture(scope="module") def region(): - "The data region" + """ + The data region. + """ return [10, 70, -5, 10] @pytest.mark.mpl_image_compare def test_plot_red_circles(data, region): - "Plot the data in red circles passing in vectors" + """ + Plot the data in red circles passing in vectors. + """ fig = Figure() fig.plot( x=data[:, 0], @@ -47,7 +53,9 @@ def test_plot_red_circles(data, region): def test_plot_fail_no_data(data): - "Plot should raise an exception if no data is given" + """ + Plot should raise an exception if no data is given. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.plot( @@ -86,7 +94,9 @@ def test_plot_fail_no_data(data): def test_plot_fail_size_color(data): - "Should raise an exception if array sizes and color are used with matrix" + """ + Should raise an exception if array sizes and color are used with matrix. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.plot( @@ -111,7 +121,9 @@ def test_plot_fail_size_color(data): @pytest.mark.mpl_image_compare def test_plot_projection(data): - "Plot the data in green squares with a projection" + """ + Plot the data in green squares with a projection. + """ fig = Figure() fig.plot( x=data[:, 0], @@ -127,7 +139,9 @@ def test_plot_projection(data): @check_figures_equal() def test_plot_colors(data, region): - "Plot the data using z as colors" + """ + Plot the data using z as colors. + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.plot( @@ -154,7 +168,9 @@ def test_plot_colors(data, region): @pytest.mark.mpl_image_compare def test_plot_sizes(data, region): - "Plot the data using z as sizes" + """ + Plot the data using z as sizes. + """ fig = Figure() fig.plot( x=data[:, 0], @@ -171,7 +187,9 @@ def test_plot_sizes(data, region): @pytest.mark.mpl_image_compare def test_plot_colors_sizes(data, region): - "Plot the data using z as sizes and colors" + """ + Plot the data using z as sizes and colors. + """ fig = Figure() fig.plot( x=data[:, 0], @@ -189,7 +207,9 @@ def test_plot_colors_sizes(data, region): @pytest.mark.mpl_image_compare def test_plot_colors_sizes_proj(data, region): - "Plot the data using z as sizes and colors with a projection" + """ + Plot the data using z as sizes and colors with a projection. + """ fig = Figure() fig.coast(region=region, projection="M10i", frame="af", water="skyblue") fig.plot( @@ -205,7 +225,9 @@ def test_plot_colors_sizes_proj(data, region): @check_figures_equal() def test_plot_transparency(): - "Plot the data with a constant transparency" + """ + Plot the data with a constant transparency. + """ x = np.arange(1, 10) y = np.arange(1, 10) @@ -232,7 +254,9 @@ def test_plot_transparency(): @check_figures_equal() def test_plot_varying_transparency(): - "Plot the data using z as transparency" + """ + Plot the data using z as transparency. + """ x = np.arange(1, 10) y = np.arange(1, 10) z = np.arange(1, 10) * 10 @@ -266,7 +290,9 @@ def test_plot_varying_transparency(): @check_figures_equal() def test_plot_sizes_colors_transparencies(): - "Plot the data with varying sizes and colors using z as transparency" + """ + Plot the data with varying sizes and colors using z as transparency. + """ x = np.arange(1.0, 10.0) y = np.arange(1.0, 10.0) color = np.arange(1, 10) * 0.15 @@ -303,7 +329,9 @@ def test_plot_sizes_colors_transparencies(): @pytest.mark.mpl_image_compare def test_plot_matrix(data): - "Plot the data passing in a matrix and specifying columns" + """ + Plot the data passing in a matrix and specifying columns. + """ fig = Figure() fig.plot( data=data, @@ -319,7 +347,9 @@ def test_plot_matrix(data): @pytest.mark.mpl_image_compare def test_plot_matrix_color(data): - "Plot the data passing in a matrix and using a colormap" + """ + Plot the data passing in a matrix and using a colormap. + """ fig = Figure() fig.plot( data=data, @@ -334,7 +364,9 @@ def test_plot_matrix_color(data): @pytest.mark.mpl_image_compare def test_plot_from_file(region): - "Plot using the data file name instead of loaded data" + """ + Plot using the data file name instead of loaded data. + """ fig = Figure() fig.plot( data=POINTS_DATA, @@ -350,7 +382,9 @@ def test_plot_from_file(region): @pytest.mark.mpl_image_compare def test_plot_vectors(): - "Plot vectors" + """ + Plot vectors. + """ azimuth = np.array([0, 45, 90, 135, 180, 225, 270, 310]) lengths = np.linspace(0.1, 1, len(azimuth)) lon = np.sin(np.deg2rad(azimuth)) @@ -371,7 +405,8 @@ def test_plot_vectors(): @pytest.mark.mpl_image_compare def test_plot_lines_with_arrows(): - """Plot lines with arrows. + """ + Plot lines with arrows. The test is slightly different from test_plot_vectors(). Here the vectors are plotted as lines, with arrows at the end. @@ -388,7 +423,9 @@ def test_plot_lines_with_arrows(): @pytest.mark.mpl_image_compare def test_plot_scalar_xy(): - "Plot symbols given scalar x, y coordinates" + """ + Plot symbols given scalar x, y coordinates. + """ fig = Figure() fig.basemap(region=[-2, 2, -2, 2], frame=True) fig.plot(x=-1.5, y=1.5, style="c1c") @@ -399,7 +436,9 @@ def test_plot_scalar_xy(): @pytest.mark.mpl_image_compare def test_plot_datetime(): - """Test various datetime input data""" + """ + Test various datetime input data. + """ fig = Figure() fig.basemap( projection="X15c/5c", diff --git a/pygmt/tests/test_plot3d.py b/pygmt/tests/test_plot3d.py index e73be97b326..d3a4dbbc7e4 100644 --- a/pygmt/tests/test_plot3d.py +++ b/pygmt/tests/test_plot3d.py @@ -16,13 +16,17 @@ @pytest.fixture(scope="module", name="data") def fixture_data(): - "Load the point data from the test file" + """ + Load the point data from the test file. + """ return np.loadtxt(POINTS_DATA) @pytest.fixture(scope="module", name="region") def fixture_region(): - "The data region" + """ + The data region. + """ return [10, 70, -5, 10, 0, 1] @@ -85,7 +89,9 @@ def test_plot3d_red_circles_zsize(data, region): def test_plot3d_fail_no_data(data, region): - "Plot should raise an exception if no data is given" + """ + Plot should raise an exception if no data is given. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.plot3d( @@ -125,7 +131,9 @@ def test_plot3d_fail_no_data(data, region): def test_plot3d_fail_size_color(data, region): - "Should raise an exception if array sizes and color are used with matrix" + """ + Should raise an exception if array sizes and color are used with matrix. + """ fig = Figure() with pytest.raises(GMTInvalidInput): fig.plot3d( @@ -150,7 +158,9 @@ def test_plot3d_fail_size_color(data, region): @check_figures_equal() def test_plot3d_projection(data, region): - "Plot the data in green squares with a projection" + """ + Plot the data in green squares with a projection. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -179,7 +189,9 @@ def test_plot3d_projection(data, region): @check_figures_equal() def test_plot3d_colors(data, region): - "Plot the data using z as colors" + """ + Plot the data using z as colors. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -211,7 +223,9 @@ def test_plot3d_colors(data, region): @check_figures_equal() def test_plot3d_sizes(data, region): - "Plot the data using z as sizes" + """ + Plot the data using z as sizes. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -244,7 +258,9 @@ def test_plot3d_sizes(data, region): @check_figures_equal() def test_plot3d_colors_sizes(data, region): - "Plot the data using z as sizes and colors" + """ + Plot the data using z as sizes and colors. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -278,7 +294,9 @@ def test_plot3d_colors_sizes(data, region): @check_figures_equal() def test_plot3d_colors_sizes_proj(data, region): - "Plot the data using z as sizes and colors with a projection" + """ + Plot the data using z as sizes and colors with a projection. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -313,7 +331,9 @@ def test_plot3d_colors_sizes_proj(data, region): @check_figures_equal() def test_plot3d_transparency(): - "Plot the data with a constant transparency" + """ + Plot the data with a constant transparency. + """ x = np.arange(1, 10) y = np.arange(1, 10) z = np.arange(1, 10) * 10 @@ -352,7 +372,9 @@ def test_plot3d_transparency(): @check_figures_equal() def test_plot3d_varying_transparency(): - "Plot the data using z as transparency using 3-D column symbols" + """ + Plot the data using z as transparency using 3-D column symbols. + """ x = np.arange(1, 10) y = np.arange(1, 10) z = np.arange(1, 10) * 10 @@ -390,7 +412,9 @@ def test_plot3d_varying_transparency(): @check_figures_equal() def test_plot3d_sizes_colors_transparencies(): - "Plot the data with varying sizes and colors using z as transparency" + """ + Plot the data with varying sizes and colors using z as transparency. + """ x = np.arange(1.0, 10.0) y = np.arange(1.0, 10.0) z = np.arange(1, 10) * 10 @@ -433,7 +457,9 @@ def test_plot3d_sizes_colors_transparencies(): @check_figures_equal() def test_plot3d_matrix(data, region): - "Plot the data passing in a matrix and specifying columns" + """ + Plot the data passing in a matrix and specifying columns. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -462,7 +488,9 @@ def test_plot3d_matrix(data, region): @check_figures_equal() def test_plot3d_matrix_color(data, region): - "Plot the data passing in a matrix and using a colormap" + """ + Plot the data passing in a matrix and using a colormap. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -491,7 +519,9 @@ def test_plot3d_matrix_color(data, region): @check_figures_equal() def test_plot3d_from_file(region): - "Plot using the data file name instead of loaded data" + """ + Plot using the data file name instead of loaded data. + """ fig_ref, fig_test = Figure(), Figure() fig_ref.plot3d( data=POINTS_DATA, @@ -520,7 +550,9 @@ def test_plot3d_from_file(region): @check_figures_equal() def test_plot3d_vectors(): - "Plot vectors" + """ + Plot vectors. + """ azimuth = np.array([0, 45, 90, 135, 180, 225, 270, 310]) lengths = np.linspace(0.1, 1, len(azimuth)) lon = np.sin(np.deg2rad(azimuth)) @@ -557,7 +589,9 @@ def test_plot3d_vectors(): @check_figures_equal() def test_plot3d_scalar_xyz(): - "Plot symbols given scalar x, y, z coordinates" + """ + Plot symbols given scalar x, y, z coordinates. + """ fig_ref, fig_test = Figure(), Figure() with GMTTempFile() as tmpfile: np.savetxt(tmpfile.name, np.c_[[-1.5, 0, 1.5], [1.5, 0, -1.5], [-1.5, 0, 1.5]]) diff --git a/pygmt/tests/test_session_management.py b/pygmt/tests/test_session_management.py index 235fb097229..5dddf3b75ef 100644 --- a/pygmt/tests/test_session_management.py +++ b/pygmt/tests/test_session_management.py @@ -10,6 +10,7 @@ def test_begin_end(): """ Run a command inside a begin-end modern mode block. + First, end the global session. When finished, restart it. """ end() # Kill the global session @@ -25,6 +26,7 @@ def test_begin_end(): def test_gmt_compat_6_is_applied(capsys): """ Ensure that users with old gmt.conf files won't get pygmt-session [ERROR]: + GMT_COMPATIBILITY: Expects values from 6 to 6; reset to 6. """ end() # Kill the global session diff --git a/pygmt/tests/test_sphinx_gallery.py b/pygmt/tests/test_sphinx_gallery.py index cac8fa612e4..3dfed2ef76e 100644 --- a/pygmt/tests/test_sphinx_gallery.py +++ b/pygmt/tests/test_sphinx_gallery.py @@ -17,7 +17,9 @@ @pytest.mark.skipif(sphinx_gallery is None, reason="requires sphinx-gallery") def test_pygmtscraper(): - "Make sure the scraper finds the figures and removes them from the pool." + """ + Make sure the scraper finds the figures and removes them from the pool. + """ showed = SHOWED_FIGURES.copy() for _ in range(len(SHOWED_FIGURES)): diff --git a/pygmt/tests/test_surface.py b/pygmt/tests/test_surface.py index 3c7a5018067..9f442b16c2d 100644 --- a/pygmt/tests/test_surface.py +++ b/pygmt/tests/test_surface.py @@ -1,5 +1,5 @@ """ -Tests for surface +Tests for surface. """ import os @@ -16,7 +16,7 @@ def test_surface_input_file(): """ - Run surface by passing in a filename + Run surface by passing in a filename. """ fname = which("@tut_ship.xyz", download="c") output = surface(data=fname, spacing="5m", region=[245, 255, 20, 30]) @@ -28,7 +28,7 @@ def test_surface_input_file(): def test_surface_input_data_array(): """ - Run surface by passing in a numpy array into data + Run surface by passing in a numpy array into data. """ ship_data = load_sample_bathymetry() data = ship_data.values # convert pandas.DataFrame to numpy.ndarray @@ -39,7 +39,7 @@ def test_surface_input_data_array(): def test_surface_input_xyz(): """ - Run surface by passing in x, y, z numpy.ndarrays individually + Run surface by passing in x, y, z numpy.ndarrays individually. """ ship_data = load_sample_bathymetry() output = surface( @@ -55,7 +55,7 @@ def test_surface_input_xyz(): def test_surface_input_xy_no_z(): """ - Run surface by passing in x and y, but no z + Run surface by passing in x and y, but no z. """ ship_data = load_sample_bathymetry() with pytest.raises(GMTInvalidInput): @@ -69,7 +69,7 @@ def test_surface_input_xy_no_z(): def test_surface_wrong_kind_of_input(): """ - Run surface using grid input that is not file/matrix/vectors + Run surface using grid input that is not file/matrix/vectors. """ ship_data = load_sample_bathymetry() data = ship_data.bathymetry.to_xarray() # convert pandas.Series to xarray.DataArray @@ -80,7 +80,7 @@ def test_surface_wrong_kind_of_input(): def test_surface_with_outfile_param(): """ - Run surface with the -Goutputfile.nc parameter + Run surface with the -Goutputfile.nc parameter. """ ship_data = load_sample_bathymetry() data = ship_data.values # convert pandas.DataFrame to numpy.ndarray @@ -100,7 +100,7 @@ def test_surface_with_outfile_param(): def test_surface_short_aliases(): """ Run surface using short aliases -I for spacing, -R for region, -G for - outfile + outfile. """ ship_data = load_sample_bathymetry() data = ship_data.values # convert pandas.DataFrame to numpy.ndarray diff --git a/pygmt/tests/test_text.py b/pygmt/tests/test_text.py index f5831607f66..8c3305c5267 100644 --- a/pygmt/tests/test_text.py +++ b/pygmt/tests/test_text.py @@ -1,6 +1,6 @@ # pylint: disable=redefined-outer-name """ -Tests text +Tests text. """ import os @@ -18,20 +18,24 @@ @pytest.fixture(scope="module") def projection(): - "The projection system" + """ + The projection system. + """ return "x4i" @pytest.fixture(scope="module") def region(): - "The data region" + """ + The data region. + """ return [0, 5, 0, 2.5] @pytest.mark.mpl_image_compare def test_text_single_line_of_text(region, projection): """ - Place a single line text of text at some x, y location + Place a single line text of text at some x, y location. """ fig = Figure() fig.text( @@ -47,7 +51,7 @@ def test_text_single_line_of_text(region, projection): @pytest.mark.mpl_image_compare def test_text_multiple_lines_of_text(region, projection): """ - Place multiple lines of text at their respective x, y locations + Place multiple lines of text at their respective x, y locations. """ fig = Figure() fig.text( @@ -62,7 +66,7 @@ def test_text_multiple_lines_of_text(region, projection): def test_text_without_text_input(region, projection): """ - Run text by passing in x and y, but no text + Run text by passing in x and y, but no text. """ fig = Figure() with pytest.raises(GMTInvalidInput): @@ -72,7 +76,7 @@ def test_text_without_text_input(region, projection): @pytest.mark.mpl_image_compare def test_text_input_single_filename(): """ - Run text by passing in one filename to textfiles + Run text by passing in one filename to textfiles. """ fig = Figure() fig.text(region=[10, 70, -5, 10], textfiles=POINTS_DATA) @@ -82,7 +86,7 @@ def test_text_input_single_filename(): @pytest.mark.mpl_image_compare def test_text_input_remote_filename(): """ - Run text by passing in a remote filename to textfiles + Run text by passing in a remote filename to textfiles. """ fig = Figure() fig.text(region=[0, 6.5, 0, 6.5], textfiles="@Table_5_11.txt") @@ -92,7 +96,7 @@ def test_text_input_remote_filename(): @pytest.mark.mpl_image_compare def test_text_input_multiple_filenames(): """ - Run text by passing in multiple filenames to textfiles + Run text by passing in multiple filenames to textfiles. """ fig = Figure() fig.text(region=[10, 70, -30, 10], textfiles=[POINTS_DATA, CITIES_DATA]) @@ -101,7 +105,7 @@ def test_text_input_multiple_filenames(): def test_text_nonexistent_filename(): """ - Run text by passing in a list of filenames with one that does not exist + Run text by passing in a list of filenames with one that does not exist. """ fig = Figure() with pytest.raises(GMTCLibError): @@ -149,7 +153,7 @@ def test_text_position_offset_with_line(region): @pytest.mark.mpl_image_compare def test_text_angle_30(region, projection): """ - Print text at 30 degrees counter-clockwise from horizontal + Print text at 30 degrees counter-clockwise from horizontal. """ fig = Figure() fig.text( @@ -166,7 +170,7 @@ def test_text_angle_30(region, projection): @pytest.mark.mpl_image_compare def test_text_font_bold(region, projection): """ - Print text with a bold font + Print text with a bold font. """ fig = Figure() fig.text( @@ -183,7 +187,7 @@ def test_text_font_bold(region, projection): @pytest.mark.mpl_image_compare def test_text_fill(region, projection): """ - Print text with blue color fill + Print text with blue color fill. """ fig = Figure() fig.text( @@ -200,7 +204,7 @@ def test_text_fill(region, projection): @pytest.mark.mpl_image_compare def test_text_pen(region, projection): """ - Print text with thick green dashed pen + Print text with thick green dashed pen. """ fig = Figure() fig.text( @@ -217,7 +221,7 @@ def test_text_pen(region, projection): @pytest.mark.mpl_image_compare def test_text_round_clearance(region, projection): """ - Print text with round rectangle box clearance + Print text with round rectangle box clearance. """ fig = Figure() fig.text( @@ -235,7 +239,7 @@ def test_text_round_clearance(region, projection): @pytest.mark.mpl_image_compare def test_text_justify_bottom_right_and_top_left(region, projection): """ - Print text justified at bottom right and top left + Print text justified at bottom right and top left. """ fig = Figure() fig.text( @@ -261,7 +265,9 @@ def test_text_justify_bottom_right_and_top_left(region, projection): def test_text_justify_parsed_from_textfile(): """ Print text justified based on a column from textfile, using justify=True - boolean operation. Loosely based on "All great-circle paths lead to Rome" + boolean operation. + + Loosely based on "All great-circle paths lead to Rome" gallery example at https://gmt.soest.hawaii.edu/doc/latest/gallery/ex23.html """ @@ -300,7 +306,9 @@ def test_text_angle_font_justify_from_textfile(): @check_figures_equal() def test_text_transparency(): - "Add texts with a constant transparency" + """ + Add texts with a constant transparency. + """ x = np.arange(1, 10) y = np.arange(11, 20) text = [f"TEXT-{i}-{j}" for i, j in zip(x, y)] @@ -320,7 +328,9 @@ def test_text_transparency(): @check_figures_equal() def test_text_varying_transparency(): - "Add texts with varying transparency" + """ + Add texts with varying transparency. + """ x = np.arange(1, 10) y = np.arange(11, 20) text = [f"TEXT-{i}-{j}" for i, j in zip(x, y)] @@ -341,7 +351,9 @@ def test_text_varying_transparency(): @check_figures_equal() def test_text_nonstr_text(): - "Input text is in non-string type (e.g., int, float)" + """ + Input text is in non-string type (e.g., int, float) + """ fig_ref, fig_test = Figure(), Figure() # Use single-character arguments and input files for the reference image diff --git a/pygmt/tests/test_which.py b/pygmt/tests/test_which.py index 9a51adfb990..caac58fe36d 100644 --- a/pygmt/tests/test_which.py +++ b/pygmt/tests/test_which.py @@ -1,5 +1,5 @@ """ -Tests for pygmt.which +Tests for pygmt.which. """ import os @@ -9,7 +9,9 @@ def test_which(): - "Make sure which returns file paths for @files correctly without errors" + """ + Make sure which returns file paths for @files correctly without errors. + """ for fname in ["tut_quakes.ngdc", "tut_bathy.nc"]: cached_file = which(f"@{fname}", download="c") assert os.path.exists(cached_file) @@ -17,7 +19,9 @@ def test_which(): def test_which_fails(): - "which should fail with a FileNotFoundError" + """ + which should fail with a FileNotFoundError. + """ bogus_file = unique_name() with pytest.raises(FileNotFoundError): which(bogus_file) diff --git a/pygmt/tests/test_x2sys_cross.py b/pygmt/tests/test_x2sys_cross.py index a68b9e41ee1..43d766cadd3 100644 --- a/pygmt/tests/test_x2sys_cross.py +++ b/pygmt/tests/test_x2sys_cross.py @@ -1,6 +1,6 @@ # pylint: disable=unused-argument """ -Tests for x2sys_cross +Tests for x2sys_cross. """ import os from tempfile import TemporaryDirectory @@ -19,7 +19,7 @@ def fixture_mock_x2sys_home(monkeypatch): """ Set the X2SYS_HOME environment variable to the current working directory - for the test session + for the test session. """ monkeypatch.setenv("X2SYS_HOME", os.getcwd()) @@ -27,7 +27,7 @@ def fixture_mock_x2sys_home(monkeypatch): @pytest.fixture(scope="module", name="tracks") def fixture_tracks(): """ - Load track data from the sample bathymetry file + Load track data from the sample bathymetry file. """ dataframe = load_sample_bathymetry() dataframe.columns = ["x", "y", "z"] # longitude, latitude, bathymetry @@ -37,7 +37,7 @@ def fixture_tracks(): def test_x2sys_cross_input_file_output_file(mock_x2sys_home): """ Run x2sys_cross by passing in a filename, and output internal crossovers to - an ASCII txt file + an ASCII txt file. """ with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) @@ -57,7 +57,7 @@ def test_x2sys_cross_input_file_output_file(mock_x2sys_home): def test_x2sys_cross_input_file_output_dataframe(mock_x2sys_home): """ Run x2sys_cross by passing in a filename, and output internal crossovers to - a pandas.DataFrame + a pandas.DataFrame. """ with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) @@ -98,7 +98,7 @@ def test_x2sys_cross_input_dataframe_output_dataframe(mock_x2sys_home, tracks): def test_x2sys_cross_input_two_dataframes(mock_x2sys_home): """ Run x2sys_cross by passing in two pandas.DataFrame tables with a time - column, and output external crossovers to a pandas.DataFrame + column, and output external crossovers to a pandas.DataFrame. """ with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) @@ -132,7 +132,7 @@ def test_x2sys_cross_input_two_dataframes(mock_x2sys_home): def test_x2sys_cross_input_two_filenames(mock_x2sys_home): """ Run x2sys_cross by passing in two filenames, and output external crossovers - to a pandas.DataFrame + to a pandas.DataFrame. """ with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) diff --git a/pygmt/tests/test_x2sys_init.py b/pygmt/tests/test_x2sys_init.py index 8696b7e1617..c91435c0eef 100644 --- a/pygmt/tests/test_x2sys_init.py +++ b/pygmt/tests/test_x2sys_init.py @@ -1,6 +1,6 @@ # pylint: disable=unused-argument """ -Tests for x2sys_init +Tests for x2sys_init. """ import os from tempfile import TemporaryDirectory @@ -13,7 +13,7 @@ def fixture_mock_x2sys_home(monkeypatch): """ Set the X2SYS_HOME environment variable to the current working directory - for the test session + for the test session. """ monkeypatch.setenv("X2SYS_HOME", os.getcwd()) @@ -21,7 +21,7 @@ def fixture_mock_x2sys_home(monkeypatch): def test_x2sys_init_region_spacing(mock_x2sys_home): """ Test that x2sys_init's region (R) and spacing (I) sequence arguments accept - a list properly + a list properly. """ with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) @@ -38,7 +38,7 @@ def test_x2sys_init_region_spacing(mock_x2sys_home): def test_x2sys_init_units_gap(mock_x2sys_home): """ Test that x2sys_init's units (N) and gap (W) arguments accept a list - properly + properly. """ with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) diff --git a/requirements-dev.txt b/requirements-dev.txt index fdbbd256aef..f7ce04e8502 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,17 +1,18 @@ # Requirements for development using conda -ipython -matplotlib -jupyter -pytest>=6.0 -pytest-cov -pytest-mpl -coverage[toml] black blackdoc +coverage[toml] +docformatter +flake8 +ipython isort>=5 +jupyter +matplotlib +nbsphinx pylint -flake8 +pytest-cov +pytest-mpl +pytest>=6.0 sphinx -sphinx_rtd_theme==0.4.3 sphinx-gallery -nbsphinx +sphinx_rtd_theme==0.4.3