Skip to content

Commit 871d106

Browse files
authored
Split tests in test_clib.py into mutliple smaller test files (#3516)
1 parent 7dffc68 commit 871d106

File tree

6 files changed

+381
-342
lines changed

6 files changed

+381
-342
lines changed

pygmt/tests/test_clib.py

Lines changed: 1 addition & 342 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,18 @@
33
"""
44

55
from contextlib import contextmanager
6-
from pathlib import Path
76

8-
import numpy as np
9-
import numpy.testing as npt
107
import pytest
11-
import xarray as xr
128
from packaging.version import Version
13-
from pygmt import Figure, clib
9+
from pygmt import clib
1410
from pygmt.clib import required_gmt_version
15-
from pygmt.clib.conversion import dataarray_to_matrix
1611
from pygmt.clib.session import FAMILIES, VIAS
1712
from pygmt.exceptions import (
1813
GMTCLibError,
1914
GMTCLibNoSessionError,
2015
GMTInvalidInput,
2116
GMTVersionError,
2217
)
23-
from pygmt.helpers import GMTTempFile
24-
25-
POINTS_DATA = Path(__file__).parent / "data" / "points.txt"
2618

2719

2820
@contextmanager
@@ -129,82 +121,6 @@ def test_destroy_session_fails():
129121
ses.destroy()
130122

131123

132-
@pytest.mark.benchmark
133-
def test_call_module():
134-
"""
135-
Call a GMT module by passing a list of arguments.
136-
"""
137-
with clib.Session() as lib:
138-
with GMTTempFile() as out_fname:
139-
lib.call_module("info", [str(POINTS_DATA), "-C", f"->{out_fname.name}"])
140-
assert Path(out_fname.name).stat().st_size > 0
141-
output = out_fname.read().strip()
142-
assert output == "11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338"
143-
144-
145-
def test_call_module_argument_string():
146-
"""
147-
Call a GMT module by passing a single argument string.
148-
"""
149-
with clib.Session() as lib:
150-
with GMTTempFile() as out_fname:
151-
lib.call_module("info", f"{POINTS_DATA} -C ->{out_fname.name}")
152-
assert Path(out_fname.name).stat().st_size > 0
153-
output = out_fname.read().strip()
154-
assert output == "11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338"
155-
156-
157-
def test_call_module_empty_argument():
158-
"""
159-
call_module should work if an empty string or an empty list is passed as argument.
160-
"""
161-
Figure()
162-
with clib.Session() as lib:
163-
lib.call_module("logo", "")
164-
with clib.Session() as lib:
165-
lib.call_module("logo", [])
166-
167-
168-
def test_call_module_invalid_argument_type():
169-
"""
170-
call_module only accepts a string or a list of strings as module arguments.
171-
"""
172-
with clib.Session() as lib:
173-
with pytest.raises(GMTInvalidInput):
174-
lib.call_module("get", ("FONT_TITLE", "FONT_TAG"))
175-
176-
177-
def test_call_module_invalid_arguments():
178-
"""
179-
call_module should fail for invalid module arguments.
180-
"""
181-
with clib.Session() as lib:
182-
with pytest.raises(GMTCLibError):
183-
lib.call_module("info", ["bogus-data.bla"])
184-
185-
186-
def test_call_module_invalid_name():
187-
"""
188-
call_module should fail when an invalid module name is given.
189-
"""
190-
with clib.Session() as lib:
191-
with pytest.raises(GMTCLibError):
192-
lib.call_module("meh", [])
193-
194-
195-
def test_call_module_error_message():
196-
"""
197-
Check if the GMT error message was captured when calling a module.
198-
"""
199-
with clib.Session() as lib:
200-
with pytest.raises(GMTCLibError) as exc_info:
201-
lib.call_module("info", ["bogus-data.bla"])
202-
assert "Module 'info' failed with status code" in exc_info.value.args[0]
203-
assert (
204-
"gmtinfo [ERROR]: Cannot find file bogus-data.bla" in exc_info.value.args[0]
205-
)
206-
207-
208124
def test_method_no_session():
209125
"""
210126
Fails when not in a session.
@@ -268,263 +184,6 @@ def test_parse_constant_fails():
268184
)
269185

270186

271-
def test_create_data_dataset():
272-
"""
273-
Run the function to make sure it doesn't fail badly.
274-
"""
275-
with clib.Session() as lib:
276-
# Dataset from vectors
277-
data_vector = lib.create_data(
278-
family="GMT_IS_DATASET|GMT_VIA_VECTOR",
279-
geometry="GMT_IS_POINT",
280-
mode="GMT_CONTAINER_ONLY",
281-
dim=[10, 20, 1, 0], # columns, rows, layers, dtype
282-
)
283-
# Dataset from matrices
284-
data_matrix = lib.create_data(
285-
family="GMT_IS_DATASET|GMT_VIA_MATRIX",
286-
geometry="GMT_IS_POINT",
287-
mode="GMT_CONTAINER_ONLY",
288-
dim=[10, 20, 1, 0],
289-
)
290-
assert data_vector != data_matrix
291-
292-
293-
def test_create_data_grid_dim():
294-
"""
295-
Create a grid ignoring range and inc.
296-
"""
297-
with clib.Session() as lib:
298-
# Grids from matrices using dim
299-
lib.create_data(
300-
family="GMT_IS_GRID|GMT_VIA_MATRIX",
301-
geometry="GMT_IS_SURFACE",
302-
mode="GMT_CONTAINER_ONLY",
303-
dim=[10, 20, 1, 0],
304-
)
305-
306-
307-
def test_create_data_grid_range():
308-
"""
309-
Create a grid specifying range and inc instead of dim.
310-
"""
311-
with clib.Session() as lib:
312-
# Grids from matrices using range and int
313-
lib.create_data(
314-
family="GMT_IS_GRID|GMT_VIA_MATRIX",
315-
geometry="GMT_IS_SURFACE",
316-
mode="GMT_CONTAINER_ONLY",
317-
ranges=[150.0, 250.0, -20.0, 20.0],
318-
inc=[0.1, 0.2],
319-
)
320-
321-
322-
def test_create_data_fails():
323-
"""
324-
Check that create_data raises exceptions for invalid input and output.
325-
"""
326-
# Passing in invalid mode
327-
with pytest.raises(GMTInvalidInput):
328-
with clib.Session() as lib:
329-
lib.create_data(
330-
family="GMT_IS_DATASET",
331-
geometry="GMT_IS_SURFACE",
332-
mode="Not_a_valid_mode",
333-
dim=[0, 0, 1, 0],
334-
ranges=[150.0, 250.0, -20.0, 20.0],
335-
inc=[0.1, 0.2],
336-
)
337-
# Passing in invalid geometry
338-
with pytest.raises(GMTInvalidInput):
339-
with clib.Session() as lib:
340-
lib.create_data(
341-
family="GMT_IS_GRID",
342-
geometry="Not_a_valid_geometry",
343-
mode="GMT_CONTAINER_ONLY",
344-
dim=[0, 0, 1, 0],
345-
ranges=[150.0, 250.0, -20.0, 20.0],
346-
inc=[0.1, 0.2],
347-
)
348-
349-
# If the data pointer returned is None (NULL pointer)
350-
with clib.Session() as lib:
351-
with mock(lib, "GMT_Create_Data", returns=None):
352-
with pytest.raises(GMTCLibError):
353-
lib.create_data(
354-
family="GMT_IS_DATASET",
355-
geometry="GMT_IS_SURFACE",
356-
mode="GMT_CONTAINER_ONLY",
357-
dim=[11, 10, 2, 0],
358-
)
359-
360-
361-
def test_extract_region_fails():
362-
"""
363-
Check that extract region fails if nothing has been plotted.
364-
"""
365-
Figure()
366-
with pytest.raises(GMTCLibError):
367-
with clib.Session() as lib:
368-
lib.extract_region()
369-
370-
371-
def test_extract_region_two_figures():
372-
"""
373-
Extract region should handle multiple figures existing at the same time.
374-
"""
375-
# Make two figures before calling extract_region to make sure that it's
376-
# getting from the current figure, not the last figure.
377-
fig1 = Figure()
378-
region1 = np.array([0, 10, -20, -10])
379-
fig1.coast(region=region1, projection="M6i", frame=True, land="black")
380-
381-
fig2 = Figure()
382-
fig2.basemap(region="US.HI+r5", projection="M6i", frame=True)
383-
384-
# Activate the first figure and extract the region from it
385-
# Use in a different session to avoid any memory problems.
386-
with clib.Session() as lib:
387-
lib.call_module("figure", [fig1._name, "-"])
388-
with clib.Session() as lib:
389-
wesn1 = lib.extract_region()
390-
npt.assert_allclose(wesn1, region1)
391-
392-
# Now try it with the second one
393-
with clib.Session() as lib:
394-
lib.call_module("figure", [fig2._name, "-"])
395-
with clib.Session() as lib:
396-
wesn2 = lib.extract_region()
397-
npt.assert_allclose(wesn2, np.array([-165.0, -150.0, 15.0, 25.0]))
398-
399-
400-
def test_write_data_fails():
401-
"""
402-
Check that write data raises an exception for non-zero return codes.
403-
"""
404-
# It's hard to make the C API function fail without causing a Segmentation
405-
# Fault. Can't test this if by giving a bad file name because if
406-
# output=='', GMT will just write to stdout and spaces are valid file
407-
# names. Use a mock instead just to exercise this part of the code.
408-
with clib.Session() as lib:
409-
with mock(lib, "GMT_Write_Data", returns=1):
410-
with pytest.raises(GMTCLibError):
411-
lib.write_data(
412-
"GMT_IS_VECTOR",
413-
"GMT_IS_POINT",
414-
"GMT_WRITE_SET",
415-
[1] * 6,
416-
"some-file-name",
417-
None,
418-
)
419-
420-
421-
@pytest.mark.benchmark
422-
def test_dataarray_to_matrix_works():
423-
"""
424-
Check that dataarray_to_matrix returns correct output.
425-
"""
426-
data = np.diag(v=np.arange(3))
427-
x = np.linspace(start=0, stop=4, num=3)
428-
y = np.linspace(start=5, stop=9, num=3)
429-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
430-
431-
matrix, region, inc = dataarray_to_matrix(grid)
432-
npt.assert_allclose(actual=matrix, desired=np.flipud(data))
433-
npt.assert_allclose(actual=region, desired=[x.min(), x.max(), y.min(), y.max()])
434-
npt.assert_allclose(actual=inc, desired=[x[1] - x[0], y[1] - y[0]])
435-
436-
437-
def test_dataarray_to_matrix_negative_x_increment():
438-
"""
439-
Check if dataarray_to_matrix returns correct output with flipped x.
440-
"""
441-
data = np.diag(v=np.arange(3))
442-
x = np.linspace(start=4, stop=0, num=3)
443-
y = np.linspace(start=5, stop=9, num=3)
444-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
445-
446-
matrix, region, inc = dataarray_to_matrix(grid)
447-
npt.assert_allclose(actual=matrix, desired=np.flip(data, axis=(0, 1)))
448-
npt.assert_allclose(actual=region, desired=[x.min(), x.max(), y.min(), y.max()])
449-
npt.assert_allclose(actual=inc, desired=[abs(x[1] - x[0]), abs(y[1] - y[0])])
450-
451-
452-
def test_dataarray_to_matrix_negative_y_increment():
453-
"""
454-
Check that dataarray_to_matrix returns correct output with flipped y.
455-
"""
456-
data = np.diag(v=np.arange(3))
457-
x = np.linspace(start=0, stop=4, num=3)
458-
y = np.linspace(start=9, stop=5, num=3)
459-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
460-
461-
matrix, region, inc = dataarray_to_matrix(grid)
462-
npt.assert_allclose(actual=matrix, desired=data)
463-
npt.assert_allclose(actual=region, desired=[x.min(), x.max(), y.min(), y.max()])
464-
npt.assert_allclose(actual=inc, desired=[abs(x[1] - x[0]), abs(y[1] - y[0])])
465-
466-
467-
def test_dataarray_to_matrix_negative_x_and_y_increment():
468-
"""
469-
Check that dataarray_to_matrix returns correct output with flipped x/y.
470-
"""
471-
data = np.diag(v=np.arange(3))
472-
x = np.linspace(start=4, stop=0, num=3)
473-
y = np.linspace(start=9, stop=5, num=3)
474-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
475-
476-
matrix, region, inc = dataarray_to_matrix(grid)
477-
npt.assert_allclose(actual=matrix, desired=np.fliplr(data))
478-
npt.assert_allclose(actual=region, desired=[x.min(), x.max(), y.min(), y.max()])
479-
npt.assert_allclose(actual=inc, desired=[abs(x[1] - x[0]), abs(y[1] - y[0])])
480-
481-
482-
def test_dataarray_to_matrix_dims_fails():
483-
"""
484-
Check that it fails for > 2 dims.
485-
"""
486-
# Make a 3-D regular grid
487-
data = np.ones((10, 12, 11), dtype="float32")
488-
x = np.arange(11)
489-
y = np.arange(12)
490-
z = np.arange(10)
491-
grid = xr.DataArray(data, coords=[("z", z), ("y", y), ("x", x)])
492-
with pytest.raises(GMTInvalidInput):
493-
dataarray_to_matrix(grid)
494-
495-
496-
def test_dataarray_to_matrix_irregular_inc_warning():
497-
"""
498-
Check that it warns for variable increments, see also
499-
https://github.com/GenericMappingTools/pygmt/issues/1468.
500-
"""
501-
data = np.ones((4, 5), dtype="float64")
502-
x = np.linspace(0, 1, 5)
503-
y = np.logspace(2, 3, 4)
504-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
505-
with pytest.warns(expected_warning=RuntimeWarning) as record:
506-
dataarray_to_matrix(grid)
507-
assert len(record) == 1
508-
509-
510-
def test_dataarray_to_matrix_zero_inc_fails():
511-
"""
512-
Check that dataarray_to_matrix fails for zero increments grid.
513-
"""
514-
data = np.ones((5, 5), dtype="float32")
515-
x = np.linspace(0, 1, 5)
516-
y = np.zeros_like(x)
517-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
518-
with pytest.raises(GMTInvalidInput):
519-
dataarray_to_matrix(grid)
520-
521-
y = np.linspace(0, 1, 5)
522-
x = np.zeros_like(x)
523-
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
524-
with pytest.raises(GMTInvalidInput):
525-
dataarray_to_matrix(grid)
526-
527-
528187
def test_get_default():
529188
"""
530189
Make sure get_default works without crashing and gives reasonable results.

0 commit comments

Comments
 (0)