From 2557e8f5e3e5eb9e8e6c4c47503e5e088172d9cf Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Sun, 22 Nov 2020 22:33:41 -0500 Subject: [PATCH] Run "make format" to format all docstrings --- doc/conf.py | 4 +- pygmt/__init__.py | 1 - pygmt/base_plotting.py | 21 ++--- pygmt/clib/conversion.py | 8 +- pygmt/clib/loading.py | 4 - pygmt/clib/session.py | 37 +++----- pygmt/datasets/earth_relief.py | 7 +- pygmt/datasets/tutorial.py | 6 +- pygmt/exceptions.py | 33 ++----- pygmt/figure.py | 19 ++-- pygmt/filtering.py | 4 +- pygmt/gridding.py | 4 +- pygmt/gridops.py | 5 +- pygmt/helpers/__init__.py | 5 +- pygmt/helpers/decorators.py | 15 +--- pygmt/helpers/tempfile.py | 6 +- pygmt/helpers/testing.py | 4 +- pygmt/helpers/utils.py | 9 +- pygmt/mathops.py | 4 +- pygmt/modules.py | 16 +--- pygmt/sampling.py | 5 +- pygmt/session_management.py | 4 +- pygmt/sphinx_gallery.py | 10 +-- pygmt/tests/test_accessor.py | 33 +++---- pygmt/tests/test_basemap.py | 20 ++--- pygmt/tests/test_blockmedian.py | 28 ++---- pygmt/tests/test_clib.py | 114 +++++++++++------------- pygmt/tests/test_clib_loading.py | 12 ++- pygmt/tests/test_clib_put_matrix.py | 11 ++- pygmt/tests/test_clib_put_strings.py | 9 +- pygmt/tests/test_clib_put_vector.py | 16 ++-- pygmt/tests/test_coast.py | 12 ++- pygmt/tests/test_colorbar.py | 66 ++++---------- pygmt/tests/test_config.py | 54 ++++-------- pygmt/tests/test_contour.py | 16 ++-- pygmt/tests/test_datasets.py | 26 +++--- pygmt/tests/test_figure.py | 25 +++--- pygmt/tests/test_grdcontour.py | 24 +++-- pygmt/tests/test_grdcut.py | 16 ++-- pygmt/tests/test_grdimage.py | 31 +++---- pygmt/tests/test_grdinfo.py | 10 +-- pygmt/tests/test_grdtrack.py | 45 +++------- pygmt/tests/test_grdview.py | 117 +++++++++---------------- pygmt/tests/test_helpers.py | 23 +++-- pygmt/tests/test_image.py | 6 +- pygmt/tests/test_info.py | 32 +++---- pygmt/tests/test_legend.py | 24 ++--- pygmt/tests/test_logo.py | 8 +- pygmt/tests/test_makecpt.py | 81 +++++------------ pygmt/tests/test_meca.py | 46 ++++------ pygmt/tests/test_plot.py | 46 +++++----- pygmt/tests/test_plot3d.py | 39 ++++----- pygmt/tests/test_psconvert.py | 20 ++--- pygmt/tests/test_session_management.py | 6 +- pygmt/tests/test_sphinx_gallery.py | 7 +- pygmt/tests/test_surface.py | 34 ++----- pygmt/tests/test_text.py | 87 ++++++------------ pygmt/tests/test_which.py | 9 +- pygmt/tests/test_x2sys_cross.py | 60 ++++--------- pygmt/tests/test_x2sys_init.py | 22 ++--- pygmt/x2sys.py | 4 +- setup.py | 4 +- 62 files changed, 520 insertions(+), 954 deletions(-) diff --git a/doc/conf.py b/doc/conf.py index 3adbee656c4..6cb39d6830b 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- -""" -Sphinx documentation configuration file. -""" +"""Sphinx documentation configuration file.""" # pylint: disable=invalid-name import datetime diff --git a/pygmt/__init__.py b/pygmt/__init__.py index 0fb12c6652a..45039b64c38 100644 --- a/pygmt/__init__.py +++ b/pygmt/__init__.py @@ -163,7 +163,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 13d1fb00f68..829330a3a38 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 @@ -51,7 +52,6 @@ def _preprocess(self, **kwargs): # pylint: disable=no-self-use >>> base = BasePlotting() >>> base._preprocess(resolution="low") {'resolution': 'low'} - """ return kwargs @@ -78,7 +78,7 @@ def _preprocess(self, **kwargs): # pylint: disable=no-self-use @kwargs_to_strings(R="sequence", p="sequence") def coast(self, **kwargs): """ - Plot continents, shorelines, rivers, and borders on maps + Plot continents, shorelines, rivers, and borders on maps. Plots grayshaded, colored, or textured land-masses [or water-masses] on maps and [optionally] draws coastlines, rivers, and political @@ -138,7 +138,6 @@ def coast(self, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) with Session() as lib: @@ -224,7 +223,6 @@ def colorbar(self, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) with Session() as lib: @@ -253,7 +251,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. @@ -469,7 +467,6 @@ def grdimage(self, grid, **kwargs): {p} {t} {x} - """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) @@ -580,7 +577,6 @@ def grdview(self, grid, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) kind = data_kind(grid, None, None) @@ -778,7 +774,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) @@ -851,7 +846,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. @@ -961,7 +956,6 @@ def plot3d( {t} *transparency* can also be a 1d array to set varying transparency for symbols. - """ kwargs = self._preprocess(**kwargs) @@ -1083,7 +1077,6 @@ def contour(self, x=None, y=None, z=None, data=None, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) @@ -1159,7 +1152,6 @@ def basemap(self, **kwargs): {XY} {p} {t} - """ kwargs = self._preprocess(**kwargs) if not ("B" in kwargs or "L" in kwargs or "T" in kwargs): @@ -1216,7 +1208,6 @@ def logo(self, **kwargs): {V} {XY} {t} - """ kwargs = self._preprocess(**kwargs) with Session() as lib: @@ -1658,8 +1649,8 @@ def set_pointer(data_pointers, spec): 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`.""" + 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 e851211050d..4f111709a03 100644 --- a/pygmt/clib/conversion.py +++ b/pygmt/clib/conversion.py @@ -1,6 +1,4 @@ -""" -Functions to convert data types into ctypes friendly formats. -""" +"""Functions to convert data types into ctypes friendly formats.""" import numpy as np import pandas as pd @@ -80,7 +78,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( @@ -159,7 +156,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 @@ -201,7 +197,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") @@ -239,7 +234,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 ee9332e86be..25fa10b30a4 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 7d53566cb51..b3c67d2311d 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 sys import ctypes as ctp @@ -133,7 +134,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.") @@ -141,14 +141,12 @@ def session_pointer(self): @session_pointer.setter def session_pointer(self, session): - """ - Set the session void pointer. - """ + """Set the session void pointer.""" self._session_pointer = 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"), @@ -178,7 +176,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 @@ -203,7 +200,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``. @@ -223,7 +220,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 @@ -278,7 +274,6 @@ def get_libgmt_func(self, name, argtypes=None, restype=None): ... >>> type(func) ._FuncPtr'> - """ if not hasattr(self, "_libgmt"): self._libgmt = load_libgmt() @@ -314,7 +309,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 @@ -344,8 +338,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) @@ -447,7 +443,6 @@ def get_default(self, name): ------ GMTCLibError If the parameter doesn't exist. - """ c_get_default = self.get_libgmt_func( "GMT_Get_Default", @@ -490,7 +485,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", @@ -548,7 +542,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", @@ -718,7 +711,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: @@ -772,7 +764,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", @@ -834,7 +825,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", @@ -897,7 +887,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", @@ -951,7 +940,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", @@ -1048,7 +1036,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", @@ -1145,7 +1132,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 @@ -1259,7 +1245,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 @@ -1343,7 +1328,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] @@ -1427,7 +1411,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 80c2b1b6217..ddd3161f141 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 @@ -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 b56e0ce0e1e..2c419167355 100644 --- a/pygmt/datasets/tutorial.py +++ b/pygmt/datasets/tutorial.py @@ -1,6 +1,4 @@ -""" -Functions to load sample data from the GMT tutorials. -""" +"""Functions to load sample data from the GMT tutorials.""" import pandas as pd from .. import which @@ -22,7 +20,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+") @@ -99,7 +96,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/exceptions.py b/pygmt/exceptions.py index 6b72b8cb919..33267809d00 100644 --- a/pygmt/exceptions.py +++ b/pygmt/exceptions.py @@ -5,48 +5,33 @@ class GMTError(Exception): - """ - Base class for all GMT related errors. - """ + """Base class for all GMT related errors.""" class GMTOSError(GMTError): - """ - Unsupported operating system. - """ + """Unsupported operating system.""" class GMTCLibError(GMTError): - """ - Error encountered when running a function from the GMT shared library. - """ + """Error encountered when running a function from the GMT shared + library.""" class GMTCLibNotFoundError(GMTCLibError): - """ - Could not find the GMT shared library. - """ + """Could not find the GMT shared library.""" class GMTCLibNoSessionError(GMTCLibError): - """ - Tried to access GMT API without a currently open GMT session. - """ + """Tried to access GMT API without a currently open GMT session.""" class GMTInvalidInput(GMTError): - """ - Raised when the input of a function/method is invalid. - """ + """Raised when the input of a function/method is invalid.""" class GMTVersionError(GMTError): - """ - Raised when an incompatible version of GMT is being used. - """ + """Raised when an incompatible version of GMT is being used.""" class GMTImageComparisonFailure(AssertionError): - """ - Raised when a comparison between two images fails. - """ + """Raised when a comparison between two images fails.""" diff --git a/pygmt/figure.py b/pygmt/figure.py index 8d4c98a8cd0..be97ac06704 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -1,6 +1,4 @@ -""" -Define the Figure class that handles all plotting. -""" +"""Define the Figure class that handles all plotting.""" import os from tempfile import TemporaryDirectory import base64 @@ -59,7 +57,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): @@ -89,16 +86,14 @@ def _activate_figure(self): lib.call_module("figure", "{} {}".format(self._name, fmt)) def _preprocess(self, **kwargs): - """ - Call the ``figure`` module before each plotting command to ensure we're - plotting to this particular figure. - """ + """Call the ``figure`` module before each plotting command to ensure + we're plotting to this particular figure.""" self._activate_figure() return 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() @@ -164,7 +159,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 @@ -209,7 +203,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") @@ -264,7 +257,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. @@ -347,7 +339,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) @@ -360,6 +351,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) @@ -368,6 +360,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 adae7524576..7b4044f2e6a 100644 --- a/pygmt/filtering.py +++ b/pygmt/filtering.py @@ -1,6 +1,4 @@ -""" -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 .clib import Session diff --git a/pygmt/gridding.py b/pygmt/gridding.py index 2801cd4a406..c6103570aec 100644 --- a/pygmt/gridding.py +++ b/pygmt/gridding.py @@ -1,6 +1,4 @@ -""" -GMT modules for Gridding of Data Tables -""" +"""GMT modules for Gridding of Data Tables.""" import xarray as xr from .clib import Session diff --git a/pygmt/gridops.py b/pygmt/gridops.py index 845fbee65ff..643a5f4fe14 100644 --- a/pygmt/gridops.py +++ b/pygmt/gridops.py @@ -1,6 +1,4 @@ -""" -GMT modules for grid operations -""" +"""GMT modules for grid operations.""" import xarray as xr @@ -229,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/__init__.py b/pygmt/helpers/__init__.py index b8a6958816d..b45e7e16d54 100644 --- a/pygmt/helpers/__init__.py +++ b/pygmt/helpers/__init__.py @@ -1,6 +1,5 @@ -""" -Functions, classes, decorators, and context managers to help wrap GMT modules. -""" +"""Functions, classes, decorators, and context managers to help wrap GMT +modules.""" from .decorators import fmt_docstring, use_alias, kwargs_to_strings from .tempfile import GMTTempFile, unique_name from .utils import ( diff --git a/pygmt/helpers/decorators.py b/pygmt/helpers/decorators.py index 28e8fafd896..37f29bf4daf 100644 --- a/pygmt/helpers/decorators.py +++ b/pygmt/helpers/decorators.py @@ -186,7 +186,6 @@ def fmt_docstring(module_func): - J = projection - R = region - """ filler_text = {} @@ -251,15 +250,11 @@ def use_alias(**aliases): """ def alias_decorator(module_func): - """ - Decorator that replaces the aliases for arguments. - """ + """Decorator that replaces the aliases for arguments.""" @functools.wraps(module_func) def new_module(*args, **kwargs): - """ - New module that parses and replaces the registered aliases. - """ + """New module that parses and replaces the registered aliases.""" for arg, alias in aliases.items(): if alias in kwargs and arg in kwargs: raise GMTInvalidInput( @@ -358,7 +353,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", @@ -382,11 +376,11 @@ 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(): @@ -431,7 +425,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..ae252c8f179 100644 --- a/pygmt/helpers/tempfile.py +++ b/pygmt/helpers/tempfile.py @@ -1,6 +1,4 @@ -""" -Utilities for dealing with temporary file management. -""" +"""Utilities for dealing with temporary file management.""" import os import uuid from tempfile import NamedTemporaryFile @@ -19,7 +17,6 @@ def unique_name(): ------- name : str A unique name generated by :func:`uuid.uuid4` - """ return uuid.uuid4().hex @@ -103,6 +100,5 @@ def loadtxt(self, **kwargs): ------- ndarray Data read from the text file. - """ return np.loadtxt(self.name, **kwargs) diff --git a/pygmt/helpers/testing.py b/pygmt/helpers/testing.py index 4a324a605d2..09f7aee5d81 100644 --- a/pygmt/helpers/testing.py +++ b/pygmt/helpers/testing.py @@ -1,6 +1,4 @@ -""" -Helper functions for testing. -""" +"""Helper functions for testing.""" import inspect import os import string diff --git a/pygmt/helpers/utils.py b/pygmt/helpers/utils.py index 7472e9f410f..0ee6dad6ac9 100644 --- a/pygmt/helpers/utils.py +++ b/pygmt/helpers/utils.py @@ -1,6 +1,4 @@ -""" -Utilities and common tasks for wrapping the GMT modules. -""" +"""Utilities and common tasks for wrapping the GMT modules.""" import sys import shutil import subprocess @@ -55,7 +53,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.") @@ -98,7 +95,6 @@ def dummy_context(arg): ... print(temp) ... some argument - """ yield arg @@ -145,7 +141,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): @@ -191,7 +186,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) @@ -207,7 +201,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 e74deb82c3a..4d68ab44889 100644 --- a/pygmt/mathops.py +++ b/pygmt/mathops.py @@ -1,6 +1,4 @@ -""" -GMT modules for Mathematical operations on tables or grids -""" +"""GMT modules for Mathematical operations on tables or grids.""" from .clib import Session from .exceptions import GMTInvalidInput from .helpers import build_arg_string, fmt_docstring, kwargs_to_strings, use_alias diff --git a/pygmt/modules.py b/pygmt/modules.py index c733bb58790..82fc1a2122c 100644 --- a/pygmt/modules.py +++ b/pygmt/modules.py @@ -1,6 +1,4 @@ -""" -Non-plot GMT modules. -""" +"""Non-plot GMT modules.""" import numpy as np import xarray as xr @@ -37,7 +35,6 @@ def grdinfo(grid, **kwargs): ------- info : str A string with information about the grid. - """ kind = data_kind(grid, None, None) with GMTTempFile() as outfile: @@ -181,7 +178,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]) @@ -296,9 +292,7 @@ def __init__(self, xarray_obj): @property def registration(self): - """ - Registration type of the grid, either Gridline (0) or Pixel (1). - """ + """Registration type of the grid, either Gridline (0) or Pixel (1).""" return self._registration @registration.setter @@ -313,10 +307,8 @@ def registration(self, value): @property def gtype(self): - """ - Coordinate system type of the grid, either Cartesian (0) or Geographic - (1). - """ + """Coordinate system type of the grid, either Cartesian (0) or + Geographic (1).""" return self._gtype @gtype.setter diff --git a/pygmt/sampling.py b/pygmt/sampling.py index 1ae93db24f3..1e8d33392c3 100644 --- a/pygmt/sampling.py +++ b/pygmt/sampling.py @@ -1,6 +1,4 @@ -""" -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 .clib import Session @@ -67,7 +65,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/session_management.py b/pygmt/session_management.py index e814daf4fb8..c9029c70569 100644 --- a/pygmt/session_management.py +++ b/pygmt/session_management.py @@ -1,6 +1,4 @@ -""" -Modern mode session management modules. -""" +"""Modern mode session management modules.""" from .clib import Session diff --git a/pygmt/sphinx_gallery.py b/pygmt/sphinx_gallery.py index 3de8300a0bd..2f389ec8e65 100644 --- a/pygmt/sphinx_gallery.py +++ b/pygmt/sphinx_gallery.py @@ -1,6 +1,4 @@ -""" -Utilities for using pygmt with sphinx-gallery. -""" +"""Utilities for using pygmt with sphinx-gallery.""" try: from sphinx_gallery.scrapers import figure_rst except ImportError: @@ -20,10 +18,8 @@ class PyGMTScraper: # pylint: disable=too-few-public-methods """ def __call__(self, block, block_vars, gallery_conf): - """ - Called by sphinx-gallery to save the figures generated after running - code. - """ + """Called by sphinx-gallery to save the figures generated after running + code.""" image_names = list() image_path_iterator = block_vars["image_path_iterator"] figures = SHOWED_FIGURES diff --git a/pygmt/tests/test_accessor.py b/pygmt/tests/test_accessor.py index 0eb88b7fecd..cf9f9518b6d 100644 --- a/pygmt/tests/test_accessor.py +++ b/pygmt/tests/test_accessor.py @@ -1,6 +1,4 @@ -""" -Test the behaviour of the GMTDataArrayAccessor class -""" +"""Test the behaviour of the GMTDataArrayAccessor class.""" import pytest import xarray as xr @@ -9,10 +7,8 @@ def test_accessor_gridline_cartesian(): - """ - Check that a grid returns a registration value of 0 when Gridline - registered, and a gtype value of 1 when using Geographic coordinates. - """ + """Check that a grid returns a registration value of 0 when Gridline + registered, and a gtype value of 1 when using Geographic coordinates.""" fname = which(fname="@test.dat.nc", download="a") grid = xr.open_dataarray(fname) assert grid.gmt.registration == 0 # gridline registration @@ -20,10 +16,8 @@ def test_accessor_gridline_cartesian(): def test_accessor_pixel_geographic(): - """ - Check that a grid returns a registration value of 1 when Pixel registered, - and a gtype value of 0 when using Cartesian coordinates. - """ + """Check that a grid returns a registration value of 1 when Pixel + registered, and a gtype value of 0 when using Cartesian coordinates.""" fname = which(fname="@earth_relief_01d_p", download="a") grid = xr.open_dataarray(fname) assert grid.gmt.registration == 1 # pixel registration @@ -31,10 +25,8 @@ def test_accessor_pixel_geographic(): def test_accessor_set_pixel_registration(): - """ - Check that we can set a grid to be Pixel registered with a registration - value of 1. - """ + """Check that we can set a grid to be Pixel registered with a registration + value of 1.""" grid = xr.DataArray(data=[[0.1, 0.2], [0.3, 0.4]]) assert grid.gmt.registration == 0 # default to gridline registration grid.gmt.registration = 1 # set to pixel registration @@ -42,11 +34,9 @@ def test_accessor_set_pixel_registration(): def test_accessor_set_geographic_cartesian_roundtrip(): - """ - Check that we can set a grid to switch between the default Cartesian + """Check that we can set a grid to switch between the default Cartesian coordinate type using a gtype of 1, set it to Geographic 0, and then back - to Cartesian again 1. - """ + to Cartesian again 1.""" grid = xr.DataArray(data=[[0.1, 0.2], [0.3, 0.4]]) assert grid.gmt.gtype == 0 # default to cartesian coordinate type grid.gmt.gtype = 1 # set to geographic type @@ -56,9 +46,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]]) with pytest.raises(GMTInvalidInput): diff --git a/pygmt/tests/test_basemap.py b/pygmt/tests/test_basemap.py index bc0d43059b1..03e8b2305af 100644 --- a/pygmt/tests/test_basemap.py +++ b/pygmt/tests/test_basemap.py @@ -1,6 +1,4 @@ -""" -Tests fig.basemap. -""" +"""Tests fig.basemap.""" import pytest from .. import Figure @@ -9,7 +7,7 @@ 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") @@ -17,7 +15,7 @@ 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 @@ -25,7 +23,7 @@ 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 @@ -33,7 +31,7 @@ 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", @@ -47,7 +45,7 @@ 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"] @@ -57,7 +55,7 @@ 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") @@ -68,7 +66,7 @@ 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 @@ -76,7 +74,7 @@ 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 diff --git a/pygmt/tests/test_blockmedian.py b/pygmt/tests/test_blockmedian.py index f63fd90a5d8..9398d65fb92 100644 --- a/pygmt/tests/test_blockmedian.py +++ b/pygmt/tests/test_blockmedian.py @@ -1,6 +1,4 @@ -""" -Tests for blockmedian -""" +"""Tests for blockmedian.""" import os import numpy.testing as npt @@ -14,9 +12,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]) assert isinstance(output, pd.DataFrame) @@ -28,10 +24,8 @@ 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 - """ + """Run blockmedian using table input that is not a pandas.DataFrame but + still a matrix.""" dataframe = load_sample_bathymetry() invalid_table = dataframe.values assert data_kind(invalid_table) == "matrix" @@ -40,10 +34,8 @@ 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 - """ + """Run blockmedian using table input that is not a pandas.DataFrame or file + but a grid.""" dataframe = load_sample_bathymetry() invalid_table = dataframe.bathymetry.to_xarray() assert data_kind(invalid_table) == "grid" @@ -52,9 +44,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( table="@tut_ship.xyz", @@ -72,8 +62,6 @@ 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 1d15be613fe..0c13ddf7afc 100644 --- a/pygmt/tests/test_clib.py +++ b/pygmt/tests/test_clib.py @@ -1,7 +1,5 @@ # pylint: disable=protected-access -""" -Test the wrappers for the C API. -""" +"""Test the wrappers for the C API.""" import os from contextlib import contextmanager @@ -46,9 +44,7 @@ def mock(session, func, returns=None, mock_func=None): if mock_func is None: def mock_api_function(*args): # pylint: disable=unused-argument - """ - A mock GMT API function that always returns a given value. - """ + """A mock GMT API function that always returns a given value.""" return returns mock_func = mock_api_function @@ -56,9 +52,7 @@ def mock_api_function(*args): # pylint: disable=unused-argument get_libgmt_func = session.get_libgmt_func def mock_get_libgmt_func(name, argtypes=None, restype=None): - """ - Return our mock function. - """ + """Return our mock function.""" if name == func: return mock_func return get_libgmt_func(name, argtypes, restype) @@ -71,7 +65,7 @@ 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 @@ -82,7 +76,7 @@ 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") @@ -106,7 +100,7 @@ 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): @@ -118,7 +112,7 @@ 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() @@ -130,7 +124,7 @@ 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: @@ -142,21 +136,21 @@ 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") @@ -166,7 +160,7 @@ 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): @@ -176,7 +170,7 @@ 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) @@ -184,7 +178,7 @@ 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: @@ -195,7 +189,7 @@ 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", @@ -221,7 +215,7 @@ 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( @@ -241,7 +235,7 @@ 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( @@ -253,7 +247,7 @@ 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( @@ -266,7 +260,8 @@ 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: @@ -303,7 +298,7 @@ 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: @@ -332,10 +327,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", "GMT_IS_POINT", @@ -364,7 +357,7 @@ 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", @@ -378,7 +371,7 @@ 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: @@ -399,10 +392,8 @@ def test_virtualfile_from_vectors(): @pytest.mark.parametrize("dtype", [np.str, np.object]) 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 - """ + """Test passing in one column with string or object dtype into virtual file + dataset.""" size = 5 x = np.arange(size, dtype=np.int32) y = np.arange(size, size * 2, 1, dtype=np.int32) @@ -418,10 +409,8 @@ def test_virtualfile_from_vectors_one_string_or_object_column(dtype): @pytest.mark.parametrize("dtype", [np.str, np.object]) 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 - """ + """Test passing in two columns of string or object dtype into virtual file + dataset.""" size = 5 x = np.arange(size, dtype=np.int32) y = np.arange(size, size * 2, 1, dtype=np.int32) @@ -439,7 +428,7 @@ 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: @@ -457,7 +446,7 @@ 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: @@ -467,7 +456,7 @@ 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: @@ -485,7 +474,7 @@ 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: @@ -506,7 +495,7 @@ 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: @@ -533,7 +522,7 @@ 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)) @@ -551,7 +540,7 @@ 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: @@ -559,7 +548,8 @@ 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() @@ -586,7 +576,7 @@ 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 @@ -605,7 +595,7 @@ 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) @@ -618,7 +608,7 @@ 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) @@ -631,7 +621,7 @@ 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) @@ -644,7 +634,8 @@ 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) @@ -657,7 +648,7 @@ 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) @@ -669,7 +660,7 @@ 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) @@ -679,7 +670,8 @@ 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 @@ -687,14 +679,14 @@ 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: @@ -702,7 +694,7 @@ 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 @@ -717,11 +709,11 @@ 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 9c11cb698c1..f1b968c541d 100644 --- a/pygmt/tests/test_clib_loading.py +++ b/pygmt/tests/test_clib_loading.py @@ -1,6 +1,4 @@ -""" -Test the functions that load libgmt -""" +"""Test the functions that load libgmt.""" import os import pytest @@ -9,18 +7,18 @@ 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 +34,7 @@ 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 c4ec764396e..6101a8764b1 100644 --- a/pygmt/tests/test_clib_put_matrix.py +++ b/pygmt/tests/test_clib_put_matrix.py @@ -1,6 +1,4 @@ -""" -Test the functions that put matrix data into GMT. -""" +"""Test the functions that put matrix data into GMT.""" import numpy as np import numpy.testing as npt import pytest @@ -14,7 +12,7 @@ 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: @@ -45,7 +43,7 @@ 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. @@ -56,7 +54,8 @@ 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 ce8816b66e8..ea2dd8fd844 100644 --- a/pygmt/tests/test_clib_put_strings.py +++ b/pygmt/tests/test_clib_put_strings.py @@ -1,6 +1,4 @@ -""" -Test the functions that put string data into GMT. -""" +"""Test the functions that put string data into GMT.""" import numpy as np import numpy.testing as npt import pytest @@ -15,7 +13,7 @@ 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", @@ -53,7 +51,8 @@ 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 ec78e1cc8ee..0ef3a7b70f2 100644 --- a/pygmt/tests/test_clib_put_vector.py +++ b/pygmt/tests/test_clib_put_vector.py @@ -1,6 +1,4 @@ -""" -Test the functions that put vector data into GMT. -""" +"""Test the functions that put vector data into GMT.""" import itertools import numpy as np import numpy.testing as npt @@ -12,7 +10,7 @@ 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 +46,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 +87,7 @@ 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 +101,7 @@ 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 +115,7 @@ 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 1f83f94d71e..cb42273f4c2 100644 --- a/pygmt/tests/test_coast.py +++ b/pygmt/tests/test_coast.py @@ -1,6 +1,4 @@ -""" -Tests for coast -""" +"""Tests for coast.""" import pytest from .. import Figure @@ -9,7 +7,7 @@ @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 +26,7 @@ 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 +38,7 @@ def test_coast_iceland(): @pytest.mark.mpl_image_compare def test_coast_aliases(): - "Test that all aliases work" + """Test that all aliases work.""" fig = Figure() fig.coast( region="-30/30/-40/40", @@ -59,7 +57,7 @@ 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], diff --git a/pygmt/tests/test_colorbar.py b/pygmt/tests/test_colorbar.py index f03002eb078..dc6994f750e 100644 --- a/pygmt/tests/test_colorbar.py +++ b/pygmt/tests/test_colorbar.py @@ -1,6 +1,4 @@ -""" -Tests colorbar -""" +"""Tests colorbar.""" import pytest from .. import Figure @@ -9,9 +7,8 @@ @pytest.mark.mpl_image_compare def test_colorbar_using_paper_coordinates(): - """ - Create colorbar positioned at 0cm,0cm with length 1cm and width 0.5cm. - """ + """Create colorbar positioned at 0cm,0cm with length 1cm and width + 0.5cm.""" fig = Figure() fig.colorbar(cmap="rainbow", position="x0c/0c+w1c/0.5c") return fig @@ -19,9 +16,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") return fig @@ -29,9 +25,7 @@ def test_colorbar_using_paper_coordinates_horizontal(): @pytest.mark.mpl_image_compare def test_colorbar_positioned_using_map_coordinates(): - """ - Create colorbar positioned at longitude,latitude 3,6 with length 2cm. - """ + """Create colorbar positioned at longitude,latitude 3,6 with length 2cm.""" fig = Figure() fig.basemap(region=[2, 4, 6, 8], projection="t0/2c", frame=True) fig.colorbar(cmap="rainbow", position="g3/6+w2c") @@ -40,9 +34,7 @@ def test_colorbar_positioned_using_map_coordinates(): @check_figures_equal() def test_colorbar_positioned_using_justification_code(): - """ - Create colorbar at Top Center inside the map frame with length 2cm. - """ + """Create colorbar at Top Center inside the map frame with length 2cm.""" fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image fig_ref.basemap(R="2/4/6/8", J="t0/2c", B="") @@ -55,9 +47,7 @@ def test_colorbar_positioned_using_justification_code(): @pytest.mark.mpl_image_compare def test_colorbar_positioned_using_normalized_coords(): - """ - Create colorbar at normalized coordinates 0.75,0.25 with length 2cm. - """ + """Create colorbar at normalized coordinates 0.75,0.25 with length 2cm.""" fig = Figure() fig.basemap(region=[2, 4, 6, 8], projection="t0/2c", frame=True) fig.colorbar(cmap="rainbow", position="n0.75/0.25+w2c") @@ -66,9 +56,7 @@ def test_colorbar_positioned_using_normalized_coords(): @pytest.mark.mpl_image_compare def test_colorbar_box(): - """ - Create colorbar with box around it. - """ + """Create colorbar with box around it.""" fig = Figure() fig.colorbar(cmap="rainbow", box=True, position="x0c/0c+w1c/0.5c") return fig @@ -76,9 +64,7 @@ def test_colorbar_box(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_pen(): - """ - Create colorbar with box that has a different colored pen. - """ + """Create colorbar with box that has a different colored pen.""" fig = Figure() fig.colorbar(cmap="rainbow", box="+porange", position="x0c/0c+w1c/0.5c") return fig @@ -86,9 +72,7 @@ def test_colorbar_box_with_pen(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_fill(): - """ - Create colorbar with box that has a different colored fill. - """ + """Create colorbar with box that has a different colored fill.""" fig = Figure() fig.colorbar(cmap="rainbow", box="+gorange", position="x0c/0c+w1c/0.5c") return fig @@ -96,10 +80,8 @@ def test_colorbar_box_with_fill(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_clearance(): - """ - Create colorbar with box that has an x-clearance of 0.8cm and y-clearance - of 0.4cm. - """ + """Create colorbar with box that has an x-clearance of 0.8cm and + y-clearance of 0.4cm.""" fig = Figure() fig.colorbar(cmap="rainbow", box="+c0.8c/0.4c+porange", position="x0c/0c+w1c/0.5c") return fig @@ -107,10 +89,8 @@ def test_colorbar_box_with_clearance(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_secondary_border(): - """ - Create colorbar with box that has a secondary, inner border in addition to - the main primary, outer border. - """ + """Create colorbar with box that has a secondary, inner border in addition + to the main primary, outer border.""" fig = Figure() fig.colorbar(cmap="rainbow", box="+porange+imagenta", position="x0c/0c+w1c/0.5c") return fig @@ -118,9 +98,7 @@ def test_colorbar_box_with_secondary_border(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_rounded_corners(): - """ - Create colorbar with box that has rounded corners. - """ + """Create colorbar with box that has rounded corners.""" fig = Figure() fig.colorbar(cmap="rainbow", box="+porange+r", position="x0c/0c+w1c/0.5c") return fig @@ -128,9 +106,7 @@ def test_colorbar_box_with_rounded_corners(): @pytest.mark.mpl_image_compare def test_colorbar_box_with_offset_background(): - """ - Create colorbar with box and an offset background shaded region. - """ + """Create colorbar with box and an offset background shaded region.""" fig = Figure() fig.colorbar(cmap="rainbow", box="+s5p/-5p", position="x0c/0c+w1c/0.5c") return fig @@ -138,9 +114,7 @@ def test_colorbar_box_with_offset_background(): @pytest.mark.mpl_image_compare def test_colorbar_truncated_to_zlow_zhigh(): - """ - Create colorbar truncated to z-low and z-high. - """ + """Create colorbar truncated to z-low and z-high.""" fig = Figure() fig.colorbar(cmap="rainbow", truncate=[0.15, 0.85], position="x0c/0c+w2c/0.5c") return fig @@ -148,9 +122,7 @@ def test_colorbar_truncated_to_zlow_zhigh(): @pytest.mark.mpl_image_compare def test_colorbar_scaled_z_values(): - """ - Create colorbar with z-values scaled to 0.1x of the original CPT. - """ + """Create colorbar with z-values scaled to 0.1x of the original CPT.""" fig = Figure() fig.colorbar(cmap="rainbow", scale=0.1, position="x0c/0c+w2c/0.5c") return fig diff --git a/pygmt/tests/test_config.py b/pygmt/tests/test_config.py index 66c3e84f11a..f7058c895b4 100644 --- a/pygmt/tests/test_config.py +++ b/pygmt/tests/test_config.py @@ -1,6 +1,4 @@ -""" -Tests for gmt config -""" +"""Tests for gmt config.""" import pytest from .. import Figure, config @@ -8,9 +6,7 @@ @pytest.mark.mpl_image_compare def test_config(): - """ - Test if config works globally and locally. - """ + """Test if config works globally and locally.""" fig = Figure() # Change global settings of current figure config(FONT_ANNOT_PRIMARY="blue") @@ -44,7 +40,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() @@ -59,10 +57,8 @@ def test_config_font_one(): ) @pytest.mark.mpl_image_compare def test_config_font_annot(): - """ - Test that setting `FONT_ANNOT` config changes both `FONT_ANNOT_PRIMARY` and - `FONT_ANNOT_SECONDARY`. - """ + """Test that setting `FONT_ANNOT` config changes both `FONT_ANNOT_PRIMARY` + and `FONT_ANNOT_SECONDARY`.""" fig = Figure() with config(FONT_ANNOT="6p,red"): fig.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", T="mjTL+w4c+d4.5") @@ -72,10 +68,8 @@ def test_config_font_annot(): @pytest.mark.mpl_image_compare def test_config_format_time_map(): - """ - Test that setting `FORMAT_TIME_MAP` config changes both - `FORMAT_TIME_PRIMARY_MAP` and `FORMAT_TIME_SECONDARY_MAP`. - """ + """Test that setting `FORMAT_TIME_MAP` config changes both + `FORMAT_TIME_PRIMARY_MAP` and `FORMAT_TIME_SECONDARY_MAP`.""" fig = Figure() with config(FORMAT_TIME_MAP="abbreviation"): fig.basemap( @@ -89,10 +83,8 @@ def test_config_format_time_map(): @pytest.mark.mpl_image_compare def test_config_map_annot_offset(): - """ - Test that setting `MAP_ANNOT_OFFSET` config changes both - `MAP_ANNOT_OFFSET_PRIMARY` and `MAP_ANNOT_OFFSET_SECONDARY`. - """ + """Test that setting `MAP_ANNOT_OFFSET` config changes both + `MAP_ANNOT_OFFSET_PRIMARY` and `MAP_ANNOT_OFFSET_SECONDARY`.""" fig = Figure() with config(MAP_ANNOT_OFFSET="15p"): fig.basemap( @@ -106,10 +98,8 @@ def test_config_map_annot_offset(): @pytest.mark.mpl_image_compare def test_config_map_grid_cross_size(): - """ - Test that setting `MAP_GRID_CROSS_SIZE` config changes both - `MAP_GRID_CROSS_SIZE_PRIMARY` and `MAP_GRID_CROSS_SIZE_SECONDARY`. - """ + """Test that setting `MAP_GRID_CROSS_SIZE` config changes both + `MAP_GRID_CROSS_SIZE_PRIMARY` and `MAP_GRID_CROSS_SIZE_SECONDARY`.""" fig = Figure() with config(MAP_GRID_CROSS_SIZE="3p"): fig.basemap( @@ -123,10 +113,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"): fig.basemap( @@ -140,10 +128,8 @@ def test_config_map_grid_pen(): @pytest.mark.mpl_image_compare def test_config_map_tick_length(): - """ - Test that setting `MAP_TICK_LENGTH` config changes both - `MAP_TICK_LENGTH_PRIMARY` and `MAP_TICK_LENGTH_SECONDARY`. - """ + """Test that setting `MAP_TICK_LENGTH` config changes both + `MAP_TICK_LENGTH_PRIMARY` and `MAP_TICK_LENGTH_SECONDARY`.""" fig = Figure() with config(MAP_TICK_LENGTH="5p"): fig.basemap( @@ -157,10 +143,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"): fig.basemap( diff --git a/pygmt/tests/test_contour.py b/pygmt/tests/test_contour.py index 0fb80481bf5..e0e8ced47c9 100644 --- a/pygmt/tests/test_contour.py +++ b/pygmt/tests/test_contour.py @@ -1,7 +1,5 @@ # pylint: disable=redefined-outer-name -""" -Tests contour. -""" +"""Tests contour.""" import os from itertools import product @@ -18,18 +16,18 @@ @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() @@ -68,7 +66,7 @@ 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]) @@ -83,7 +81,7 @@ 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 @@ -91,7 +89,7 @@ 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 ae99b3b7922..eb129dd615d 100644 --- a/pygmt/tests/test_datasets.py +++ b/pygmt/tests/test_datasets.py @@ -1,6 +1,4 @@ -""" -Test basic functionality for loading datasets. -""" +"""Test basic functionality for loading datasets.""" import numpy as np import numpy.testing as npt import pytest @@ -16,7 +14,7 @@ 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() @@ -29,7 +27,7 @@ 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() @@ -40,7 +38,7 @@ 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() @@ -53,13 +51,13 @@ 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: @@ -69,7 +67,7 @@ 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)) @@ -79,13 +77,13 @@ 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)) @@ -95,7 +93,7 @@ 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" ) @@ -110,12 +108,12 @@ 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 d3780a2eed2..222452806a3 100644 --- a/pygmt/tests/test_figure.py +++ b/pygmt/tests/test_figure.py @@ -1,7 +1,5 @@ -""" -Test the behaviors of the Figure class -Doesn't include the plotting commands, which have their own test files. -""" +"""Test the behaviors of the Figure class Doesn't include the plotting +commands, which have their own test files.""" import os import numpy as np @@ -13,7 +11,7 @@ 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) @@ -21,7 +19,7 @@ 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) @@ -34,7 +32,7 @@ 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( @@ -46,7 +44,7 @@ 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" @@ -58,7 +56,7 @@ 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" @@ -74,11 +72,11 @@ 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() @@ -110,7 +108,8 @@ 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) @@ -119,7 +118,7 @@ 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 fee5e50d9db..e13598c334b 100644 --- a/pygmt/tests/test_grdcontour.py +++ b/pygmt/tests/test_grdcontour.py @@ -1,6 +1,4 @@ -""" -Test Figure.grdcontour -""" +"""Test Figure.grdcontour.""" import os import numpy as np @@ -18,15 +16,14 @@ @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") fig_ref.grdcontour("@earth_relief_01d_g", **kwargs) @@ -36,9 +33,8 @@ 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( interval="1000", @@ -54,7 +50,7 @@ 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() @@ -69,7 +65,7 @@ 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", @@ -84,7 +80,7 @@ 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 = { @@ -115,7 +111,7 @@ 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 d716bf43492..f29a9901b88 100644 --- a/pygmt/tests/test_grdcut.py +++ b/pygmt/tests/test_grdcut.py @@ -1,6 +1,4 @@ -""" -Tests for grdcut -""" +"""Tests for grdcut.""" import os import numpy as np import pytest @@ -14,12 +12,12 @@ @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(): - "grdcut 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 +27,7 @@ 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 +46,7 @@ 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 +55,7 @@ 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 +72,6 @@ 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 3e2b5b5ec44..8db4c94b5b7 100644 --- a/pygmt/tests/test_grdimage.py +++ b/pygmt/tests/test_grdimage.py @@ -1,6 +1,4 @@ -""" -Test Figure.grdimage -""" +"""Test Figure.grdimage.""" import sys import numpy as np import pytest @@ -18,15 +16,13 @@ @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) x = np.sin(np.deg2rad(longitude)) @@ -45,7 +41,7 @@ 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 +49,7 @@ 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 +58,7 @@ 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 +108,7 @@ 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 +118,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. @@ -138,10 +135,8 @@ def test_grdimage_over_dateline(xrgrid): @pytest.mark.parametrize("lon0", [0, 123, 180]) @pytest.mark.parametrize("proj_type", ["H", "W"]) def test_grdimage_central_meridians(grid, proj_type, lon0): - """ - Test that plotting a grid with different central meridians (lon0) using - Hammer (H) and Mollweide (W) projection systems work. - """ + """Test that plotting a grid with different central meridians (lon0) using + Hammer (H) and Mollweide (W) projection systems work.""" fig_ref, fig_test = Figure(), Figure() fig_ref.grdimage( "@earth_relief_01d_g", projection=f"{proj_type}{lon0}/15c", cmap="geo" @@ -159,11 +154,9 @@ def test_grdimage_central_meridians(grid, proj_type, lon0): @pytest.mark.parametrize("lon0", [0, 123, 180]) @pytest.mark.parametrize("proj_type", [pytest.param("Q", marks=pytest.mark.xfail), "S"]) def test_grdimage_central_meridians_and_standard_parallels(grid, proj_type, lon0, lat0): - """ - Test that plotting a grid with different central meridians (lon0) and + """Test that plotting a grid with different central meridians (lon0) and standard_parallels (lat0) using Cylindrical Equidistant (Q) and General - Stereographic (S) projection systems work. - """ + Stereographic (S) projection systems work.""" fig_ref, fig_test = Figure(), Figure() fig_ref.grdimage( "@earth_relief_01d_g", projection=f"{proj_type}{lon0}/{lat0}/15c", cmap="geo" diff --git a/pygmt/tests/test_grdinfo.py b/pygmt/tests/test_grdinfo.py index 6991000b668..b65c5cb3816 100644 --- a/pygmt/tests/test_grdinfo.py +++ b/pygmt/tests/test_grdinfo.py @@ -1,6 +1,4 @@ -""" -Tests for grdinfo -""" +"""Tests for grdinfo.""" import numpy as np import pytest @@ -10,19 +8,19 @@ 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 7f3e8816271..08460a0f5ae 100644 --- a/pygmt/tests/test_grdtrack.py +++ b/pygmt/tests/test_grdtrack.py @@ -1,6 +1,4 @@ -""" -Tests for grdtrack -""" +"""Tests for grdtrack.""" import os import numpy.testing as npt @@ -19,7 +17,7 @@ @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,10 +25,8 @@ def fixture_dataarray(): @pytest.mark.xfail(reason="The reason why it fails is unclear now") def test_grdtrack_input_dataframe_and_dataarray(dataarray): - """ - Run grdtrack by passing in a pandas.DataFrame and xarray.DataArray as - inputs - """ + """Run grdtrack by passing in a pandas.DataFrame and xarray.DataArray as + inputs.""" dataframe = load_ocean_ridge_points() output = grdtrack(points=dataframe, grid=dataarray, newcolname="bathymetry") @@ -43,9 +39,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") try: @@ -62,9 +56,8 @@ 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") @@ -77,9 +70,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,10 +88,8 @@ 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 - """ + """Run grdtrack using points input that is not a pandas.DataFrame (matrix) + or file.""" dataframe = load_ocean_ridge_points() invalid_points = dataframe.longitude.to_xarray() @@ -110,10 +99,8 @@ 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 - """ + """Run grdtrack using grid input that is not as xarray.DataArray (grid) or + file.""" dataframe = load_ocean_ridge_points() invalid_grid = dataarray.to_dataset() @@ -123,9 +110,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() with pytest.raises(GMTInvalidInput): @@ -133,9 +118,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") with pytest.raises(GMTInvalidInput): diff --git a/pygmt/tests/test_grdview.py b/pygmt/tests/test_grdview.py index f9166b57b90..1cecfb01615 100644 --- a/pygmt/tests/test_grdview.py +++ b/pygmt/tests/test_grdview.py @@ -1,6 +1,4 @@ -""" -Tests grdview -""" +"""Tests grdview.""" import pytest from .. import Figure, grdcut, which @@ -11,15 +9,13 @@ @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) yield tmpfile.name @@ -27,17 +23,13 @@ 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) @check_figures_equal() def test_grdview_grid_dataarray(gridfile, xrgrid): - """ - Run grdview by passing in a grid as an xarray.DataArray. - """ + """Run grdview by passing in a grid as an xarray.DataArray.""" fig_ref, fig_test = Figure(), Figure() fig_ref.grdview(grid=gridfile) fig_test.grdview(grid=xrgrid) @@ -46,9 +38,8 @@ def test_grdview_grid_dataarray(gridfile, xrgrid): @pytest.mark.mpl_image_compare def test_grdview_grid_file_with_region_subset(region): - """ - Run grdview by passing in a grid filename, and cropping it to a region. - """ + """Run grdview by passing in a grid filename, and cropping it to a + region.""" gridfile = which("@earth_relief_01d_g", download="a") fig = Figure() @@ -57,9 +48,7 @@ def test_grdview_grid_file_with_region_subset(region): def test_grdview_wrong_kind_of_grid(xrgrid): - """ - Run grdview using grid input that is not an xarray.DataArray or file. - """ + """Run grdview using grid input that is not an xarray.DataArray or file.""" dataset = xrgrid.to_dataset() # convert xarray.DataArray to xarray.Dataset assert data_kind(dataset) == "matrix" @@ -70,11 +59,9 @@ def test_grdview_wrong_kind_of_grid(xrgrid): @check_figures_equal() def test_grdview_with_perspective(gridfile, xrgrid): - """ - Run grdview by passing in a grid and setting a perspective viewpoint with - an azimuth from the SouthEast and an elevation angle 15 degrees from the - z-plane. - """ + """Run grdview by passing in a grid and setting a perspective viewpoint + with an azimuth from the SouthEast and an elevation angle 15 degrees from + the z-plane.""" fig_ref, fig_test = Figure(), Figure() fig_ref.grdview(grid=gridfile, perspective=[135, 15]) fig_test.grdview(grid=xrgrid, perspective=[135, 15]) @@ -83,11 +70,9 @@ def test_grdview_with_perspective(gridfile, xrgrid): @check_figures_equal() def test_grdview_with_perspective_and_zscale(gridfile, xrgrid): - """ - Run grdview by passing in a grid and setting a perspective viewpoint with - an azimuth from the SouthWest and an elevation angle 30 degrees from the - z-plane, plus a z-axis scaling factor of 0.005. - """ + """Run grdview by passing in a grid and setting a perspective viewpoint + with an azimuth from the SouthWest and an elevation angle 30 degrees from + the z-plane, plus a z-axis scaling factor of 0.005.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(perspective=[225, 30], zscale=0.005) fig_ref.grdview(grid=gridfile, **kwargs) @@ -97,11 +82,9 @@ def test_grdview_with_perspective_and_zscale(gridfile, xrgrid): @check_figures_equal() def test_grdview_with_perspective_and_zsize(gridfile, xrgrid): - """ - Run grdview by passing in a grid and setting a perspective viewpoint with - an azimuth from the SouthWest and an elevation angle 30 degrees from the - z-plane, plus a z-axis size of 10cm. - """ + """Run grdview by passing in a grid and setting a perspective viewpoint + with an azimuth from the SouthWest and an elevation angle 30 degrees from + the z-plane, plus a z-axis size of 10cm.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(perspective=[225, 30], zsize="10c") fig_ref.grdview(grid=gridfile, **kwargs) @@ -111,10 +94,8 @@ def test_grdview_with_perspective_and_zsize(gridfile, xrgrid): @check_figures_equal() def test_grdview_with_cmap_for_image_plot(gridfile, xrgrid): - """ - Run grdview by passing in a grid and setting a colormap for producing an - image plot. - """ + """Run grdview by passing in a grid and setting a colormap for producing an + image plot.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(cmap="oleron", surftype="i") fig_ref.grdview(grid=gridfile, **kwargs) @@ -124,10 +105,8 @@ def test_grdview_with_cmap_for_image_plot(gridfile, xrgrid): @check_figures_equal() def test_grdview_with_cmap_for_surface_monochrome_plot(gridfile, xrgrid): - """ - Run grdview by passing in a grid and setting a colormap for producing a - surface monochrome plot. - """ + """Run grdview by passing in a grid and setting a colormap for producing a + surface monochrome plot.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(cmap="oleron", surftype="s+m") fig_ref.grdview(grid=gridfile, **kwargs) @@ -137,10 +116,8 @@ def test_grdview_with_cmap_for_surface_monochrome_plot(gridfile, xrgrid): @check_figures_equal() def test_grdview_with_cmap_for_perspective_surface_plot(gridfile, xrgrid): - """ - Run grdview by passing in a grid and setting a colormap for producing a - surface plot with a 3D perspective viewpoint. - """ + """Run grdview by passing in a grid and setting a colormap for producing a + surface plot with a 3D perspective viewpoint.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(cmap="oleron", surftype="s", perspective=[225, 30], zscale=0.005) fig_ref.grdview(grid=gridfile, **kwargs) @@ -150,10 +127,8 @@ def test_grdview_with_cmap_for_perspective_surface_plot(gridfile, xrgrid): @check_figures_equal() def test_grdview_on_a_plane(gridfile, xrgrid): - """ - Run grdview by passing in a grid and plotting it on a z-plane, while - setting a 3D perspective viewpoint. - """ + """Run grdview by passing in a grid and plotting it on a z-plane, while + setting a 3D perspective viewpoint.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(plane=-4000, perspective=[225, 30], zscale=0.005) fig_ref.grdview(grid=gridfile, **kwargs) @@ -163,10 +138,9 @@ def test_grdview_on_a_plane(gridfile, xrgrid): @check_figures_equal() def test_grdview_on_a_plane_with_colored_frontal_facade(gridfile, xrgrid): - """ - Run grdview by passing in a grid and plotting it on a z-plane whose frontal - facade is colored gray, while setting a 3D perspective viewpoint. - """ + """Run grdview by passing in a grid and plotting it on a z-plane whose + frontal facade is colored gray, while setting a 3D perspective + viewpoint.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(plane="-4000+ggray", perspective=[225, 30], zscale=0.005) fig_ref.grdview(grid=gridfile, **kwargs) @@ -176,10 +150,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)}" kwargs = dict( @@ -195,10 +167,8 @@ def test_grdview_with_perspective_and_zaxis_frame(gridfile, xrgrid, region): @check_figures_equal() def test_grdview_surface_plot_styled_with_contourpen(gridfile, xrgrid): - """ - Run grdview by passing in a grid with styled contour lines plotted on top - of a surface plot. - """ + """Run grdview by passing in a grid with styled contour lines plotted on + top of a surface plot.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(cmap="relief", surftype="s", contourpen="0.5p,black,dash") fig_ref.grdview(grid=gridfile, **kwargs) @@ -208,10 +178,8 @@ def test_grdview_surface_plot_styled_with_contourpen(gridfile, xrgrid): @check_figures_equal() def test_grdview_surface_mesh_plot_styled_with_meshpen(gridfile, xrgrid): - """ - Run grdview by passing in a grid with styled mesh lines plotted on top of a - surface mesh plot. - """ + """Run grdview by passing in a grid with styled mesh lines plotted on top + of a surface mesh plot.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict(cmap="relief", surftype="sm", meshpen="0.5p,black,dash") fig_ref.grdview(grid=gridfile, **kwargs) @@ -221,10 +189,8 @@ def test_grdview_surface_mesh_plot_styled_with_meshpen(gridfile, xrgrid): @check_figures_equal() def test_grdview_on_a_plane_styled_with_facadepen(gridfile, xrgrid): - """ - Run grdview by passing in a grid and plotting it on a z-plane with styled - lines for the frontal facade. - """ + """Run grdview by passing in a grid and plotting it on a z-plane with + styled lines for the frontal facade.""" fig_ref, fig_test = Figure(), Figure() kwargs = dict( plane=-4000, perspective=[225, 30], zscale=0.005, facadepen="0.5p,blue,dash" @@ -236,10 +202,8 @@ def test_grdview_on_a_plane_styled_with_facadepen(gridfile, xrgrid): @check_figures_equal() def test_grdview_drapegrid_dataarray(gridfile, xrgrid): - """ - Run grdview by passing in both a grid and drapegrid as an xarray.DataArray, - setting a colormap for producing an image plot. - """ + """Run grdview by passing in both a grid and drapegrid as an + xarray.DataArray, setting a colormap for producing an image plot.""" drapegrid = 1.1 * xrgrid fig_ref, fig_test = Figure(), Figure() @@ -249,9 +213,8 @@ def test_grdview_drapegrid_dataarray(gridfile, xrgrid): def test_grdview_wrong_kind_of_drapegrid(xrgrid): - """ - Run grdview using drapegrid input that is not an xarray.DataArray or file. - """ + """Run grdview using drapegrid input that is not an xarray.DataArray or + file.""" dataset = xrgrid.to_dataset() # convert xarray.DataArray to xarray.Dataset assert data_kind(dataset) == "matrix" diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index 66b61456376..359e73f3391 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -1,6 +1,4 @@ -""" -Tests the helper functions/classes/etc used in wrapping GMT -""" +"""Tests the helper functions/classes/etc used in wrapping GMT.""" import os import pytest @@ -22,29 +20,29 @@ ], ) 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 @@ -53,7 +51,7 @@ 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 @@ -61,7 +59,7 @@ 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: @@ -69,7 +67,8 @@ 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") @@ -85,7 +84,7 @@ 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") diff --git a/pygmt/tests/test_image.py b/pygmt/tests/test_image.py index 1bc0e1ffeea..fb86e8a3494 100644 --- a/pygmt/tests/test_image.py +++ b/pygmt/tests/test_image.py @@ -1,6 +1,4 @@ -""" -Tests image. -""" +"""Tests image.""" import os import sys @@ -15,7 +13,7 @@ @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 e4ce734f7e6..30a626279e2 100644 --- a/pygmt/tests/test_info.py +++ b/pygmt/tests/test_info.py @@ -1,6 +1,4 @@ -""" -Tests for gmtinfo -""" +"""Tests for gmtinfo.""" import os import numpy as np @@ -17,7 +15,7 @@ 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 " @@ -29,7 +27,7 @@ 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 = ( @@ -43,7 +41,7 @@ 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], @@ -62,7 +60,7 @@ 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={ @@ -78,7 +76,7 @@ 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 = ( @@ -88,14 +86,14 @@ 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] @@ -103,13 +101,13 @@ 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, @@ -124,21 +122,19 @@ 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]) def test_info_fails(): - """ - Make sure info raises an exception if not given either a file name, pandas - DataFrame, or numpy ndarray - """ + """Make sure info raises an exception if not given either a file name, + pandas 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 2044e7bb2a7..b1343818174 100644 --- a/pygmt/tests/test_legend.py +++ b/pygmt/tests/test_legend.py @@ -1,6 +1,4 @@ -""" -Tests for legend -""" +"""Tests for legend.""" import pytest from .. import Figure @@ -11,9 +9,7 @@ @pytest.mark.mpl_image_compare def test_legend_position(): - """ - Try positioning with each of the four legend coordinate systems. - """ + """Try positioning with each of the four legend coordinate systems.""" fig = Figure() @@ -31,9 +27,7 @@ def test_legend_position(): @pytest.mark.mpl_image_compare def test_legend_default_position(): - """ - Try using the default legend position. - """ + """Try using the default legend position.""" fig = Figure() @@ -47,9 +41,7 @@ def test_legend_default_position(): @check_figures_equal() def test_legend_entries(): - """ - Test different marker types/shapes. - """ + """Test different marker types/shapes.""" fig_ref, fig_test = Figure(), Figure() # Use single-character arguments for the reference image @@ -85,9 +77,7 @@ def test_legend_entries(): @pytest.mark.mpl_image_compare def test_legend_specfile(): - """ - Test specfile functionality. - """ + """Test specfile functionality.""" specfile_contents = """ G -0.1i @@ -130,9 +120,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): fig.legend(spec=["@Table_5_11.txt"]) diff --git a/pygmt/tests/test_logo.py b/pygmt/tests/test_logo.py index 6cfc7f4cd0e..c82a11eb8d2 100644 --- a/pygmt/tests/test_logo.py +++ b/pygmt/tests/test_logo.py @@ -1,13 +1,11 @@ -""" -Tests for fig.logo -""" +"""Tests for fig.logo.""" from .. import Figure from ..helpers.testing import check_figures_equal @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 +15,7 @@ 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 70443ee1b14..3acaa8bcf29 100644 --- a/pygmt/tests/test_makecpt.py +++ b/pygmt/tests/test_makecpt.py @@ -1,6 +1,4 @@ -""" -Tests for makecpt -""" +"""Tests for makecpt.""" import os import numpy as np @@ -18,27 +16,25 @@ @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") fig.plot( @@ -54,9 +50,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") fig.grdimage(grid, projection="W0/6i") @@ -65,10 +59,8 @@ def test_makecpt_to_plot_grid(grid): @check_figures_equal() 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 - """ + """Use static color palette table scaled to a min/max series to change + color of grid.""" # Use single-character arguments for the reference image fig_ref = Figure() makecpt(C="oleron", T="-4500/4500") @@ -81,35 +73,28 @@ 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) assert os.path.exists(cptfile.name) 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="") 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"]) @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]) fig.grdimage(grid, projection="W0/6i") @@ -118,9 +103,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]) fig.grdimage(grid, projection="W0/6i") @@ -129,9 +112,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]) fig.grdimage(grid, projection="W0/6i") @@ -140,9 +121,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) fig.grdimage(grid, projection="W0/6i") @@ -151,9 +130,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") fig.grdimage(grid, projection="W0/6i") @@ -162,10 +139,8 @@ def test_makecpt_reverse_zsign_only(grid): @pytest.mark.mpl_image_compare def test_makecpt_reverse_color_and_zsign(grid): - """ - Use static color palette table with both its colors and z-value sign - reversed - """ + """Use static color palette table with both its colors and z-value sign + reversed.""" fig = Figure() makecpt(cmap="earth", reverse="cz") fig.grdimage(grid, projection="W0/6i") @@ -174,10 +149,8 @@ def test_makecpt_reverse_color_and_zsign(grid): @pytest.mark.mpl_image_compare def test_makecpt_continuous(grid): - """ - Use static color palette table that is continuous from blue to white and - scaled from -4500 to 4500m. - """ + """Use static color palette table that is continuous from blue to white and + scaled from -4500 to 4500m.""" fig = Figure() makecpt(cmap="blue,white", continuous=True, series="-4500,4500") fig.grdimage(grid, projection="W0/6i") @@ -186,9 +159,7 @@ def test_makecpt_continuous(grid): @check_figures_equal() def test_makecpt_categorical(region): - """ - Use static color palette table that is categorical. - """ + """Use static color palette table that is categorical.""" fig_ref = Figure() makecpt(C="categorical", W="") fig_ref.colorbar(cmap=True, region=region, frame=True, position="JBC") @@ -201,9 +172,7 @@ def test_makecpt_categorical(region): @check_figures_equal() def test_makecpt_cyclic(region): - """ - Use static color palette table that is cyclic. - """ + """Use static color palette table that is cyclic.""" fig_ref = Figure() makecpt(C="cork", W="w") fig_ref.colorbar(cmap=True, region=region, frame=True, position="JBC") @@ -215,8 +184,6 @@ def test_makecpt_cyclic(region): def test_makecpt_categorical_and_cyclic(): - """ - Use incorrect setting by setting both categorical and cyclic to True. - """ + """Use incorrect setting by setting both categorical and cyclic to True.""" with pytest.raises(GMTInvalidInput): makecpt(cmap="batlow", categorical=True, cyclic=True) diff --git a/pygmt/tests/test_meca.py b/pygmt/tests/test_meca.py index 4776be1e5b1..1839e66257f 100644 --- a/pygmt/tests/test_meca.py +++ b/pygmt/tests/test_meca.py @@ -1,6 +1,4 @@ -""" -Tests for meca -""" +"""Tests for meca.""" import os import pandas as pd import numpy as np @@ -15,10 +13,8 @@ @pytest.mark.mpl_image_compare def test_meca_spec_dictionary(): - """ - Test supplying a dictionary containing a single focal mechanism to the - `spec` argument. - """ + """Test supplying a dictionary containing a single focal mechanism to the + `spec` argument.""" fig = Figure() @@ -39,10 +35,8 @@ def test_meca_spec_dictionary(): @pytest.mark.mpl_image_compare def test_meca_spec_dict_list(): - """ - Test supplying a dictionary containing a list of focal mechanism to the - `spec` argument. - """ + """Test supplying a dictionary containing a list of focal mechanism to the + `spec` argument.""" fig = Figure() @@ -66,10 +60,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,10 +84,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,10 +124,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() @@ -178,10 +166,8 @@ def test_meca_spec_2d_array(): @pytest.mark.mpl_image_compare def test_meca_spec_file(): - """ - Test supplying a file containing focal mechanisms and locations to the - `spec` argument. - """ + """Test supplying a file containing focal mechanisms and locations to the + `spec` argument.""" fig = Figure() @@ -206,10 +192,8 @@ def test_meca_spec_file(): @pytest.mark.mpl_image_compare def test_meca_loc_array(): - """ - Test supplying lists and np.ndarrays as the event location (longitude, - latitude, and depth). - """ + """Test supplying lists and np.ndarrays as the event location (longitude, + latitude, and depth).""" fig = Figure() diff --git a/pygmt/tests/test_plot.py b/pygmt/tests/test_plot.py index cef4dae5448..a02552f375f 100644 --- a/pygmt/tests/test_plot.py +++ b/pygmt/tests/test_plot.py @@ -1,7 +1,5 @@ # pylint: disable=redefined-outer-name -""" -Tests plot. -""" +"""Tests plot.""" import datetime import os @@ -23,19 +21,19 @@ @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], @@ -50,7 +48,7 @@ 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( @@ -89,7 +87,8 @@ 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( @@ -114,7 +113,7 @@ 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], @@ -130,7 +129,7 @@ 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( @@ -157,7 +156,7 @@ 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], @@ -174,7 +173,7 @@ 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], @@ -192,7 +191,7 @@ 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( @@ -208,7 +207,7 @@ 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) @@ -235,7 +234,7 @@ 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 @@ -269,7 +268,7 @@ 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 @@ -306,7 +305,7 @@ 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, @@ -322,7 +321,7 @@ 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, @@ -337,7 +336,7 @@ 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, @@ -353,7 +352,7 @@ 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)) @@ -374,7 +373,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. @@ -391,7 +391,7 @@ 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") @@ -402,7 +402,7 @@ 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 ba0590b1a1c..abfad10326c 100644 --- a/pygmt/tests/test_plot3d.py +++ b/pygmt/tests/test_plot3d.py @@ -1,6 +1,4 @@ -""" -Tests plot3d. -""" +"""Tests plot3d.""" import os import numpy as np @@ -18,13 +16,13 @@ @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] @@ -87,7 +85,7 @@ 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( @@ -127,7 +125,8 @@ 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( @@ -152,7 +151,7 @@ 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, @@ -181,7 +180,7 @@ 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, @@ -213,7 +212,7 @@ 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, @@ -246,7 +245,7 @@ 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, @@ -280,7 +279,7 @@ 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, @@ -315,7 +314,7 @@ 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 @@ -354,7 +353,7 @@ 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 @@ -392,7 +391,7 @@ 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 @@ -435,7 +434,7 @@ 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, @@ -464,7 +463,7 @@ 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, @@ -493,7 +492,7 @@ 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, @@ -522,7 +521,7 @@ 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)) @@ -559,7 +558,7 @@ 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_psconvert.py b/pygmt/tests/test_psconvert.py index 47b915462bd..4f40b8af5df 100644 --- a/pygmt/tests/test_psconvert.py +++ b/pygmt/tests/test_psconvert.py @@ -1,15 +1,11 @@ -""" -Tests psconvert. -""" +"""Tests psconvert.""" import os from .. import Figure def test_psconvert(): - """ - psconvert creates a figure in the current directory. - """ + """psconvert creates a figure in the current directory.""" fig = Figure() fig.basemap(R="10/70/-3/8", J="X4i/3i", B="a") prefix = "test_psconvert" @@ -20,9 +16,7 @@ def test_psconvert(): def test_psconvert_twice(): - """ - Call psconvert twice to get two figures. - """ + """Call psconvert twice to get two figures.""" fig = Figure() fig.basemap(R="10/70/-3/8", J="X4i/3i", B="a") prefix = "test_psconvert_twice" @@ -39,9 +33,7 @@ def test_psconvert_twice(): def test_psconvert_int_options(): - """ - psconvert handles integer options well. - """ + """psconvert handles integer options well.""" fig = Figure() fig.basemap(R="10/70/-3/8", J="X4i/3i", B="a") prefix = "test_psconvert_int_options" @@ -51,9 +43,7 @@ def test_psconvert_int_options(): def test_psconvert_aliases(): - """ - Use the aliases to make sure they work. - """ + """Use the aliases to make sure they work.""" fig = Figure() fig.basemap(R="10/70/-3/8", J="X4i/3i", B="a") prefix = "test_psconvert_aliases" diff --git a/pygmt/tests/test_session_management.py b/pygmt/tests/test_session_management.py index 47c8edc78c1..881fa8fac71 100644 --- a/pygmt/tests/test_session_management.py +++ b/pygmt/tests/test_session_management.py @@ -1,6 +1,4 @@ -""" -Test the session management modules. -""" +"""Test the session management modules.""" import os from ..session_management import begin, end @@ -10,6 +8,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 +24,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 accca7e7fdb..e3986104b61 100644 --- a/pygmt/tests/test_sphinx_gallery.py +++ b/pygmt/tests/test_sphinx_gallery.py @@ -1,6 +1,4 @@ -""" -Test the sphinx-gallery scraper and code required to make it work. -""" +"""Test the sphinx-gallery scraper and code required to make it work.""" import os from tempfile import TemporaryDirectory import pytest @@ -16,7 +14,8 @@ @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 08ad8628244..41e073abaaa 100644 --- a/pygmt/tests/test_surface.py +++ b/pygmt/tests/test_surface.py @@ -1,6 +1,4 @@ -""" -Tests for surface -""" +"""Tests for surface.""" import os import xarray as xr @@ -17,9 +15,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]) assert isinstance(output, xr.DataArray) @@ -29,9 +25,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 output = surface(data=data, spacing="5m", region=[245, 255, 20, 30]) @@ -40,9 +34,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( x=ship_data.longitude, @@ -56,9 +48,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): surface( @@ -70,9 +60,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 assert data_kind(data) == "grid" @@ -81,9 +69,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 try: @@ -100,10 +86,8 @@ 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 - """ + """Run surface using short aliases -I for spacing, -R for region, -G for + outfile.""" ship_data = load_sample_bathymetry() data = ship_data.values # convert pandas.DataFrame to numpy.ndarray try: diff --git a/pygmt/tests/test_text.py b/pygmt/tests/test_text.py index 26e45f8f4fc..9d96c183b4d 100644 --- a/pygmt/tests/test_text.py +++ b/pygmt/tests/test_text.py @@ -1,7 +1,5 @@ # pylint: disable=redefined-outer-name -""" -Tests text -""" +"""Tests text.""" import os import pytest @@ -17,21 +15,19 @@ @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( region=region, @@ -45,9 +41,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( region=region, @@ -60,9 +54,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): fig.text(region=region, projection=projection, x=1.2, y=2.4) @@ -70,9 +62,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) return fig @@ -80,9 +70,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") return fig @@ -90,18 +78,15 @@ 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]) return fig 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): fig.text(region=[10, 70, -5, 10], textfiles=[POINTS_DATA, "notexist.txt"]) @@ -109,10 +94,8 @@ def test_text_nonexistent_filename(): @pytest.mark.mpl_image_compare def test_text_position(region): - """ - Print text at center middle (CM) and eight other positions - (Top/Middle/Bottom x Left/Centre/Right). - """ + """Print text at center middle (CM) and eight other positions + (Top/Middle/Bottom x Left/Centre/Right).""" fig = Figure() fig.text(region=region, projection="x1c", frame="a", position="CM", text="C M") for position in ("TL", "TC", "TR", "ML", "MR", "BL", "BC", "BR"): @@ -121,9 +104,7 @@ def test_text_position(region): def test_text_xy_with_position_fails(region): - """ - Run text by providing both x/y pairs and position arguments. - """ + """Run text by providing both x/y pairs and position arguments.""" fig = Figure() with pytest.raises(GMTInvalidInput): fig.text( @@ -133,11 +114,9 @@ def test_text_xy_with_position_fails(region): @pytest.mark.mpl_image_compare def test_text_position_offset_with_line(region): - """ - Print text at centre middle (CM) and eight other positions + """Print text at centre middle (CM) and eight other positions (Top/Middle/Bottom x Left/Centre/Right), offset by 0.5 cm, with a line - drawn from the original to the shifted point. - """ + drawn from the original to the shifted point.""" fig = Figure() fig.text(region=region, projection="x1c", frame="a", position="CM", text="C M") for position in ("TL", "TC", "TR", "ML", "MR", "BL", "BC", "BR"): @@ -147,9 +126,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( region=region, @@ -164,9 +141,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( region=region, @@ -181,9 +156,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( region=region, @@ -198,9 +171,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( region=region, @@ -215,9 +186,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( region=region, @@ -233,9 +202,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( region=region, @@ -260,7 +227,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 """ @@ -277,10 +246,8 @@ def test_text_justify_parsed_from_textfile(): @pytest.mark.mpl_image_compare def test_text_angle_font_justify_from_textfile(): - """ - Print text with x, y, angle, font, justify, and text arguments parsed from - the textfile. - """ + """Print text with x, y, angle, font, justify, and text arguments parsed + from the textfile.""" fig = Figure() with GMTTempFile(suffix=".txt") as tempfile: with open(tempfile.name, "w") as tmpfile: diff --git a/pygmt/tests/test_which.py b/pygmt/tests/test_which.py index 407127b9551..ea7e22c351f 100644 --- a/pygmt/tests/test_which.py +++ b/pygmt/tests/test_which.py @@ -1,6 +1,4 @@ -""" -Tests for pygmt.which -""" +"""Tests for pygmt.which.""" import os import pytest @@ -10,7 +8,8 @@ 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) @@ -18,7 +17,7 @@ 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 50577b738df..ac652cac018 100644 --- a/pygmt/tests/test_x2sys_cross.py +++ b/pygmt/tests/test_x2sys_cross.py @@ -1,7 +1,5 @@ # pylint: disable=unused-argument -""" -Tests for x2sys_cross -""" +"""Tests for x2sys_cross.""" import os from tempfile import TemporaryDirectory @@ -18,28 +16,22 @@ @pytest.fixture(name="mock_x2sys_home") def fixture_mock_x2sys_home(monkeypatch): - """ - Set the X2SYS_HOME environment variable to the current working directory - for the test session - """ + """Set the X2SYS_HOME environment variable to the current working directory + for the test session.""" monkeypatch.setenv("X2SYS_HOME", os.getcwd()) @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 return [dataframe.query(expr="z > -20")] # reduce size of dataset 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 - """ + """Run x2sys_cross by passing in a filename, and output internal crossovers + to an ASCII txt file.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init(tag=tag, fmtfile="xyz", force=True) @@ -56,10 +48,8 @@ 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 - """ + """Run x2sys_cross by passing in a filename, and output internal crossovers + to a pandas.DataFrame.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init(tag=tag, fmtfile="xyz", force=True) @@ -75,10 +65,8 @@ def test_x2sys_cross_input_file_output_dataframe(mock_x2sys_home): def test_x2sys_cross_input_dataframe_output_dataframe(mock_x2sys_home, tracks): - """ - Run x2sys_cross by passing in one dataframe, and output external crossovers - to a pandas.DataFrame. - """ + """Run x2sys_cross by passing in one dataframe, and output external + crossovers to a pandas.DataFrame.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init(tag=tag, fmtfile="xyz", force=True) @@ -97,10 +85,8 @@ 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 - """ + """Run x2sys_cross by passing in two pandas.DataFrame tables with a time + column, and output external crossovers to a pandas.DataFrame.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init( @@ -131,10 +117,8 @@ 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 - """ + """Run x2sys_cross by passing in two filenames, and output external + crossovers to a pandas.DataFrame.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init(tag=tag, fmtfile="xyz", force=True) @@ -160,10 +144,8 @@ def test_x2sys_cross_input_two_filenames(mock_x2sys_home): def test_x2sys_cross_invalid_tracks_input_type(tracks): - """ - Run x2sys_cross using tracks input that is not a pandas.DataFrame (matrix) - or str (file) type, which would raise a GMTInvalidInput error. - """ + """Run x2sys_cross using tracks input that is not a pandas.DataFrame + (matrix) or str (file) type, which would raise a GMTInvalidInput error.""" invalid_tracks = tracks[0].to_xarray().z assert data_kind(invalid_tracks) == "grid" with pytest.raises(GMTInvalidInput): @@ -171,10 +153,8 @@ def test_x2sys_cross_invalid_tracks_input_type(tracks): def test_x2sys_cross_region_interpolation_numpoints(mock_x2sys_home): - """ - Test that x2sys_cross's region (R), interpolation (l) and numpoints (W) - arguments work. - """ + """Test that x2sys_cross's region (R), interpolation (l) and numpoints (W) + arguments work.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init(tag=tag, fmtfile="xyz", force=True) @@ -195,9 +175,7 @@ def test_x2sys_cross_region_interpolation_numpoints(mock_x2sys_home): def test_x2sys_cross_trackvalues(mock_x2sys_home): - """ - Test that x2sys_cross's trackvalues (Z) argument work. - """ + """Test that x2sys_cross's trackvalues (Z) argument work.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init(tag=tag, fmtfile="xyz", force=True) diff --git a/pygmt/tests/test_x2sys_init.py b/pygmt/tests/test_x2sys_init.py index a6c608e57e1..c419691b061 100644 --- a/pygmt/tests/test_x2sys_init.py +++ b/pygmt/tests/test_x2sys_init.py @@ -1,7 +1,5 @@ # pylint: disable=unused-argument -""" -Tests for x2sys_init -""" +"""Tests for x2sys_init.""" import os from tempfile import TemporaryDirectory @@ -12,18 +10,14 @@ @pytest.fixture(name="mock_x2sys_home") def fixture_mock_x2sys_home(monkeypatch): - """ - Set the X2SYS_HOME environment variable to the current working directory - for the test session - """ + """Set the X2SYS_HOME environment variable to the current working directory + for the test session.""" monkeypatch.setenv("X2SYS_HOME", os.getcwd()) 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 - """ + """Test that x2sys_init's region (R) and spacing (I) sequence arguments + accept a list properly.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init( @@ -37,10 +31,8 @@ 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 - """ + """Test that x2sys_init's units (N) and gap (W) arguments accept a list + properly.""" with TemporaryDirectory(prefix="X2SYS", dir=os.getcwd()) as tmpdir: tag = os.path.basename(tmpdir) x2sys_init( diff --git a/pygmt/x2sys.py b/pygmt/x2sys.py index e3803ba7806..8936ae96cf2 100644 --- a/pygmt/x2sys.py +++ b/pygmt/x2sys.py @@ -1,6 +1,4 @@ -""" -GMT supplementary X2SYS module for crossover analysis. -""" +"""GMT supplementary X2SYS module for crossover analysis.""" import contextlib import os from pathlib import Path diff --git a/setup.py b/setup.py index b36d247f8b7..036564c2684 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,4 @@ -""" -Build and install the project. -""" +"""Build and install the project.""" from setuptools import setup, find_packages