From ee2117db996534d066baf4d549bcd94eff626a3b Mon Sep 17 00:00:00 2001 From: Ryan May Date: Tue, 6 Oct 2020 23:26:07 -0600 Subject: [PATCH] TST: Add some tests for warnings in xarray handling --- src/metpy/xarray.py | 15 ++++++--------- tests/test_xarray.py | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/metpy/xarray.py b/src/metpy/xarray.py index 644d65a3d64..960ba3c5ea3 100644 --- a/src/metpy/xarray.py +++ b/src/metpy/xarray.py @@ -688,15 +688,12 @@ def parse_cf(self, varname=None, coordinates=None): 'Attempting to parse metpy_crs as a data variable. Unexpected merge conflicts ' 'may occur.' ) - elif 'metpy_crs' in var.coords: - try: - assert isinstance(var.coords['metpy_crs'].item(), CFProjection) - except (ValueError, AssertionError): - # Catch non-scalar and non-CFProjection coordinates - warnings.warn( - 'metpy_crs already present as a non-CFProjection coordinate. Unexpected ' - 'merge conflicts may occur.' - ) + elif 'metpy_crs' in var.coords and (var.coords['metpy_crs'].size > 1 or not isinstance( + var.coords['metpy_crs'].item(), CFProjection)): + warnings.warn( + 'metpy_crs already present as a non-CFProjection coordinate. Unexpected ' + 'merge conflicts may occur.' + ) # Assign coordinates if the coordinates argument is given if coordinates is not None: diff --git a/tests/test_xarray.py b/tests/test_xarray.py index 162a80268ed..0ef261b2b31 100644 --- a/tests/test_xarray.py +++ b/tests/test_xarray.py @@ -248,6 +248,30 @@ def test_missing_grid_mapping_var(caplog): assert 'Could not find' in caplog.text +def test_parsecf_crs(): + """Test calling `parse_cf` with the metpy_crs variable.""" + ds = xr.Dataset({'metpy_crs': xr.DataArray(1)}) + + with pytest.warns(UserWarning, match='Attempting to parse metpy_crs'): + ds.metpy.parse_cf('metpy_crs') + + +def test_parsecf_existing_scalar_crs(): + """Test calling `parse_cf` on a variable with an existing scalar metpy_crs coordinate.""" + ds = xr.Dataset({'data': xr.DataArray(1, coords=dict(metpy_crs=1))}) + + with pytest.warns(UserWarning, match='metpy_crs already present'): + ds.metpy.parse_cf('data') + + +def test_parsecf_existing_vector_crs(): + """Test calling `parse_cf` on a variable with an existing vector metpy_crs coordinate.""" + ds = xr.Dataset({'data': xr.DataArray(1, dims=('metpy_crs',), coords=(np.ones(3),))}) + + with pytest.warns(UserWarning, match='metpy_crs already present'): + ds.metpy.parse_cf('data') + + def test_preprocess_and_wrap_only_preprocessing(): """Test xarray preprocessing and wrapping decorator for only preprocessing.""" data = xr.DataArray(np.ones(3), attrs={'units': 'km'})