From 4ba28bb44632b7fe31784fbbbb55bc292e4effd3 Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Tue, 24 Oct 2017 21:33:57 -0700 Subject: [PATCH 1/8] fixes for warnings related to unit tests --- .travis.yml | 3 +- xarray/tests/test_accessors.py | 6 +- xarray/tests/test_backends.py | 73 ++++---- xarray/tests/test_combine.py | 42 ++--- xarray/tests/test_conventions.py | 26 +-- xarray/tests/test_dask.py | 30 ++-- xarray/tests/test_dataarray.py | 150 ++++++++--------- xarray/tests/test_dataset.py | 252 ++++++++++++++-------------- xarray/tests/test_duck_array_ops.py | 6 +- xarray/tests/test_extensions.py | 4 +- xarray/tests/test_formatting.py | 4 +- xarray/tests/test_indexing.py | 28 ++-- xarray/tests/test_merge.py | 34 ++-- xarray/tests/test_plot.py | 52 +++--- xarray/tests/test_ufuncs.py | 4 +- xarray/tests/test_utils.py | 8 +- xarray/tests/test_variable.py | 80 ++++----- 17 files changed, 405 insertions(+), 397 deletions(-) diff --git a/.travis.yml b/.travis.yml index 496875fcd86..19c6dbc8646 100644 --- a/.travis.yml +++ b/.travis.yml @@ -83,7 +83,8 @@ install: - python setup.py install script: - - py.test xarray --cov=xarray --cov-config ci/.coveragerc --cov-report term-missing --verbose $EXTRA_FLAGS + # temporary mod while cleaning up warnings + - py.test -W error xarray --cov=xarray --cov-config ci/.coveragerc --cov-report term-missing --verbose $EXTRA_FLAGS after_success: - coveralls diff --git a/xarray/tests/test_accessors.py b/xarray/tests/test_accessors.py index dd1d77cf0af..5233dea81a7 100644 --- a/xarray/tests/test_accessors.py +++ b/xarray/tests/test_accessors.py @@ -6,7 +6,7 @@ import numpy as np import pandas as pd -from . import TestCase, requires_dask +from . import TestCase, requires_dask, raises_regex class TestDatetimeAccessor(TestCase): @@ -45,7 +45,7 @@ def test_not_datetime_type(self): nontime_data = self.data.copy() int_data = np.arange(len(self.data.time)).astype('int8') nontime_data['time'].values = int_data - with self.assertRaisesRegexp(TypeError, 'dt'): + with raises_regex(TypeError, 'dt'): nontime_data.time.dt @requires_dask @@ -93,4 +93,4 @@ def test_seasons(self): "SON", "SON", "SON", "DJF"] seasons = xr.DataArray(seasons) - self.assertArrayEqual(seasons.values, dates.dt.season.values) \ No newline at end of file + self.assertArrayEqual(seasons.values, dates.dt.season.values) diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index 6cb291693f4..e56910374dd 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -28,7 +28,7 @@ requires_scipy_or_netCDF4, requires_dask, requires_h5netcdf, requires_pynio, requires_pathlib, has_netCDF4, has_scipy, assert_allclose, flaky, network, requires_rasterio, - assert_identical) + assert_identical, raises_regex) from .test_dataset import create_test_data from xarray.tests import mock @@ -113,7 +113,7 @@ def __getitem__(self, key): return self.array[key] array = UnreliableArray([0]) - with self.assertRaises(UnreliableArrayFailure): + with pytest.raises(UnreliableArrayFailure): array[0] self.assertEqual(array[0], 0) @@ -188,7 +188,7 @@ def assert_loads(vars=None): self.assertTrue(v._in_memory) self.assertDatasetAllClose(expected, actual) - with self.assertRaises(AssertionError): + with pytest.raises(AssertionError): # make sure the contextmanager works! with assert_loads() as ds: pass @@ -303,8 +303,7 @@ def test_roundtrip_datetime_data(self): kwds = {'encoding': {'t0': {'units': 'days since 1950-01-01'}}} with self.roundtrip(expected, save_kwargs=kwds) as actual: self.assertDatasetIdentical(expected, actual) - self.assertEquals(actual.t0.encoding['units'], - 'days since 1950-01-01') + assert actual.t0.encoding['units'] == 'days since 1950-01-01' def test_roundtrip_timedelta_data(self): time_deltas = pd.to_timedelta(['1h', '2h', 'NaT']) @@ -490,7 +489,7 @@ def test_roundtrip_endian(self): if type(self) is NetCDF4DataTest: ds['z'].encoding['endian'] = 'big' - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): with self.roundtrip(ds) as actual: pass @@ -501,7 +500,7 @@ def test_invalid_dataarray_names_raise(self): da = xr.DataArray(data) for name, e in zip([0, (4, 5), True, ''], [te, te, te, ve]): ds = Dataset({name: da}) - with self.assertRaisesRegexp(*e): + with raises_regex(*e): with self.roundtrip(ds) as actual: pass @@ -513,17 +512,17 @@ def test_encoding_kwarg(self): self.assertEqual(ds.x.encoding, {}) kwargs = dict(encoding={'x': {'foo': 'bar'}}) - with self.assertRaisesRegexp(ValueError, 'unexpected encoding'): + with raises_regex(ValueError, 'unexpected encoding'): with self.roundtrip(ds, save_kwargs=kwargs) as actual: pass kwargs = dict(encoding={'x': 'foo'}) - with self.assertRaisesRegexp(ValueError, 'must be castable'): + with raises_regex(ValueError, 'must be castable'): with self.roundtrip(ds, save_kwargs=kwargs) as actual: pass kwargs = dict(encoding={'invalid': {}}) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): with self.roundtrip(ds, save_kwargs=kwargs) as actual: pass @@ -612,9 +611,9 @@ def test_open_group(self): self.assertVariableEqual(actual['x'], expected['x']) # check that missing group raises appropriate exception - with self.assertRaises(IOError): + with pytest.raises(IOError): open_dataset(tmp_file, group='bar') - with self.assertRaisesRegexp(ValueError, 'must be a string'): + with raises_regex(ValueError, 'must be a string'): open_dataset(tmp_file, group=(1, 2, 3)) def test_open_subgroup(self): @@ -959,13 +958,13 @@ def roundtrip(self, data, save_kwargs={}, open_kwargs={}, def test_array_attrs(self): ds = Dataset(attrs={'foo': [[1, 2], [3, 4]]}) - with self.assertRaisesRegexp(ValueError, 'must be 1-dimensional'): + with raises_regex(ValueError, 'must be 1-dimensional'): with self.roundtrip(ds) as roundtripped: pass def test_roundtrip_example_1_netcdf_gz(self): if sys.version_info[:2] < (2, 7): - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'gzipped netCDF not supported'): open_example_dataset('example_1.nc.gz') else: @@ -985,7 +984,7 @@ def test_nc4_scipy(self): with nc4.Dataset(tmp_file, 'w', format='NETCDF4') as rootgrp: rootgrp.createGroup('foo') - with self.assertRaisesRegexp(TypeError, 'pip install netcdf4'): + with raises_regex(TypeError, 'pip install netcdf4'): open_dataset(tmp_file, engine='scipy') @@ -1066,18 +1065,18 @@ def roundtrip(self, data, save_kwargs={}, open_kwargs={}, def test_engine(self): data = create_test_data() - with self.assertRaisesRegexp(ValueError, 'unrecognized engine'): + with raises_regex(ValueError, 'unrecognized engine'): data.to_netcdf('foo.nc', engine='foobar') - with self.assertRaisesRegexp(ValueError, 'invalid engine'): + with raises_regex(ValueError, 'invalid engine'): data.to_netcdf(engine='netcdf4') with create_tmp_file() as tmp_file: data.to_netcdf(tmp_file) - with self.assertRaisesRegexp(ValueError, 'unrecognized engine'): + with raises_regex(ValueError, 'unrecognized engine'): open_dataset(tmp_file, engine='foobar') netcdf_bytes = data.to_netcdf() - with self.assertRaisesRegexp(ValueError, 'can only read'): + with raises_regex(ValueError, 'can only read'): open_dataset(BytesIO(netcdf_bytes), engine='foobar') def test_cross_engine_read_write_netcdf3(self): @@ -1366,12 +1365,12 @@ def test_common_coord_when_datavars_minimal(self): def test_invalid_data_vars_value_should_fail(self): with self.setup_files_and_datasets() as (files, _): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): with open_mfdataset(files, data_vars='minimum'): pass # test invalid coord parameter - with self.assertRaises(ValueError): + with pytest.raises(ValueError): with open_mfdataset(files, coords='minimum'): pass @@ -1424,7 +1423,7 @@ def test_open_mfdataset(self): self.assertEqual(actual.foo.variable.data.chunks, ((3, 2, 3, 2),)) - with self.assertRaisesRegexp(IOError, 'no files to open'): + with raises_regex(IOError, 'no files to open'): open_mfdataset('foo-bar-baz-*.nc', autoclose=self.autoclose) @requires_pathlib @@ -1455,7 +1454,7 @@ def test_attrs_mfdataset(self): # first dataset loaded self.assertEqual(actual.test1, ds1.test1) # attributes from ds2 are not retained, e.g., - with self.assertRaisesRegexp(AttributeError, + with raises_regex(AttributeError, 'no attribute'): actual.test2 @@ -1485,15 +1484,15 @@ def test_save_mfdataset_roundtrip(self): def test_save_mfdataset_invalid(self): ds = Dataset() - with self.assertRaisesRegexp(ValueError, 'cannot use mode'): + with raises_regex(ValueError, 'cannot use mode'): save_mfdataset([ds, ds], ['same', 'same']) - with self.assertRaisesRegexp(ValueError, 'same length'): + with raises_regex(ValueError, 'same length'): save_mfdataset([ds, ds], ['only one path']) def test_save_mfdataset_invalid_dataarray(self): # regression test for GH1555 da = DataArray([1, 2]) - with self.assertRaisesRegexp(TypeError, 'supports writing Dataset'): + with raises_regex(TypeError, 'supports writing Dataset'): save_mfdataset([da], ['dataarray']) @@ -1818,11 +1817,11 @@ def test_indexing(self): # but on x and y only windowed operations are allowed, more # exotic slicing should raise an error err_msg = 'not valid on rasterio' - with self.assertRaisesRegexp(IndexError, err_msg): + with raises_regex(IndexError, err_msg): actual.isel(x=[2, 4], y=[1, 3]).values - with self.assertRaisesRegexp(IndexError, err_msg): + with raises_regex(IndexError, err_msg): actual.isel(x=[4, 2]).values - with self.assertRaisesRegexp(IndexError, err_msg): + with raises_regex(IndexError, err_msg): actual.isel(x=slice(5, 2, -1)).values # Integer indexing @@ -1888,7 +1887,7 @@ def test_caching(self): # Without cache an error is raised err_msg = 'not valid on rasterio' - with self.assertRaisesRegexp(IndexError, err_msg): + with raises_regex(IndexError, err_msg): actual.isel(x=[2, 4]).values # This should cache everything @@ -1948,7 +1947,7 @@ class TestEncodingInvalid(TestCase): def test_extract_nc4_variable_encoding(self): var = xr.Variable(('x',), [1, 2, 3], {}, {'foo': 'bar'}) - with self.assertRaisesRegexp(ValueError, 'unexpected encoding'): + with raises_regex(ValueError, 'unexpected encoding'): _extract_nc4_variable_encoding(var, raise_on_invalid=True) var = xr.Variable(('x',), [1, 2, 3], {}, {'chunking': (2, 1)}) @@ -1964,7 +1963,7 @@ def test_extract_h5nc_encoding(self): # not supported with h5netcdf (yet) var = xr.Variable(('x',), [1, 2, 3], {}, {'least_sigificant_digit': 2}) - with self.assertRaisesRegexp(ValueError, 'unexpected encoding'): + with raises_regex(ValueError, 'unexpected encoding'): _extract_nc4_variable_encoding(var, raise_on_invalid=True) @@ -1997,17 +1996,17 @@ def new_dataset_and_coord_attrs(): ds, attrs = new_dataset_and_attrs() attrs[123] = 'test' - with self.assertRaisesRegexp(TypeError, 'Invalid name for attr'): + with raises_regex(TypeError, 'Invalid name for attr'): ds.to_netcdf('test.nc') ds, attrs = new_dataset_and_attrs() attrs[MiscObject()] = 'test' - with self.assertRaisesRegexp(TypeError, 'Invalid name for attr'): + with raises_regex(TypeError, 'Invalid name for attr'): ds.to_netcdf('test.nc') ds, attrs = new_dataset_and_attrs() attrs[''] = 'test' - with self.assertRaisesRegexp(ValueError, 'Invalid name for attr'): + with raises_regex(ValueError, 'Invalid name for attr'): ds.to_netcdf('test.nc') # This one should work @@ -2018,12 +2017,12 @@ def new_dataset_and_coord_attrs(): ds, attrs = new_dataset_and_attrs() attrs['test'] = {'a': 5} - with self.assertRaisesRegexp(TypeError, 'Invalid value for attr'): + with raises_regex(TypeError, 'Invalid value for attr'): ds.to_netcdf('test.nc') ds, attrs = new_dataset_and_attrs() attrs['test'] = MiscObject() - with self.assertRaisesRegexp(TypeError, 'Invalid value for attr'): + with raises_regex(TypeError, 'Invalid value for attr'): ds.to_netcdf('test.nc') ds, attrs = new_dataset_and_attrs() diff --git a/xarray/tests/test_combine.py b/xarray/tests/test_combine.py index f4bb5e83f98..6c74d20c4aa 100644 --- a/xarray/tests/test_combine.py +++ b/xarray/tests/test_combine.py @@ -3,13 +3,15 @@ from __future__ import print_function from copy import deepcopy +import pytest + import numpy as np import pandas as pd from xarray import Dataset, DataArray, auto_combine, concat, Variable from xarray.core.pycompat import iteritems, OrderedDict -from . import TestCase, InaccessibleArray, requires_dask +from . import TestCase, InaccessibleArray, requires_dask, raises_regex from .test_dataset import create_test_data @@ -91,7 +93,7 @@ def test_concat_coords(self): actual = concat(objs, dim='x', coords=coords) self.assertDatasetIdentical(expected, actual) for coords in ['minimal', []]: - with self.assertRaisesRegexp(ValueError, 'not equal across'): + with raises_regex(ValueError, 'not equal across'): concat(objs, dim='x', coords=coords) def test_concat_constant_index(self): @@ -102,7 +104,7 @@ def test_concat_constant_index(self): for mode in ['different', 'all', ['foo']]: actual = concat([ds1, ds2], 'y', data_vars=mode) self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'not equal across datasets'): + with raises_regex(ValueError, 'not equal across datasets'): concat([ds1, ds2], 'y', data_vars='minimal') def test_concat_size0(self): @@ -128,41 +130,41 @@ def test_concat_errors(self): split_data = [data.isel(dim1=slice(3)), data.isel(dim1=slice(3, None))] - with self.assertRaisesRegexp(ValueError, 'must supply at least one'): + with raises_regex(ValueError, 'must supply at least one'): concat([], 'dim1') - with self.assertRaisesRegexp(ValueError, 'are not coordinates'): + with raises_regex(ValueError, 'are not coordinates'): concat([data, data], 'new_dim', coords=['not_found']) - with self.assertRaisesRegexp(ValueError, 'global attributes not'): + with raises_regex(ValueError, 'global attributes not'): data0, data1 = deepcopy(split_data) data1.attrs['foo'] = 'bar' concat([data0, data1], 'dim1', compat='identical') self.assertDatasetIdentical( data, concat([data0, data1], 'dim1', compat='equals')) - with self.assertRaisesRegexp(ValueError, 'encountered unexpected'): + with raises_regex(ValueError, 'encountered unexpected'): data0, data1 = deepcopy(split_data) data1['foo'] = ('bar', np.random.randn(10)) concat([data0, data1], 'dim1') - with self.assertRaisesRegexp(ValueError, 'compat.* invalid'): + with raises_regex(ValueError, 'compat.* invalid'): concat(split_data, 'dim1', compat='foobar') - with self.assertRaisesRegexp(ValueError, 'unexpected value for'): + with raises_regex(ValueError, 'unexpected value for'): concat([data, data], 'new_dim', coords='foobar') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'coordinate in some datasets but not others'): concat([Dataset({'x': 0}), Dataset({'x': [1]})], dim='z') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'coordinate in some datasets but not others'): concat([Dataset({'x': 0}), Dataset({}, {'x': 1})], dim='z') - with self.assertRaisesRegexp(ValueError, 'no longer a valid'): + with raises_regex(ValueError, 'no longer a valid'): concat([data, data], 'new_dim', mode='different') - with self.assertRaisesRegexp(ValueError, 'no longer a valid'): + with raises_regex(ValueError, 'no longer a valid'): concat([data, data], 'new_dim', concat_over='different') def test_concat_promote_shape(self): @@ -214,7 +216,7 @@ def test_concat_do_not_promote(self): objs = [Dataset({'y': ('t', [1])}, {'x': 1, 't': [0]}), Dataset({'y': ('t', [2])}, {'x': 2, 't': [0]})] - with self.assertRaises(ValueError): + with pytest.raises(ValueError): concat(objs, 't', coords='minimal') def test_concat_dim_is_variable(self): @@ -262,10 +264,10 @@ def test_concat(self): expected = foo[:2].rename({'x': 'concat_dim'}) self.assertDataArrayIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'not identical'): + with raises_regex(ValueError, 'not identical'): concat([foo, bar], dim='w', compat='identical') - with self.assertRaisesRegexp(ValueError, 'not a valid argument'): + with raises_regex(ValueError, 'not a valid argument'): concat([foo, bar], dim='w', data_vars='minimal') def test_concat_encoding(self): @@ -317,15 +319,15 @@ def test_auto_combine(self): self.assertDatasetIdentical(expected, actual) objs = [Dataset({'x': [0], 'y': [0]}), Dataset({'y': [1], 'x': [1]})] - with self.assertRaisesRegexp(ValueError, 'too many .* dimensions'): + with raises_regex(ValueError, 'too many .* dimensions'): auto_combine(objs) objs = [Dataset({'x': 0}), Dataset({'x': 1})] - with self.assertRaisesRegexp(ValueError, 'cannot infer dimension'): + with raises_regex(ValueError, 'cannot infer dimension'): auto_combine(objs) objs = [Dataset({'x': [0], 'y': [0]}), Dataset({'x': [0]})] - with self.assertRaises(KeyError): + with pytest.raises(KeyError): auto_combine(objs) @requires_dask # only for toolz @@ -356,7 +358,7 @@ def test_auto_combine_still_fails(self): # https://github.com/pydata/xarray/issues/508 datasets = [Dataset({'x': 0}, {'y': 0}), Dataset({'x': 1}, {'y': 1, 'z': 1})] - with self.assertRaises(ValueError): + with pytest.raises(ValueError): auto_combine(datasets, 'y') @requires_dask # only for toolz diff --git a/xarray/tests/test_conventions.py b/xarray/tests/test_conventions.py index 6aaa2cbfa89..72813a95646 100644 --- a/xarray/tests/test_conventions.py +++ b/xarray/tests/test_conventions.py @@ -6,9 +6,11 @@ import pandas as pd import warnings +import pytest + from xarray import conventions, Variable, Dataset, open_dataset from xarray.core import utils, indexing -from . import TestCase, requires_netCDF4, unittest +from . import TestCase, requires_netCDF4, unittest, raises_regex from .test_backends import CFEncodedDataTest from xarray.core.pycompat import iteritems from xarray.backends.memory import InMemoryDataStore @@ -65,10 +67,10 @@ def test_wrapper_class(self): self.assertEqual(actual.shape, expected.shape) self.assertEqual(actual.size, expected.size) self.assertEqual(actual.ndim, expected.ndim) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): len(actual) self.assertArrayEqual(expected, actual) - with self.assertRaises(IndexError): + with pytest.raises(IndexError): actual[:2] self.assertEqual(str(actual), 'abc') @@ -82,7 +84,7 @@ def test_wrapper_class(self): self.assertEqual(len(actual), len(expected)) self.assertArrayEqual(expected, actual) self.assertArrayEqual(expected[:1], actual[:1]) - with self.assertRaises(IndexError): + with pytest.raises(IndexError): actual[:, :2] def test_char_to_string(self): @@ -219,7 +221,7 @@ def test_decode_cf_datetime_overflow(self): def test_decode_cf_datetime_transition_to_invalid(self): # manually create dataset with not-decoded date from datetime import datetime - ds = Dataset(coords={'time' : [0, 266 * 365]}) + ds = Dataset(coords={'time': [0, 266 * 365]}) units = 'days since 2000-01-01 00:00:00' ds.time.attrs = dict(units=units) ds_decoded = conventions.decode_cf(ds) @@ -268,8 +270,8 @@ def test_decode_cf_with_conflicting_fill_missing_value(self): {'units': 'foobar', 'missing_value': 0, '_FillValue': 1}) - self.assertRaisesRegexp(ValueError, "_FillValue and missing_value", - lambda: conventions.decode_cf_variable(var)) + with raises_regex(ValueError, "_FillValue and missing_value"): + conventions.decode_cf_variable(var) var = Variable(['t'], np.arange(10), {'units': 'foobar', @@ -279,9 +281,9 @@ def test_decode_cf_with_conflicting_fill_missing_value(self): self.assertIsNotNone(var) var = Variable(['t'], np.arange(10), - {'units': 'foobar', - 'missing_value': np.float32(np.nan), - '_FillValue': np.float32(np.nan)}) + {'units': 'foobar', + 'missing_value': np.float32(np.nan), + '_FillValue': np.float32(np.nan)}) var = conventions.decode_cf_variable(var) self.assertIsNotNone(var) @@ -494,7 +496,7 @@ def test_infer_timedelta_units(self): def test_invalid_units_raises_eagerly(self): ds = Dataset({'time': ('time', [0, 1], {'units': 'foobar since 123'})}) - with self.assertRaisesRegexp(ValueError, 'unable to decode time'): + with raises_regex(ValueError, 'unable to decode time'): decode_cf(ds) @requires_netCDF4 @@ -538,7 +540,7 @@ def test_incompatible_attributes(self): Variable(['t'], [0, 1, 2], {'_FillValue': 0}, {'_FillValue': 2}), ] for var in invalid_vars: - with self.assertRaises(ValueError): + with pytest.raises(ValueError): conventions.encode_cf_variable(var) def test_missing_fillvalue(self): diff --git a/xarray/tests/test_dask.py b/xarray/tests/test_dask.py index 59b0d302151..bdb61203668 100644 --- a/xarray/tests/test_dask.py +++ b/xarray/tests/test_dask.py @@ -14,7 +14,7 @@ from xarray import Variable, DataArray, Dataset import xarray.ufuncs as xu from xarray.core.pycompat import suppress -from . import TestCase +from . import TestCase, raises_regex from xarray.tests import mock @@ -86,7 +86,7 @@ def test_indexing(self): self.assertLazyAndIdentical(u[0], v[0]) self.assertLazyAndIdentical(u[:1], v[:1]) self.assertLazyAndIdentical(u[[0, 1], [0, 1, 2]], v[[0, 1], [0, 1, 2]]) - with self.assertRaisesRegexp(TypeError, 'stored in a dask array'): + with raises_regex(TypeError, 'stored in a dask array'): v[:1] = 0 def test_squeeze(self): @@ -145,9 +145,9 @@ def test_pickle(self): a1 = Variable(['x'], build_dask_array('x')) a1.compute() self.assertFalse(a1._in_memory) - self.assertEquals(kernel_call_count, 1) + assert kernel_call_count == 1 a2 = pickle.loads(pickle.dumps(a1)) - self.assertEquals(kernel_call_count, 1) + assert kernel_call_count == 1 self.assertVariableIdentical(a1, a2) self.assertFalse(a1._in_memory) self.assertFalse(a2._in_memory) @@ -160,7 +160,7 @@ def test_reduce(self): self.assertLazyAndAllClose(u.argmax(dim='x'), v.argmax(dim='x')) self.assertLazyAndAllClose((u > 1).any(), (v > 1).any()) self.assertLazyAndAllClose((u < 1).all('x'), (v < 1).all('x')) - with self.assertRaisesRegexp(NotImplementedError, 'dask'): + with raises_regex(NotImplementedError, 'dask'): v.median() def test_missing_values(self): @@ -339,7 +339,7 @@ def test_groupby_first(self): for coords in [u.coords, v.coords]: coords['ab'] = ('x', ['a', 'a', 'b', 'b']) - with self.assertRaisesRegexp(NotImplementedError, 'dask'): + with raises_regex(NotImplementedError, 'dask'): v.groupby('ab').first() expected = u.groupby('ab').first() actual = v.groupby('ab').first(skipna=False) @@ -451,7 +451,7 @@ def test_dataarray_repr(self): y (x) int64 dask.array Dimensions without coordinates: x""") self.assertEqual(expected, repr(a)) - self.assertEquals(kernel_call_count, 0) + assert kernel_call_count == 0 def test_dataset_repr(self): # Test that pickling/unpickling converts the dask backend @@ -469,7 +469,7 @@ def test_dataset_repr(self): Data variables: a (x) int64 dask.array""") self.assertEqual(expected, repr(ds)) - self.assertEquals(kernel_call_count, 0) + assert kernel_call_count == 0 def test_dataarray_pickle(self): # Test that pickling/unpickling converts the dask backend @@ -480,9 +480,9 @@ def test_dataarray_pickle(self): a1.compute() self.assertFalse(a1._in_memory) self.assertFalse(a1.coords['y']._in_memory) - self.assertEquals(kernel_call_count, 2) + assert kernel_call_count == 2 a2 = pickle.loads(pickle.dumps(a1)) - self.assertEquals(kernel_call_count, 2) + assert kernel_call_count == 2 self.assertDataArrayIdentical(a1, a2) self.assertFalse(a1._in_memory) self.assertFalse(a2._in_memory) @@ -499,9 +499,9 @@ def test_dataset_pickle(self): ds1.compute() self.assertFalse(ds1['a']._in_memory) self.assertFalse(ds1['y']._in_memory) - self.assertEquals(kernel_call_count, 2) + assert kernel_call_count == 2 ds2 = pickle.loads(pickle.dumps(ds1)) - self.assertEquals(kernel_call_count, 2) + assert kernel_call_count == 2 self.assertDatasetIdentical(ds1, ds2) self.assertFalse(ds1['a']._in_memory) self.assertFalse(ds2['a']._in_memory) @@ -518,7 +518,7 @@ def test_dataarray_getattr(self): coords={'y': ('x', nonindex_coord)}) with suppress(AttributeError): getattr(a, 'NOTEXIST') - self.assertEquals(kernel_call_count, 0) + assert kernel_call_count == 0 def test_dataset_getattr(self): # Test that pickling/unpickling converts the dask backend @@ -529,14 +529,14 @@ def test_dataset_getattr(self): coords={'y': ('x', nonindex_coord)}) with suppress(AttributeError): getattr(ds, 'NOTEXIST') - self.assertEquals(kernel_call_count, 0) + assert kernel_call_count == 0 def test_values(self): # Test that invoking the values property does not convert the dask # backend to numpy a = DataArray([1, 2]).chunk() self.assertFalse(a._in_memory) - self.assertEquals(a.values.tolist(), [1, 2]) + assert a.values.tolist() == [1, 2] self.assertFalse(a._in_memory) def test_from_dask_variable(self): diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index c3860bbb108..562459db7e6 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -73,12 +73,12 @@ def test_properties(self): self.assertItemsEqual(list(self.dv.coords), list(self.ds.coords)) for k, v in iteritems(self.dv.coords): self.assertArrayEqual(v, self.ds.coords[k]) - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): self.dv.dataset self.assertIsInstance(self.ds['x'].to_index(), pd.Index) - with self.assertRaisesRegexp(ValueError, 'must be 1-dimensional'): + with raises_regex(ValueError, 'must be 1-dimensional'): self.ds['foo'].to_index() - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): self.dv.variable = self.v def test_data_property(self): @@ -104,7 +104,7 @@ def test_get_index(self): dims=['x', 'y']) assert array.get_index('x').equals(pd.Index(['a', 'b'])) assert array.get_index('y').equals(pd.Index([0, 1, 2])) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): array.get_index('z') def test_get_index_size_zero(self): @@ -190,24 +190,24 @@ def test_dims(self): arr = self.dv self.assertEqual(arr.dims, ('x', 'y')) - with self.assertRaisesRegexp(AttributeError, 'you cannot assign'): + with raises_regex(AttributeError, 'you cannot assign'): arr.dims = ('w', 'z') def test_sizes(self): array = DataArray(np.zeros((3, 4)), dims=['x', 'y']) self.assertEqual(array.sizes, {'x': 3, 'y': 4}) self.assertEqual(tuple(array.sizes), array.dims) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): array.sizes['foo'] = 5 def test_encoding(self): expected = {'foo': 'bar'} self.dv.encoding['foo'] = 'bar' - self.assertEquals(expected, self.dv.encoding) + assert expected, self.d == encoding expected = {'baz': 0} self.dv.encoding = expected - self.assertEquals(expected, self.dv.encoding) + assert expected, self.d == encoding self.assertIsNot(expected, self.dv.encoding) def test_constructor(self): @@ -275,26 +275,26 @@ def test_constructor(self): def test_constructor_invalid(self): data = np.random.randn(3, 2) - with self.assertRaisesRegexp(ValueError, 'coords is not dict-like'): + with raises_regex(ValueError, 'coords is not dict-like'): DataArray(data, [[0, 1, 2]], ['x', 'y']) - with self.assertRaisesRegexp(ValueError, 'not a subset of the .* dim'): + with raises_regex(ValueError, 'not a subset of the .* dim'): DataArray(data, {'x': [0, 1, 2]}, ['a', 'b']) - with self.assertRaisesRegexp(ValueError, 'not a subset of the .* dim'): + with raises_regex(ValueError, 'not a subset of the .* dim'): DataArray(data, {'x': [0, 1, 2]}) - with self.assertRaisesRegexp(TypeError, 'is not a string'): + with raises_regex(TypeError, 'is not a string'): DataArray(data, dims=['x', None]) - with self.assertRaisesRegexp(ValueError, 'conflicting sizes for dim'): + with raises_regex(ValueError, 'conflicting sizes for dim'): DataArray([1, 2, 3], coords=[('x', [0, 1])]) - with self.assertRaisesRegexp(ValueError, 'conflicting sizes for dim'): + with raises_regex(ValueError, 'conflicting sizes for dim'): DataArray([1, 2], coords={'x': [0, 1], 'y': ('x', [1])}, dims='x') - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): DataArray(np.random.rand(4, 4), [('x', self.mindex), ('y', self.mindex)]) - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): DataArray(np.random.rand(4, 4), [('x', self.mindex), ('level_1', range(4))]) @@ -596,7 +596,7 @@ def test_isel_fancy(self): da.isel(x=(('points', ), x), y=(('points', ), y))) # make sure we're raising errors in the right places - with self.assertRaisesRegexp(IndexError, + with raises_regex(IndexError, 'Dimensions of indexers mismatch'): da.isel(y=(('points', ), [1, 2]), x=(('points', ), [1, 2, 3])) @@ -611,7 +611,7 @@ def test_isel_fancy(self): assert 'station' in actual.dims self.assertDataArrayIdentical(actual['station'], stations['station']) - with self.assertRaisesRegexp(ValueError, 'conflicting values for '): + with raises_regex(ValueError, 'conflicting values for '): da.isel(x=DataArray([0, 1, 2], dims='station', coords={'station': [0, 1, 2]}), y=DataArray([0, 1, 2], dims='station', @@ -758,20 +758,20 @@ def test_isel_points(self): da.isel_points(x=x, y=y)) # make sure we're raising errors in the right places - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'All indexers must be the same length'): da.isel_points(y=[1, 2], x=[1, 2, 3]) - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'dimension bad_key does not exist'): da.isel_points(bad_key=[1, 2]) - with self.assertRaisesRegexp(TypeError, 'Indexers must be integers'): + with raises_regex(TypeError, 'Indexers must be integers'): da.isel_points(y=[1.5, 2.2]) - with self.assertRaisesRegexp(TypeError, 'Indexers must be integers'): + with raises_regex(TypeError, 'Indexers must be integers'): da.isel_points(x=[1, 2, 3], y=slice(3)) - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'Indexers must be 1 dimensional'): da.isel_points(y=1, x=2) - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'Existing dimension names are not'): da.isel_points(y=[1, 2], x=[1, 2], dim='x') @@ -855,7 +855,7 @@ def test_sel(lab_indexer, pos_indexer, replaced_idx=False, mdata.sel(x=('a', 1))) self.assertDataArrayIdentical(mdata.loc[{'one': 'a'}, ...], mdata.sel(x={'one': 'a'})) - with self.assertRaises(IndexError): + with pytest.raises(IndexError): mdata.loc[('a', 1)] self.assertDataArrayIdentical(mdata.sel(x={'one': 'a', 'two': 1}), @@ -880,7 +880,7 @@ def test_coords(self): IndexVariable('y', np.array([0, 1, 2], 'int64'))] da = DataArray(np.random.randn(2, 3), coords, name='foo') - self.assertEquals(2, len(da.coords)) + assert 2 == len(da.coords) self.assertEqual(['x', 'y'], list(da.coords)) @@ -891,9 +891,9 @@ def test_coords(self): self.assertNotIn(0, da.coords) self.assertNotIn('foo', da.coords) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): da.coords[0] - with self.assertRaises(KeyError): + with pytest.raises(KeyError): da.coords['foo'] expected = dedent("""\ @@ -901,14 +901,14 @@ def test_coords(self): * x (x) int64 -1 -2 * y (y) int64 0 1 2""") actual = repr(da.coords) - self.assertEquals(expected, actual) + assert expected == actual del da.coords['x'] expected = DataArray(da.values, {'y': [0, 1, 2]}, dims=['x', 'y'], name='foo') self.assertDataArrayIdentical(da, expected) - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): self.mda['level_1'] = np.arange(4) self.mda.coords['level_1'] = np.arange(4) @@ -998,13 +998,13 @@ def test_reset_coords(self): dims=['x', 'y'], name='foo') self.assertDataArrayIdentical(actual, expected) - with self.assertRaisesRegexp(ValueError, 'cannot reset coord'): + with raises_regex(ValueError, 'cannot reset coord'): data.reset_coords(inplace=True) - with self.assertRaisesRegexp(ValueError, 'cannot be found'): + with raises_regex(ValueError, 'cannot be found'): data.reset_coords('foo', drop=True) - with self.assertRaisesRegexp(ValueError, 'cannot be found'): + with raises_regex(ValueError, 'cannot be found'): data.reset_coords('not_found') - with self.assertRaisesRegexp(ValueError, 'cannot remove index'): + with raises_regex(ValueError, 'cannot remove index'): data.reset_coords('y') def test_assign_coords(self): @@ -1019,7 +1019,7 @@ def test_assign_coords(self): expected.coords['d'] = ('x', [1.5, 1.5, 3.5, 3.5]) self.assertDataArrayIdentical(actual, expected) - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): self.mda.assign_coords(level_1=range(4)) def test_coords_alignment(self): @@ -1063,7 +1063,7 @@ def test_reindex_like_no_index(self): self.assertDatasetIdentical(foo, foo.reindex_like(foo)) bar = foo[:4] - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'different size for unlabeled'): foo.reindex_like(bar) @@ -1116,26 +1116,26 @@ def test_expand_dims_error(self): coords={'x': np.linspace(0.0, 1.0, 3.0)}, attrs={'key': 'entry'}) - with self.assertRaisesRegexp(ValueError, 'dim should be str or'): + with raises_regex(ValueError, 'dim should be str or'): array.expand_dims(0) - with self.assertRaisesRegexp(ValueError, 'lengths of dim and axis'): + with raises_regex(ValueError, 'lengths of dim and axis'): # dims and axis argument should be the same length array.expand_dims(dim=['a', 'b'], axis=[1, 2, 3]) - with self.assertRaisesRegexp(ValueError, 'Dimension x already'): + with raises_regex(ValueError, 'Dimension x already'): # Should not pass the already existing dimension. array.expand_dims(dim=['x']) # raise if duplicate - with self.assertRaisesRegexp(ValueError, 'duplicate values.'): + with raises_regex(ValueError, 'duplicate values.'): array.expand_dims(dim=['y', 'y']) - with self.assertRaisesRegexp(ValueError, 'duplicate values.'): + with raises_regex(ValueError, 'duplicate values.'): array.expand_dims(dim=['y', 'z'], axis=[1, 1]) - with self.assertRaisesRegexp(ValueError, 'duplicate values.'): + with raises_regex(ValueError, 'duplicate values.'): array.expand_dims(dim=['y', 'z'], axis=[2, -2]) # out of bounds error, axis must be in [-4, 3] - with self.assertRaises(IndexError): + with pytest.raises(IndexError): array.expand_dims(dim=['y', 'z'], axis=[2, 4]) - with self.assertRaises(IndexError): + with pytest.raises(IndexError): array.expand_dims(dim=['y', 'z'], axis=[2, -5]) # Does not raise an IndexError array.expand_dims(dim=['y', 'z'], axis=[2, -4]) @@ -1228,7 +1228,7 @@ def test_set_index(self): coords={'x': ('x', [0, 1]), 'level': ('y', [1, 2])}, dims=('x', 'y')) - with self.assertRaisesRegexp(ValueError, 'dimension mismatch'): + with raises_regex(ValueError, 'dimension mismatch'): array2d.set_index(x='level') def test_reset_index(self): @@ -1275,11 +1275,11 @@ def test_reorder_levels(self): self.assertDataArrayIdentical(array, expected) array = DataArray([1, 2], dims='x') - with self.assertRaises(KeyError): + with pytest.raises(KeyError): array.reorder_levels(x=['level_1', 'level_2']) array['x'] = [0, 1] - with self.assertRaisesRegexp(ValueError, 'has no MultiIndex'): + with raises_regex(ValueError, 'has no MultiIndex'): array.reorder_levels(x=['level_1', 'level_2']) def test_dataset_getitem(self): @@ -1357,9 +1357,9 @@ def test_inplace_math_basics(self): def test_inplace_math_automatic_alignment(self): a = DataArray(range(5), [('x', range(5))]) b = DataArray(range(1, 6), [('x', range(1, 6))]) - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): a += b - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): b += a def test_math_name(self): @@ -1532,14 +1532,14 @@ def test_drop_coordinates(self): actual = arr.drop('z') self.assertDataArrayIdentical(expected, actual) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): arr.drop('not found') - with self.assertRaisesRegexp(ValueError, 'cannot be found'): + with raises_regex(ValueError, 'cannot be found'): arr.drop(None) renamed = arr.rename('foo') - with self.assertRaisesRegexp(ValueError, 'cannot be found'): + with raises_regex(ValueError, 'cannot be found'): renamed.drop('foo') def test_drop_index_labels(self): @@ -1696,10 +1696,10 @@ def test_fillna(self): actual = a.fillna(b[:0]) self.assertDataArrayIdentical(a, actual) - with self.assertRaisesRegexp(TypeError, 'fillna on a DataArray'): + with raises_regex(TypeError, 'fillna on a DataArray'): a.fillna({0: 0}) - with self.assertRaisesRegexp(ValueError, 'broadcast'): + with raises_regex(ValueError, 'broadcast'): a.fillna([1, 2]) fill_value = DataArray([0, 1], dims='y') @@ -1864,11 +1864,11 @@ def test_groupby_math(self): actual_agg = actual.groupby('abc').mean() self.assertDataArrayAllClose(expected_agg, actual_agg) - with self.assertRaisesRegexp(TypeError, 'only support binary ops'): + with raises_regex(TypeError, 'only support binary ops'): grouped + 1 - with self.assertRaisesRegexp(TypeError, 'only support binary ops'): + with raises_regex(TypeError, 'only support binary ops'): grouped + grouped - with self.assertRaisesRegexp(TypeError, 'in-place operations'): + with raises_regex(TypeError, 'in-place operations'): array += grouped def test_groupby_math_not_aligned(self): @@ -2009,7 +2009,7 @@ def test_resample(self): actual = array.resample(time='24H').reduce(np.mean) self.assertDataArrayIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'index must be monotonic'): + with raises_regex(ValueError, 'index must be monotonic'): array[[2, 0, 1]].resample(time='1D') def test_resample_first(self): @@ -2048,7 +2048,7 @@ def test_resample_first(self): def test_resample_bad_resample_dim(self): times = pd.date_range('2000-01-01', freq='6H', periods=10) array = DataArray(np.arange(10), [('__resample_dim__', times)]) - with self.assertRaisesRegexp(ValueError, 'Proxy resampling dimension'): + with raises_regex(ValueError, 'Proxy resampling dimension'): array.resample(**{'__resample_dim__': '1D'}).first() @requires_scipy @@ -2271,7 +2271,7 @@ def test_upsample_interpolate_dask(self): {'time': times, 'x': xs, 'y': ys}, ('x', 'y', 'time')) - with self.assertRaisesRegexp(TypeError, + with raises_regex(TypeError, "dask arrays are not yet supported"): array.resample(time='1H').interpolate('linear') @@ -2371,11 +2371,11 @@ def test_align_mixed_indexes(self): self.assertDatasetIdentical(result1, array_with_coord) def test_align_without_indexes_errors(self): - with self.assertRaisesRegexp(ValueError, 'cannot be aligned'): + with raises_regex(ValueError, 'cannot be aligned'): align(DataArray([1, 2, 3], dims=['x']), DataArray([1, 2], dims=['x'])) - with self.assertRaisesRegexp(ValueError, 'cannot be aligned'): + with raises_regex(ValueError, 'cannot be aligned'): align(DataArray([1, 2, 3], dims=['x']), DataArray([1, 2], coords=[('x', [0, 1])])) @@ -2487,7 +2487,7 @@ def test_to_pandas(self): roundtripped = DataArray(da.to_pandas()).drop(dims) self.assertDataArrayIdentical(da, roundtripped) - with self.assertRaisesRegexp(ValueError, 'cannot convert'): + with raises_regex(ValueError, 'cannot convert'): DataArray(np.random.randn(1, 2, 3, 4, 5)).to_pandas() def test_to_dataframe(self): @@ -2511,7 +2511,7 @@ def test_to_dataframe(self): self.assertArrayEqual(expected.index.values, actual.index.values) arr.name = None # unnamed - with self.assertRaisesRegexp(ValueError, 'unnamed'): + with raises_regex(ValueError, 'unnamed'): arr.to_dataframe() def test_to_pandas_name_matches_coordinate(self): @@ -2586,14 +2586,14 @@ def test_to_and_from_dict(self): d = {'dims': ('x', 'y'), 'data': array.values, 'coords': {'x': {'data': ['a', 'b']}}} - with self.assertRaisesRegexp( + with raises_regex( ValueError, "cannot convert dict when coords are missing the key 'dims'"): DataArray.from_dict(d) # this one is missing some necessary information d = {'dims': ('t')} - with self.assertRaisesRegexp( + with raises_regex( ValueError, "cannot convert dict without the key 'data'"): DataArray.from_dict(d) @@ -2703,7 +2703,7 @@ def test_to_and_from_cdms2(self): def test_to_dataset_whole(self): unnamed = DataArray([1, 2], dims='x') - with self.assertRaisesRegexp(ValueError, 'unable to convert unnamed'): + with raises_regex(ValueError, 'unable to convert unnamed'): unnamed.to_dataset() actual = unnamed.to_dataset(name='foo') @@ -2728,7 +2728,7 @@ def test_to_dataset_split(self): actual = array.to_dataset('x') self.assertDatasetIdentical(expected, actual) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): array.to_dataset('x', name='foo') roundtripped = actual.to_array(dim='x') @@ -2815,11 +2815,11 @@ def test_real_and_imag(self): def test_setattr_raises(self): array = DataArray(0, coords={'scalar': 1}, attrs={'foo': 'bar'}) - with self.assertRaisesRegexp(AttributeError, 'cannot set attr'): + with raises_regex(AttributeError, 'cannot set attr'): array.scalar = 2 - with self.assertRaisesRegexp(AttributeError, 'cannot set attr'): + with raises_regex(AttributeError, 'cannot set attr'): array.foo = 2 - with self.assertRaisesRegexp(AttributeError, 'cannot set attr'): + with raises_regex(AttributeError, 'cannot set attr'): array.other = 2 def test_full_like(self): @@ -2838,7 +2838,7 @@ def test_full_like(self): # override dtype actual = full_like(da, fill_value=True, dtype=bool) expect.values = [[True, True], [True, True]] - self.assertEquals(expect.dtype, bool) + assert expect.dtype == bool self.assertDataArrayIdentical(expect, actual) def test_dot(self): @@ -2873,11 +2873,11 @@ def test_dot(self): expected = DataArray(expected_vals, coords=[x, j], dims=['x', 'j']) self.assertDataArrayEqual(expected, actual) - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): da.dot(dm.to_dataset(name='dm')) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): da.dot(dm.values) - with self.assertRaisesRegexp(ValueError, 'no shared dimensions'): + with raises_regex(ValueError, 'no shared dimensions'): da.dot(DataArray(1)) def test_binary_op_join_setting(self): diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index cfb5d4367c4..87be07f50b0 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -233,13 +233,13 @@ def test_constructor(self): x2 = ('x', np.arange(1000)) z = (['x', 'y'], np.arange(1000).reshape(100, 10)) - with self.assertRaisesRegexp(ValueError, 'conflicting sizes'): + with raises_regex(ValueError, 'conflicting sizes'): Dataset({'a': x1, 'b': x2}) - with self.assertRaisesRegexp(ValueError, "disallows such variables"): + with raises_regex(ValueError, "disallows such variables"): Dataset({'a': x1, 'x': z}) - with self.assertRaisesRegexp(TypeError, 'tuples to convert'): + with raises_regex(TypeError, 'tuples to convert'): Dataset({'x': (1, 2, 3, 4, 5, 6, 7)}) - with self.assertRaisesRegexp(ValueError, 'already exists as a scalar'): + with raises_regex(ValueError, 'already exists as a scalar'): Dataset({'x': 0, 'y': ('x', [1, 2, 3])}) # verify handling of DataArrays @@ -249,7 +249,7 @@ def test_constructor(self): def test_constructor_invalid_dims(self): # regression for GH1120 - with self.assertRaises(MergeError): + with pytest.raises(MergeError): Dataset(data_vars=dict(v=('y', [1, 2, 3, 4])), coords=dict(y=DataArray([.1, .2, .3, .4], dims='x'))) @@ -281,7 +281,7 @@ class Arbitrary(object): self.assertDatasetIdentical(expected, actual) def test_constructor_deprecated(self): - with self.assertRaisesRegexp(ValueError, 'DataArray dimensions'): + with raises_regex(ValueError, 'DataArray dimensions'): DataArray([1, 2, 3], coords={'x': [0, 1, 2]}) def test_constructor_auto_align(self): @@ -311,7 +311,7 @@ def test_constructor_auto_align(self): self.assertDatasetIdentical(expected3, actual) e = ('x', [0, 0]) - with self.assertRaisesRegexp(ValueError, 'conflicting sizes'): + with raises_regex(ValueError, 'conflicting sizes'): Dataset({'a': a, 'b': b, 'e': e}) def test_constructor_pandas_sequence(self): @@ -349,7 +349,7 @@ def test_constructor_pandas_single(self): def test_constructor_compat(self): data = OrderedDict([('x', DataArray(0, coords={'y': 1})), ('y', ('z', [1, 1, 1]))]) - with self.assertRaises(MergeError): + with pytest.raises(MergeError): Dataset(data, compat='equals') expected = Dataset({'x': 0}, {'y': ('z', [1, 1, 1])}) actual = Dataset(data) @@ -375,7 +375,7 @@ def test_constructor_compat(self): self.assertDatasetIdentical(expected, actual) data = {'x': DataArray(0, coords={'y': 3}), 'y': ('z', [1, 1, 1])} - with self.assertRaises(MergeError): + with pytest.raises(MergeError): Dataset(data) data = {'x': DataArray(0, coords={'y': 1}), 'y': [1, 1]} @@ -384,7 +384,7 @@ def test_constructor_compat(self): self.assertDatasetIdentical(expected, actual) def test_constructor_with_coords(self): - with self.assertRaisesRegexp(ValueError, 'found in both data_vars and'): + with raises_regex(ValueError, 'found in both data_vars and'): Dataset({'a': ('x', [1])}, {'a': ('x', [1])}) ds = Dataset({}, {'a': ('x', [1])}) @@ -393,7 +393,7 @@ def test_constructor_with_coords(self): mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2]], names=('level_1', 'level_2')) - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): Dataset({}, {'x': mindex, 'y': mindex}) Dataset({}, {'x': mindex, 'level_1': range(4)}) @@ -442,7 +442,7 @@ def test_get_index(self): coords={'x': ['a', 'b']}) assert ds.get_index('x').equals(pd.Index(['a', 'b'])) assert ds.get_index('y').equals(pd.Index([0, 1, 2])) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): ds.get_index('z') def test_attr_access(self): @@ -473,7 +473,7 @@ def test_variable(self): self.assertEqual(list(a), ['foo', 'bar']) self.assertArrayEqual(a['foo'].values, d) # try to add variable with dim (10,3) with data that's (3,10) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): a['qux'] = (('time', 'x'), d.T) def test_modify_inplace(self): @@ -491,14 +491,14 @@ def test_modify_inplace(self): # this should work a['x'] = ('x', vec[:5]) a['z'] = ('x', np.arange(5)) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): # now it shouldn't, since there is a conflicting length a['x'] = ('x', vec[:4]) arr = np.random.random((10, 1,)) scal = np.array(0) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): a['y'] = ('y', arr) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): a['y'] = ('y', scal) self.assertTrue('y' not in a.dims) @@ -525,9 +525,9 @@ def test_coords_properties(self): self.assertNotIn(0, data.coords) self.assertNotIn('foo', data.coords) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data.coords['foo'] - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data.coords[0] expected = dedent("""\ @@ -556,7 +556,7 @@ def test_coords_modify(self): self.assertArrayEqual(actual['z'], ['a', 'b']) actual = data.copy(deep=True) - with self.assertRaisesRegexp(ValueError, 'conflicting sizes'): + with raises_regex(ValueError, 'conflicting sizes'): actual.coords['x'] = ('x', [-1]) self.assertDatasetIdentical(actual, data) # should not be modified @@ -565,10 +565,10 @@ def test_coords_modify(self): expected = data.reset_coords('b', drop=True) self.assertDatasetIdentical(expected, actual) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): del data.coords['not_found'] - with self.assertRaises(KeyError): + with pytest.raises(KeyError): del data.coords['foo'] actual = data.copy(deep=True) @@ -584,7 +584,7 @@ def test_coords_setitem_with_new_dimension(self): def test_coords_setitem_multiindex(self): data = create_test_multiindex() - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): data.coords['level_1'] = range(4) def test_coords_set(self): @@ -621,7 +621,7 @@ def test_coords_set(self): actual = all_coords.reset_coords('zzz') self.assertDatasetIdentical(two_coords, actual) - with self.assertRaisesRegexp(ValueError, 'cannot remove index'): + with raises_regex(ValueError, 'cannot remove index'): one_coord.reset_coords('x') actual = all_coords.reset_coords('zzz', drop=True) @@ -649,13 +649,13 @@ def test_coords_merge(self): self.assertDatasetIdentical(expected, actual) other_coords = Dataset(coords={'x': ('x', ['a'])}).coords - with self.assertRaises(MergeError): + with pytest.raises(MergeError): orig_coords.merge(other_coords) other_coords = Dataset(coords={'x': ('x', ['a', 'b'])}).coords - with self.assertRaises(MergeError): + with pytest.raises(MergeError): orig_coords.merge(other_coords) other_coords = Dataset(coords={'x': ('x', ['a', 'b', 'c'])}).coords - with self.assertRaises(MergeError): + with pytest.raises(MergeError): orig_coords.merge(other_coords) other_coords = Dataset(coords={'a': ('x', [8, 9])}).coords @@ -780,7 +780,7 @@ def test_chunk(self): self.assertEqual(reblocked.chunks, expected_chunks) self.assertDatasetIdentical(reblocked, data) - with self.assertRaisesRegexp(ValueError, 'some chunks'): + with raises_regex(ValueError, 'some chunks'): data.chunk({'foo': 10}) @requires_dask @@ -789,9 +789,9 @@ def test_dask_is_lazy(self): create_test_data().dump_to_store(store) ds = open_dataset(store).chunk() - with self.assertRaises(UnexpectedDataAccess): + with pytest.raises(UnexpectedDataAccess): ds.load() - with self.assertRaises(UnexpectedDataAccess): + with pytest.raises(UnexpectedDataAccess): ds['var1'].values # these should not raise UnexpectedDataAccess: @@ -832,7 +832,7 @@ def test_isel(self): actual = ret[v].values np.testing.assert_array_equal(expected, actual) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): data.isel(not_a_dim=slice(0, 2)) ret = data.isel(dim1=0) @@ -924,11 +924,11 @@ def test_isel_fancy(self): data.isel(dim2=(('points', ), pdim2), dim1=(('points', ), pdim1))) # make sure we're raising errors in the right places - with self.assertRaisesRegexp(IndexError, + with raises_regex(IndexError, 'Dimensions of indexers mismatch'): data.isel(dim1=(('points', ), [1, 2]), dim2=(('points', ), [1, 2, 3])) - with self.assertRaisesRegexp(TypeError, 'cannot use a Dataset'): + with raises_regex(TypeError, 'cannot use a Dataset'): data.isel(dim1=Dataset({'points': [1, 2]})) # test to be sure we keep around variables that were not indexed @@ -949,7 +949,7 @@ def test_isel_fancy(self): self.assertDataArrayIdentical(actual['station'].drop(['dim2']), stations['station']) - with self.assertRaisesRegexp(ValueError, 'conflicting values for '): + with raises_regex(ValueError, 'conflicting values for '): data.isel(dim1=DataArray([0, 1, 2], dims='station', coords={'station': [0, 1, 2]}), dim2=DataArray([0, 1, 2], dims='station', @@ -996,14 +996,14 @@ def test_isel_dataarray(self): # Conflict in the dimension coordinate indexing_da = DataArray(np.arange(1, 4), dims=['dim2'], coords={'dim2': np.random.randn(3)}) - with self.assertRaisesRegexp( + with raises_regex( IndexError, "dimension coordinate 'dim2'"): actual = data.isel(dim2=indexing_da) # Also the case for DataArray - with self.assertRaisesRegexp( + with raises_regex( IndexError, "dimension coordinate 'dim2'"): actual = data['var2'].isel(dim2=indexing_da) - with self.assertRaisesRegexp( + with raises_regex( IndexError, "dimension coordinate 'dim2'"): data['dim2'].isel(dim2=indexing_da) @@ -1059,7 +1059,7 @@ def test_isel_dataarray(self): # indexer generated from coordinates indexing_ds = Dataset({}, coords={'dim2': [0, 1, 2]}) - with self.assertRaisesRegexp( + with raises_regex( IndexError, "dimension coordinate 'dim2'"): actual = data.isel(dim2=indexing_ds['dim2']) @@ -1190,10 +1190,10 @@ def test_sel_dataarray_mindex(self): self.assertDatasetIdentical(actual_isel, actual_sel) # Vectorized indexing with level-variables raises an error - with self.assertRaisesRegexp(ValueError, 'Vectorized selection is '): + with raises_regex(ValueError, 'Vectorized selection is '): mds.sel(one=['a', 'b']) - with self.assertRaisesRegexp(ValueError, 'Vectorized selection is ' + with raises_regex(ValueError, 'Vectorized selection is ' 'not available along MultiIndex variable:' ' x'): mds.sel(x=xr.DataArray([np.array(midx[:2]), np.array(midx[-2:])], @@ -1246,20 +1246,20 @@ def test_isel_points(self): data.isel_points(dim2=pdim2, dim1=pdim1)) # make sure we're raising errors in the right places - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'All indexers must be the same length'): data.isel_points(dim1=[1, 2], dim2=[1, 2, 3]) - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'dimension bad_key does not exist'): data.isel_points(bad_key=[1, 2]) - with self.assertRaisesRegexp(TypeError, 'Indexers must be integers'): + with raises_regex(TypeError, 'Indexers must be integers'): data.isel_points(dim1=[1.5, 2.2]) - with self.assertRaisesRegexp(TypeError, 'Indexers must be integers'): + with raises_regex(TypeError, 'Indexers must be integers'): data.isel_points(dim1=[1, 2, 3], dim2=slice(3)) - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'Indexers must be 1 dimensional'): data.isel_points(dim1=1, dim2=2) - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'Existing dimension names are not valid'): data.isel_points(dim1=[1, 2], dim2=[1, 2], dim='dim2') @@ -1327,7 +1327,7 @@ def test_sel_points(self): method='pad') self.assertDatasetIdentical(expected, actual) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data.sel_points(x=[2.5], y=[2.0], method='pad', tolerance=1e-3) def test_sel_fancy(self): @@ -1401,7 +1401,7 @@ def test_sel_fancy(self): self.assertDataArrayIdentical(actual['a'].drop('x'), idx_x['a']) self.assertDataArrayIdentical(actual['b'].drop('y'), idx_y['b']) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data.sel_points(x=[2.5], y=[2.0], method='pad', tolerance=1e-3) def test_sel_method(self): @@ -1414,22 +1414,22 @@ def test_sel_method(self): actual = data.sel(dim2=0.95, method='nearest', tolerance=1) self.assertDatasetIdentical(expected, actual) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): actual = data.sel(dim2=np.pi, method='nearest', tolerance=0) expected = data.sel(dim2=[1.5]) actual = data.sel(dim2=[1.45], method='backfill') self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(NotImplementedError, 'slice objects'): + with raises_regex(NotImplementedError, 'slice objects'): data.sel(dim2=slice(1, 3), method='ffill') - with self.assertRaisesRegexp(TypeError, '``method``'): + with raises_regex(TypeError, '``method``'): # this should not pass silently data.sel(data) # cannot pass method if there is no associated coordinate - with self.assertRaisesRegexp(ValueError, 'cannot supply'): + with raises_regex(ValueError, 'cannot supply'): data.sel(dim1=0, method='nearest') def test_loc(self): @@ -1437,9 +1437,9 @@ def test_loc(self): expected = data.sel(dim3='a') actual = data.loc[dict(dim3='a')] self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(TypeError, 'can only lookup dict'): + with raises_regex(TypeError, 'can only lookup dict'): data.loc['a'] - with self.assertRaises(TypeError): + with pytest.raises(TypeError): data.loc[dict(dim3='a')] = 0 def test_selection_multiindex(self): @@ -1521,7 +1521,7 @@ def test_reindex(self): actual = data.reindex(dim1=data['dim1'].to_index()) self.assertDatasetIdentical(actual, expected) - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'cannot reindex or align along dimension'): data.reindex(dim1=data['dim1'][:5]) @@ -1533,13 +1533,13 @@ def test_reindex(self): actual = data.reindex({'dim2': data['dim2']}) expected = data self.assertDatasetIdentical(actual, expected) - with self.assertRaisesRegexp(ValueError, 'cannot specify both'): + with raises_regex(ValueError, 'cannot specify both'): data.reindex({'x': 0}, x=0) - with self.assertRaisesRegexp(ValueError, 'dictionary'): + with raises_regex(ValueError, 'dictionary'): data.reindex('foo') # invalid dimension - with self.assertRaisesRegexp(ValueError, 'invalid reindex dim'): + with raises_regex(ValueError, 'invalid reindex dim'): data.reindex(invalid=0) # out of order @@ -1642,9 +1642,9 @@ def test_align(self): right2.sel(dim3=intersection)) self.assertTrue(np.isnan(left2['var3'][-2:]).all()) - with self.assertRaisesRegexp(ValueError, 'invalid value for join'): + with raises_regex(ValueError, 'invalid value for join'): align(left, right, join='foobar') - with self.assertRaises(TypeError): + with pytest.raises(TypeError): align(left, right, foo='bar') def test_align_exact(self): @@ -1655,7 +1655,7 @@ def test_align_exact(self): self.assertDatasetIdentical(left1, left) self.assertDatasetIdentical(left2, left) - with self.assertRaisesRegexp(ValueError, 'indexes .* not equal'): + with raises_regex(ValueError, 'indexes .* not equal'): xr.align(left, right, join='exact') def test_align_exclude(self): @@ -1707,7 +1707,7 @@ def test_align_non_unique(self): assert x1.identical(x) and x2.identical(x) y = Dataset({'bar': ('x', [6, 7]), 'x': [0, 1]}) - with self.assertRaisesRegexp(ValueError, 'cannot reindex or align'): + with raises_regex(ValueError, 'cannot reindex or align'): align(x, y) def test_broadcast(self): @@ -1807,7 +1807,7 @@ def test_drop_variables(self): actual = data.drop(['time']) self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'cannot be found'): + with raises_regex(ValueError, 'cannot be found'): data.drop('not_found_here') def test_drop_index_labels(self): @@ -1822,11 +1822,11 @@ def test_drop_index_labels(self): expected = data.isel(x=slice(0, 0)) self.assertDatasetIdentical(expected, actual) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): # not contained in axis data.drop(['c'], dim='x') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'does not have coordinate labels'): data.drop(1, 'y') @@ -1876,24 +1876,24 @@ def test_rename(self): self.assertTrue('var1' not in renamed) self.assertTrue('dim2' not in renamed) - with self.assertRaisesRegexp(ValueError, "cannot rename 'not_a_var'"): + with raises_regex(ValueError, "cannot rename 'not_a_var'"): data.rename({'not_a_var': 'nada'}) - with self.assertRaisesRegexp(ValueError, "'var1' conflicts"): + with raises_regex(ValueError, "'var1' conflicts"): data.rename({'var2': 'var1'}) # verify that we can rename a variable without accessing the data var1 = data['var1'] data['var1'] = (var1.dims, InaccessibleArray(var1.values)) renamed = data.rename(newnames) - with self.assertRaises(UnexpectedDataAccess): + with pytest.raises(UnexpectedDataAccess): renamed['renamed_var1'].values def test_rename_old_name(self): # regtest for GH1477 data = create_test_data() - with self.assertRaisesRegexp(ValueError, "'samecol' conflicts"): + with raises_regex(ValueError, "'samecol' conflicts"): data.rename({'var1': 'samecol', 'var2': 'samecol'}) # This shouldn't cause any problems. @@ -1913,7 +1913,7 @@ def test_rename_inplace(self): data.rename({'x': 'y'}, inplace=True) self.assertDatasetIdentical(data, renamed) self.assertFalse(data.equals(copied)) - self.assertEquals(data.dims, {'y': 3, 't': 3}) + assert data.dims == {'y': 3, 't': 3} # check virtual variables self.assertArrayEqual(data['t.dayofyear'], [1, 2, 3]) @@ -1932,9 +1932,9 @@ def test_swap_dims(self): actual.swap_dims({'x': 'y'}, inplace=True) self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'cannot swap'): + with raises_regex(ValueError, 'cannot swap'): original.swap_dims({'y': 'x'}) - with self.assertRaisesRegexp(ValueError, 'replacement dimension'): + with raises_regex(ValueError, 'replacement dimension'): original.swap_dims({'x': 'z'}) def test_expand_dims_error(self): @@ -1946,13 +1946,13 @@ def test_expand_dims_error(self): 'c': np.linspace(0, 1, 5)}, attrs={'key': 'entry'}) - with self.assertRaisesRegexp(ValueError, 'already exists'): + with raises_regex(ValueError, 'already exists'): original.expand_dims(dim=['x']) # Make sure it raises true error also for non-dimensional coordinates # which has dimension. original.set_coords('z', inplace=True) - with self.assertRaisesRegexp(ValueError, 'already exists'): + with raises_regex(ValueError, 'already exists'): original.expand_dims(dim=['z']) def test_expand_dims(self): @@ -2027,7 +2027,7 @@ def test_reorder_levels(self): self.assertDatasetIdentical(ds, expected) ds = Dataset({}, coords={'x': [1, 2]}) - with self.assertRaisesRegexp(ValueError, 'has no MultiIndex'): + with raises_regex(ValueError, 'has no MultiIndex'): ds.reorder_levels(x=['level_1', 'level_2']) def test_stack(self): @@ -2063,9 +2063,9 @@ def test_unstack(self): def test_unstack_errors(self): ds = Dataset({'x': [1, 2, 3]}) - with self.assertRaisesRegexp(ValueError, 'invalid dimension'): + with raises_regex(ValueError, 'invalid dimension'): ds.unstack('foo') - with self.assertRaisesRegexp(ValueError, 'does not have a MultiIndex'): + with raises_regex(ValueError, 'does not have a MultiIndex'): ds.unstack('x') def test_stack_unstack(self): @@ -2109,7 +2109,7 @@ def test_update_auto_align(self): {'t': [0, 1]}) actual = ds.copy() other = {'y': ('t', [5]), 't': [1]} - with self.assertRaisesRegexp(ValueError, 'conflicting sizes'): + with raises_regex(ValueError, 'conflicting sizes'): actual.update(other) actual.update(Dataset(other)) self.assertDatasetIdentical(expected, actual) @@ -2125,9 +2125,9 @@ def test_getitem(self): data = create_test_data() self.assertIsInstance(data['var1'], DataArray) self.assertVariableEqual(data['var1'].variable, data.variables['var1']) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data['notfound'] - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data[['var1', 'notfound']] actual = data[['var1', 'var2']] @@ -2151,7 +2151,7 @@ def test_getitem_hashable(self): expected = data['var1'] + 1 expected.name = (3, 4) self.assertDataArrayIdentical(expected, data[(3, 4)]) - with self.assertRaisesRegexp(KeyError, "('var1', 'var2')"): + with raises_regex(KeyError, "('var1', 'var2')"): data[('var1', 'var2')] def test_virtual_variables_default_coords(self): @@ -2238,7 +2238,7 @@ def test_setitem(self): data2['B'] = dv self.assertDatasetIdentical(data1, data2) # can't assign an ND array without dimensions - with self.assertRaisesRegexp(ValueError, + with raises_regex(ValueError, 'without explicit dimension names'): data2['C'] = var.values.reshape(2, 4) # but can assign a 1D array @@ -2250,16 +2250,16 @@ def test_setitem(self): data2['scalar'] = ([], 0) self.assertDatasetIdentical(data1, data2) # can't use the same dimension name as a scalar var - with self.assertRaisesRegexp(ValueError, 'already exists as a scalar'): + with raises_regex(ValueError, 'already exists as a scalar'): data1['newvar'] = ('scalar', [3, 4, 5]) # can't resize a used dimension - with self.assertRaisesRegexp(ValueError, 'arguments without labels'): + with raises_regex(ValueError, 'arguments without labels'): data1['dim1'] = data1['dim1'][:5] # override an existing value data1['A'] = 3 * data2['A'] self.assertVariableEqual(data1['A'], 3 * data2['A']) - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): data1[{'x': 0}] = 0 def test_setitem_pandas(self): @@ -2345,7 +2345,7 @@ def test_assign_attrs(self): def test_assign_multiindex_level(self): data = create_test_multiindex() - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): data.assign(level_1=range(4)) data.assign_coords(level_1=range(4)) @@ -2380,7 +2380,7 @@ def test_setitem_both_non_unique_index(self): def test_setitem_multiindex_level(self): data = create_test_multiindex() - with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'): + with raises_regex(ValueError, 'conflicting MultiIndex'): data['level_1'] = range(4) def test_delitem(self): @@ -2403,7 +2403,7 @@ def get_args(v): expected.set_coords(data.coords, inplace=True) self.assertDatasetIdentical(expected, data.squeeze(*args)) # invalid squeeze - with self.assertRaisesRegexp(ValueError, 'cannot select a dimension'): + with raises_regex(ValueError, 'cannot select a dimension'): data.squeeze('y') def test_squeeze_drop(self): @@ -2471,11 +2471,11 @@ def test_groupby_iter(self): def test_groupby_errors(self): data = create_test_data() - with self.assertRaisesRegexp(TypeError, '`group` must be'): + with raises_regex(TypeError, '`group` must be'): data.groupby(np.arange(10)) - with self.assertRaisesRegexp(ValueError, 'length does not match'): + with raises_regex(ValueError, 'length does not match'): data.groupby(data['dim1'][:3]) - with self.assertRaisesRegexp(TypeError, "`group` must be"): + with raises_regex(TypeError, "`group` must be"): data.groupby(data.coords['dim1'].to_index()) def test_groupby_reduce(self): @@ -2533,20 +2533,20 @@ def test_groupby_math(self): actual = zeros + grouped self.assertDatasetEqual(expected, actual) - with self.assertRaisesRegexp(ValueError, 'incompat.* grouped binary'): + with raises_regex(ValueError, 'incompat.* grouped binary'): grouped + ds - with self.assertRaisesRegexp(ValueError, 'incompat.* grouped binary'): + with raises_regex(ValueError, 'incompat.* grouped binary'): ds + grouped - with self.assertRaisesRegexp(TypeError, 'only support binary ops'): + with raises_regex(TypeError, 'only support binary ops'): grouped + 1 - with self.assertRaisesRegexp(TypeError, 'only support binary ops'): + with raises_regex(TypeError, 'only support binary ops'): grouped + grouped - with self.assertRaisesRegexp(TypeError, 'in-place operations'): + with raises_regex(TypeError, 'in-place operations'): ds += grouped ds = Dataset({'x': ('time', np.arange(100)), 'time': pd.date_range('2000-01-01', periods=100)}) - with self.assertRaisesRegexp(ValueError, 'incompat.* grouped binary'): + with raises_regex(ValueError, 'incompat.* grouped binary'): ds + ds.groupby('time.month') def test_groupby_math_virtual(self): @@ -2778,7 +2778,7 @@ def test_from_dataframe_non_unique_columns(self): # regression test for GH449 df = pd.DataFrame(np.zeros((2, 2))) df.columns = ['foo', 'foo'] - with self.assertRaisesRegexp(ValueError, 'non-unique columns'): + with raises_regex(ValueError, 'non-unique columns'): Dataset.from_dataframe(df) def test_convert_dataframe_with_many_types_and_multiindex(self): @@ -2861,7 +2861,7 @@ def test_to_and_from_dict(self): d = {'a': {'data': x}, 't': {'data': t, 'dims': 't'}, 'b': {'dims': 't', 'data': y}} - with self.assertRaisesRegexp(ValueError, "cannot convert dict " + with raises_regex(ValueError, "cannot convert dict " "without the key 'dims'"): Dataset.from_dict(d) @@ -2924,9 +2924,9 @@ def test_lazy_load(self): for decode_cf in [True, False]: ds = open_dataset(store, decode_cf=decode_cf) - with self.assertRaises(UnexpectedDataAccess): + with pytest.raises(UnexpectedDataAccess): ds.load() - with self.assertRaises(UnexpectedDataAccess): + with pytest.raises(UnexpectedDataAccess): ds['var1'].values # these should not raise UnexpectedDataAccess: @@ -2986,11 +2986,11 @@ def test_dropna(self): expected = ds.isel(a=[1, 3]) self.assertDatasetIdentical(actual, ds) - with self.assertRaisesRegexp(ValueError, 'a single dataset dimension'): + with raises_regex(ValueError, 'a single dataset dimension'): ds.dropna('foo') - with self.assertRaisesRegexp(ValueError, 'invalid how'): + with raises_regex(ValueError, 'invalid how'): ds.dropna('a', how='somehow') - with self.assertRaisesRegexp(TypeError, 'must specify how or thresh'): + with raises_regex(TypeError, 'must specify how or thresh'): ds.dropna('a', how=None) def test_fillna(self): @@ -3035,7 +3035,7 @@ def test_fillna(self): self.assertDatasetIdentical(expected, actual) # but new data variables is not okay - with self.assertRaisesRegexp(ValueError, 'must be contained'): + with raises_regex(ValueError, 'must be contained'): ds.fillna({'x': 0}) # empty argument should be OK @@ -3165,7 +3165,7 @@ def test_where_drop(self): actual = ds.where(ds.a > 1, drop=True) self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(TypeError, 'must be a'): + with raises_regex(TypeError, 'must be a'): ds.where(np.arange(5) > 1, drop=True) # 1d with odd coordinates @@ -3251,17 +3251,17 @@ def test_reduce(self): def test_reduce_bad_dim(self): data = create_test_data() - with self.assertRaisesRegexp(ValueError, 'Dataset does not contain'): + with raises_regex(ValueError, 'Dataset does not contain'): ds = data.mean(dim='bad_dim') def test_reduce_cumsum_test_dims(self): data = create_test_data() for cumfunc in ['cumsum', 'cumprod']: - with self.assertRaisesRegexp(ValueError, "must supply either single 'dim' or 'axis'"): + with raises_regex(ValueError, "must supply either single 'dim' or 'axis'"): ds = getattr(data, cumfunc)() - with self.assertRaisesRegexp(ValueError, "must supply either single 'dim' or 'axis'"): + with raises_regex(ValueError, "must supply either single 'dim' or 'axis'"): ds = getattr(data, cumfunc)(dim=['dim1', 'dim2']) - with self.assertRaisesRegexp(ValueError, 'Dataset does not contain'): + with raises_regex(ValueError, 'Dataset does not contain'): ds = getattr(data, cumfunc)(dim='bad_dim') # ensure dimensions are correct @@ -3377,10 +3377,10 @@ def mean_only_one_axis(x, axis): actual = ds.reduce(mean_only_one_axis, 'y') self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(TypeError, 'non-integer axis'): + with raises_regex(TypeError, 'non-integer axis'): ds.reduce(mean_only_one_axis) - with self.assertRaisesRegexp(TypeError, 'non-integer axis'): + with raises_regex(TypeError, 'non-integer axis'): ds.reduce(mean_only_one_axis, ['x', 'y']) def test_quantile(self): @@ -3467,9 +3467,9 @@ def test_unary_ops(self): self.assertDatasetIdentical(ds.isnull(), ~ds.notnull()) # don't actually patch these methods in - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): ds.item - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): ds.searchsorted def test_dataset_array_math(self): @@ -3552,11 +3552,11 @@ def test_dataset_math_auto_align(self): def test_dataset_math_errors(self): ds = self.make_example_math_dataset() - with self.assertRaises(TypeError): + with pytest.raises(TypeError): ds['foo'] += ds - with self.assertRaises(TypeError): + with pytest.raises(TypeError): ds['foo'].variable += ds - with self.assertRaisesRegexp(ValueError, 'must have the same'): + with raises_regex(ValueError, 'must have the same'): ds += ds[['bar']] # verify we can rollback in-place operations if something goes wrong @@ -3564,7 +3564,7 @@ def test_dataset_math_errors(self): # but not floats thanks to numpy's inconsistent handling other = DataArray(np.datetime64('2000-01-01T12'), coords={'c': 2}) actual = ds.copy(deep=True) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): actual += other self.assertDatasetIdentical(actual, ds) @@ -3595,9 +3595,9 @@ def test_dataset_transpose(self): expected_dims = tuple(d for d in new_order if d in ds[k].dims) self.assertEqual(actual[k].dims, expected_dims) - with self.assertRaisesRegexp(ValueError, 'arguments to transpose'): + with raises_regex(ValueError, 'arguments to transpose'): ds.transpose('dim1', 'dim2', 'dim3') - with self.assertRaisesRegexp(ValueError, 'arguments to transpose'): + with raises_regex(ValueError, 'arguments to transpose'): ds.transpose('dim1', 'dim2', 'dim3', 'time', 'extra_dim') def test_dataset_retains_period_index_on_transpose(self): @@ -3657,12 +3657,12 @@ def test_dataset_diff_n2(self): def test_dataset_diff_exception_n_neg(self): ds = create_test_data(seed=1) - with self.assertRaisesRegexp(ValueError, 'must be non-negative'): + with raises_regex(ValueError, 'must be non-negative'): ds.diff('dim2', n=-1) def test_dataset_diff_exception_label_str(self): ds = create_test_data(seed=1) - with self.assertRaisesRegexp(ValueError, '\'label\' argument has to'): + with raises_regex(ValueError, '\'label\' argument has to'): ds.diff('dim2', label='raise_me') def test_shift(self): @@ -3673,7 +3673,7 @@ def test_shift(self): expected = Dataset({'foo': ('x', [np.nan, 1, 2])}, coords, attrs) self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'dimensions'): + with raises_regex(ValueError, 'dimensions'): ds.shift(foo=123) def test_roll(self): @@ -3686,7 +3686,7 @@ def test_roll(self): expected = Dataset({'foo': ('x', [3, 1, 2])}, ex_coords, attrs) self.assertDatasetIdentical(expected, actual) - with self.assertRaisesRegexp(ValueError, 'dimensions'): + with raises_regex(ValueError, 'dimensions'): ds.roll(foo=123) def test_real_and_imag(self): @@ -3701,11 +3701,11 @@ def test_real_and_imag(self): def test_setattr_raises(self): ds = Dataset({}, coords={'scalar': 1}, attrs={'foo': 'bar'}) - with self.assertRaisesRegexp(AttributeError, 'cannot set attr'): + with raises_regex(AttributeError, 'cannot set attr'): ds.scalar = 2 - with self.assertRaisesRegexp(AttributeError, 'cannot set attr'): + with raises_regex(AttributeError, 'cannot set attr'): ds.foo = 2 - with self.assertRaisesRegexp(AttributeError, 'cannot set attr'): + with raises_regex(AttributeError, 'cannot set attr'): ds.other = 2 def test_filter_by_attrs(self): diff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py index 65e3dfa8922..121f401b1a0 100644 --- a/xarray/tests/test_duck_array_ops.py +++ b/xarray/tests/test_duck_array_ops.py @@ -8,7 +8,7 @@ first, last, count, mean, array_notnull_equiv, ) -from . import TestCase +from . import TestCase, raises_regex class TestOps(TestCase): @@ -42,7 +42,7 @@ def test_first(self): actual = first(self.x, axis=-1, skipna=False) self.assertArrayEqual(expected, actual) - with self.assertRaisesRegexp(IndexError, 'out of bounds'): + with raises_regex(IndexError, 'out of bounds'): first(self.x, 3) def test_last(self): @@ -66,7 +66,7 @@ def test_last(self): actual = last(self.x, axis=-1, skipna=False) self.assertArrayEqual(expected, actual) - with self.assertRaisesRegexp(IndexError, 'out of bounds'): + with raises_regex(IndexError, 'out of bounds'): last(self.x, 3) def test_count(self): diff --git a/xarray/tests/test_extensions.py b/xarray/tests/test_extensions.py index 2fc41512737..27a838bc1ac 100644 --- a/xarray/tests/test_extensions.py +++ b/xarray/tests/test_extensions.py @@ -8,7 +8,7 @@ import xarray as xr -from . import TestCase +from . import TestCase, raises_regex @xr.register_dataset_accessor('example_accessor') @@ -86,5 +86,5 @@ class BrokenAccessor(object): def __init__(self, xarray_obj): raise AttributeError('broken') - with self.assertRaisesRegexp(RuntimeError, 'error initializing'): + with raises_regex(RuntimeError, 'error initializing'): xr.Dataset().stupid_accessor diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 73c6bce1574..2c2c9bd614d 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -8,7 +8,7 @@ from xarray.core import formatting from xarray.core.pycompat import PY3 -from . import TestCase +from . import TestCase, raises_regex class TestFormatting(TestCase): @@ -37,7 +37,7 @@ def test_first_n_items(self): expected = array.flat[:n] self.assertItemsEqual(expected, actual) - with self.assertRaisesRegexp(ValueError, 'at least one item'): + with raises_regex(ValueError, 'at least one item'): formatting.first_n_items(array, 0) def test_last_item(self): diff --git a/xarray/tests/test_indexing.py b/xarray/tests/test_indexing.py index f8268ea2d6d..3373fb658d1 100644 --- a/xarray/tests/test_indexing.py +++ b/xarray/tests/test_indexing.py @@ -3,13 +3,15 @@ from __future__ import print_function import itertools +import pytest + import numpy as np import pandas as pd from xarray import Dataset, DataArray, Variable from xarray.core import indexing from xarray.core import nputils -from . import TestCase, ReturnItem +from . import TestCase, ReturnItem, raises_regex class TestIndexers(TestCase): @@ -29,7 +31,7 @@ def test_expanded_indexer(self): self.assertArrayEqual(x[i], x[j]) self.assertArrayEqual(self.set_to_zero(x, i), self.set_to_zero(x, j)) - with self.assertRaisesRegexp(IndexError, 'too many indices'): + with raises_regex(IndexError, 'too many indices'): indexing.expanded_indexer(I[1, 2, 3], 2) def test_asarray_tuplesafe(self): @@ -46,27 +48,27 @@ def test_asarray_tuplesafe(self): def test_convert_label_indexer(self): # TODO: add tests that aren't just for edge cases index = pd.Index([1, 2, 3]) - with self.assertRaisesRegexp(KeyError, 'not all values found'): + with raises_regex(KeyError, 'not all values found'): indexing.convert_label_indexer(index, [0]) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): indexing.convert_label_indexer(index, 0) - with self.assertRaisesRegexp(ValueError, 'does not have a MultiIndex'): + with raises_regex(ValueError, 'does not have a MultiIndex'): indexing.convert_label_indexer(index, {'one': 0}) mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2]], names=('one', 'two')) - with self.assertRaisesRegexp(KeyError, 'not all values found'): + with raises_regex(KeyError, 'not all values found'): indexing.convert_label_indexer(mindex, [0]) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): indexing.convert_label_indexer(mindex, 0) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): indexing.convert_label_indexer(index, {'three': 0}) - with self.assertRaisesRegexp(KeyError, 'index to be fully lexsorted'): + with raises_regex(KeyError, 'index to be fully lexsorted'): indexing.convert_label_indexer(mindex, (slice(None), 1, 'no_level')) def test_convert_unsorted_datetime_index_raises(self): index = pd.to_datetime(['2001', '2000', '2002']) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): # pandas will try to convert this into an array indexer. We should # raise instead, so we can be sure the result of indexing with a # slice is always a view. @@ -80,13 +82,13 @@ def test_get_dim_indexers(self): dim_indexers = indexing.get_dim_indexers(mdata, {'one': 'a', 'two': 1}) self.assertEqual(dim_indexers, {'x': {'one': 'a', 'two': 1}}) - with self.assertRaisesRegexp(ValueError, 'cannot combine'): + with raises_regex(ValueError, 'cannot combine'): indexing.get_dim_indexers(mdata, {'x': 'a', 'two': 1}) - with self.assertRaisesRegexp(ValueError, 'do not exist'): + with raises_regex(ValueError, 'do not exist'): indexing.get_dim_indexers(mdata, {'y': 'a'}) - with self.assertRaisesRegexp(ValueError, 'do not exist'): + with raises_regex(ValueError, 'do not exist'): indexing.get_dim_indexers(mdata, {'four': 1}) def test_remap_label_indexers(self): diff --git a/xarray/tests/test_merge.py b/xarray/tests/test_merge.py index c7b6868da26..532b9ee4ff0 100644 --- a/xarray/tests/test_merge.py +++ b/xarray/tests/test_merge.py @@ -4,7 +4,9 @@ import numpy as np import xarray as xr -from . import TestCase +import pytest + +from . import TestCase, raises_regex from .test_dataset import create_test_data from xarray.core import merge @@ -20,7 +22,7 @@ def test_broadcast_dimension_size(self): [xr.Variable(('x', 'y'), [[1, 2]]), xr.Variable('y', [2, 1])]) assert actual == {'x': 1, 'y': 2} - with self.assertRaises(ValueError): + with pytest.raises(ValueError): actual = merge.broadcast_dimension_size( [xr.Variable(('x', 'y'), [[1, 2]]), xr.Variable('y', [2])]) @@ -44,7 +46,7 @@ def test_merge_datasets(self): def test_merge_dataarray_unnamed(self): data = xr.DataArray([1, 2], dims='x') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'without providing an explicit name'): xr.merge([data]) @@ -60,13 +62,13 @@ def test_merge_dicts_dims(self): def test_merge_error(self): ds = xr.Dataset({'x': 0}) - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): xr.merge([ds, ds + 1]) def test_merge_alignment_error(self): ds = xr.Dataset(coords={'x': [1, 2]}) other = xr.Dataset(coords={'x': [2, 3]}) - with self.assertRaisesRegexp(ValueError, 'indexes .* not equal'): + with raises_regex(ValueError, 'indexes .* not equal'): xr.merge([ds, other], join='exact') def test_merge_no_conflicts_single_var(self): @@ -88,11 +90,11 @@ def test_merge_no_conflicts_single_var(self): compat='no_conflicts', join='inner')) - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): ds3 = xr.Dataset({'a': ('x', [99, 3]), 'x': [1, 2]}) xr.merge([ds1, ds3], compat='no_conflicts') - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): ds3 = xr.Dataset({'a': ('y', [2, 3]), 'y': [1, 2]}) xr.merge([ds1, ds3], compat='no_conflicts') @@ -150,12 +152,12 @@ def test_merge(self): actual = data.merge(data.reset_coords(drop=True)) assert data.identical(actual) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): ds1.merge(ds2.rename({'var3': 'var1'})) - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'should be coordinates or not'): data.reset_coords().merge(data) - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'should be coordinates or not'): data.merge(data.reset_coords()) @@ -182,20 +184,20 @@ def test_merge_compat(self): ds2 = xr.Dataset({'x': 1}) for compat in ['broadcast_equals', 'equals', 'identical', 'no_conflicts']: - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): ds1.merge(ds2, compat=compat) ds2 = xr.Dataset({'x': [0, 0]}) for compat in ['equals', 'identical']: - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'should be coordinates or not'): ds1.merge(ds2, compat=compat) ds2 = xr.Dataset({'x': ((), 0, {'foo': 'bar'})}) - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): ds1.merge(ds2, compat='identical') - with self.assertRaisesRegexp(ValueError, 'compat=\S+ invalid'): + with raises_regex(ValueError, 'compat=\S+ invalid'): ds1.merge(ds2, compat='foobar') def test_merge_auto_align(self): @@ -233,10 +235,10 @@ def test_merge_no_conflicts(self): assert expected2.identical(ds1.merge(ds2, compat='no_conflicts', join='inner')) - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): ds3 = xr.Dataset({'a': ('x', [99, 3]), 'x': [1, 2]}) ds1.merge(ds3, compat='no_conflicts') - with self.assertRaises(xr.MergeError): + with pytest.raises(xr.MergeError): ds3 = xr.Dataset({'a': ('y', [2, 3]), 'y': [1, 2]}) ds1.merge(ds3, compat='no_conflicts') diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index d6d48ba1e9f..3fd4b87a3f5 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -24,7 +24,7 @@ _build_discrete_cmap, _color_palette, import_seaborn) -from . import TestCase, requires_matplotlib, requires_seaborn +from . import TestCase, requires_matplotlib, requires_seaborn, raises_regex @pytest.mark.flaky @@ -153,10 +153,10 @@ def test_convenient_facetgrid(self): for ax in g.axes.flat: self.assertTrue(ax.has_data()) - with self.assertRaisesRegexp(ValueError, '[Ff]acet'): + with raises_regex(ValueError, '[Ff]acet'): d.plot(x='x', y='y', col='z', ax=plt.gca()) - with self.assertRaisesRegexp(ValueError, '[Ff]acet'): + with raises_regex(ValueError, '[Ff]acet'): d[0].plot(x='x', y='y', col='z', ax=plt.gca()) @pytest.mark.slow @@ -188,16 +188,16 @@ def test_plot_size(self): self.darray.plot(size=5, aspect=2) assert tuple(plt.gcf().get_size_inches()) == (10, 5) - with self.assertRaisesRegexp(ValueError, 'cannot provide both'): + with raises_regex(ValueError, 'cannot provide both'): self.darray.plot(ax=plt.gca(), figsize=(3, 4)) - with self.assertRaisesRegexp(ValueError, 'cannot provide both'): + with raises_regex(ValueError, 'cannot provide both'): self.darray.plot(size=5, figsize=(3, 4)) - with self.assertRaisesRegexp(ValueError, 'cannot provide both'): + with raises_regex(ValueError, 'cannot provide both'): self.darray.plot(size=5, ax=plt.gca()) - with self.assertRaisesRegexp(ValueError, 'cannot provide `aspect`'): + with raises_regex(ValueError, 'cannot provide `aspect`'): self.darray.plot(aspect=1) @pytest.mark.slow @@ -210,7 +210,7 @@ def test_convenient_facetgrid_4d(self): for ax in g.axes.flat: self.assertTrue(ax.has_data()) - with self.assertRaisesRegexp(ValueError, '[Ff]acet'): + with raises_regex(ValueError, '[Ff]acet'): d.plot(x='x', y='y', col='columns', ax=plt.gca()) @@ -236,7 +236,7 @@ def test_ylabel_is_data_name(self): def test_wrong_dims_raises_valueerror(self): twodims = DataArray(easy_array((2, 5))) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): twodims.plot.line() def test_format_string(self): @@ -248,7 +248,7 @@ def test_can_pass_in_axis(self): def test_nonnumeric_index_raises_typeerror(self): a = DataArray([1, 2, 3], {'letter': ['a', 'b', 'c']}, dims='letter') - with self.assertRaisesRegexp(TypeError, r'[Pp]lot'): + with raises_regex(TypeError, r'[Pp]lot'): a.plot.line() def test_primitive_returned(self): @@ -575,18 +575,18 @@ def test_label_names(self): self.assertEqual('y', plt.gca().get_ylabel()) def test_1d_raises_valueerror(self): - with self.assertRaisesRegexp(ValueError, r'DataArray must be 2d'): + with raises_regex(ValueError, r'DataArray must be 2d'): self.plotfunc(self.darray[0, :]) def test_3d_raises_valueerror(self): a = DataArray(easy_array((2, 3, 4))) - with self.assertRaisesRegexp(ValueError, r'DataArray must be 2d'): + with raises_regex(ValueError, r'DataArray must be 2d'): self.plotfunc(a) def test_nonnumeric_index_raises_typeerror(self): a = DataArray(easy_array((3, 2)), coords=[['a', 'b', 'c'], ['d', 'e']]) - with self.assertRaisesRegexp(TypeError, r'[Pp]lot'): + with raises_regex(TypeError, r'[Pp]lot'): self.plotfunc(a) def test_can_pass_in_axis(self): @@ -659,13 +659,13 @@ def test_positional_coord_string(self): self.assertEqual('y', ax.get_ylabel()) def test_bad_x_string_exception(self): - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'x and y must be coordinate variables'): self.plotmethod('not_a_real_dim', 'y') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'x must be a dimension name if y is not supplied'): self.plotmethod(x='not_a_real_dim') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'y must be a dimension name if x is not supplied'): self.plotmethod(y='not_a_real_dim') self.darray.coords['z'] = 100 @@ -755,7 +755,7 @@ def test_colorbar_kwargs(self): self.plotmethod(add_colorbar=False) self.assertNotIn('testvar', text_in_fig()) # check that error is raised - self.assertRaises(ValueError, self.plotmethod, + pytest.raises(ValueError, self.plotmethod, add_colorbar=False, cbar_kwargs= {'label':'label'}) def test_verbose_facetgrid(self): @@ -908,11 +908,11 @@ def _color_as_tuple(c): (0.0, 0.0, 1.0)) def test_cmap_and_color_both(self): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.plotmethod(colors='k', cmap='RdBu') def list_of_colors_in_cmap_deprecated(self): - with self.assertRaises(Exception): + with pytest.raises(Exception): self.plotmethod(cmap=['k', 'b']) @pytest.mark.slow @@ -984,7 +984,7 @@ def test_default_aspect_is_auto(self): @pytest.mark.slow def test_cannot_change_mpl_aspect(self): - with self.assertRaisesRegexp(ValueError, 'not available in xarray'): + with raises_regex(ValueError, 'not available in xarray'): self.darray.plot.imshow(aspect='equal') # with numbers we fall back to fig control @@ -1000,11 +1000,11 @@ def test_primitive_artist_returned(self): @pytest.mark.slow @requires_seaborn def test_seaborn_palette_needs_levels(self): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): self.plotmethod(cmap='husl') def test_2d_coord_names(self): - with self.assertRaisesRegexp(ValueError, 'requires 1D coordinates'): + with raises_regex(ValueError, 'requires 1D coordinates'): self.plotmethod(x='x2d', y='y2d') @@ -1076,7 +1076,7 @@ def test_empty_cell(self): @pytest.mark.slow def test_norow_nocol_error(self): - with self.assertRaisesRegexp(ValueError, r'[Rr]ow'): + with raises_regex(ValueError, r'[Rr]ow'): xplt.FacetGrid(self.darray) @pytest.mark.slow @@ -1097,7 +1097,7 @@ def test_float_index(self): @pytest.mark.slow def test_nonunique_index_error(self): self.darray.coords['z'] = [0.1, 0.2, 0.2] - with self.assertRaisesRegexp(ValueError, r'[Uu]nique'): + with raises_regex(ValueError, r'[Uu]nique'): xplt.FacetGrid(self.darray, col='z') @pytest.mark.slow @@ -1156,10 +1156,10 @@ def test_figure_size(self): g = xplt.FacetGrid(self.darray, col='z', figsize=(9, 4)) self.assertArrayEqual(g.fig.get_size_inches(), (9, 4)) - with self.assertRaisesRegexp(ValueError, "cannot provide both"): + with raises_regex(ValueError, "cannot provide both"): g = xplt.plot(self.darray, row=2, col='z', figsize=(6, 4), size=6) - with self.assertRaisesRegexp(ValueError, "Can't use"): + with raises_regex(ValueError, "Can't use"): g = xplt.plot(self.darray, row=2, col='z', ax=plt.gca(), size=6) @pytest.mark.slow diff --git a/xarray/tests/test_ufuncs.py b/xarray/tests/test_ufuncs.py index 37a4a1959fd..af7d6e105cc 100644 --- a/xarray/tests/test_ufuncs.py +++ b/xarray/tests/test_ufuncs.py @@ -8,7 +8,7 @@ import xarray.ufuncs as xu import xarray as xr -from . import TestCase +from . import TestCase, raises_regex class TestOps(TestCase): @@ -59,7 +59,7 @@ def test_groupby(self): self.assertIdentical(ds.a, xu.maximum(arr_grouped, group_mean.a)) self.assertIdentical(ds.a, xu.maximum(group_mean.a, arr_grouped)) - with self.assertRaisesRegexp(TypeError, 'only support binary ops'): + with raises_regex(TypeError, 'only support binary ops'): xu.maximum(ds.a.variable, ds_grouped) def test_pickle(self): diff --git a/xarray/tests/test_utils.py b/xarray/tests/test_utils.py index 1b1208d0da7..8c987c58c50 100644 --- a/xarray/tests/test_utils.py +++ b/xarray/tests/test_utils.py @@ -81,7 +81,7 @@ def test_safe(self): utils.update_safety_check(self.x, self.y) def test_unsafe(self): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): utils.update_safety_check(self.x, self.z) def test_ordered_dict_intersection(self): @@ -116,11 +116,11 @@ def test_dict_equiv(self): def test_frozen(self): x = utils.Frozen(self.x) - with self.assertRaises(TypeError): + with pytest.raises(TypeError): x['foo'] = 'bar' - with self.assertRaises(TypeError): + with pytest.raises(TypeError): del x['a'] - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): x.update(self.y) self.assertEqual(x.mapping, self.x) self.assertIn(repr(x), ("Frozen({'a': 'A', 'b': 'B'})", diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index c93b4d98367..0d59ec632d1 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -19,7 +19,7 @@ from xarray.core.pycompat import PY3, OrderedDict from xarray.core.common import full_like, zeros_like, ones_like -from . import TestCase, source_ndarray, requires_dask +from . import TestCase, source_ndarray, requires_dask, raises_regex class VariableSubclassTestCases(object): @@ -93,7 +93,7 @@ def test_getitem_1d_fancy(self): v_new = v[[True, False, True]] self.assertVariableIdentical(v[[0, 2]], v_new) - with self.assertRaisesRegexp(IndexError, "Boolean indexer should"): + with raises_regex(IndexError, "Boolean indexer should"): ind = Variable(('a', ), [True, False, True]) v[ind] @@ -389,7 +389,7 @@ def test_concat(self): Variable.concat((v, w), 'b')) self.assertVariableIdentical(Variable(['b', 'a'], np.array([x, y])), Variable.concat((v, w), 'b')) - with self.assertRaisesRegexp(ValueError, 'inconsistent dimensions'): + with raises_regex(ValueError, 'inconsistent dimensions'): Variable.concat([v, Variable(['c'], y)], 'b') # test indexers actual = Variable.concat( @@ -405,7 +405,7 @@ def test_concat(self): self.assertVariableIdentical(v, Variable.concat([v[:1], v[1:]], 'time')) # test dimension order self.assertVariableIdentical(v, Variable.concat([v[:, :5], v[:, 5:]], 'x')) - with self.assertRaisesRegexp(ValueError, 'all input arrays must have'): + with raises_regex(ValueError, 'all input arrays must have'): Variable.concat([v[:, 0], v[:, 1:]], 'x') def test_concat_attrs(self): @@ -547,12 +547,12 @@ def test_getitem_advanced(self): # with boolean variable with wrong shape ind = np.array([True, False]) - with self.assertRaisesRegexp(IndexError, 'Boolean array size 2 is '): + with raises_regex(IndexError, 'Boolean array size 2 is '): v[Variable(('a', 'b'), [[0, 1]]), ind] # boolean indexing with different dimension ind = Variable(['a'], [True, False, False]) - with self.assertRaisesRegexp(IndexError, 'Boolean indexer should be'): + with raises_regex(IndexError, 'Boolean indexer should be'): v[dict(y=ind)] def test_getitem_uint_1d(self): @@ -673,21 +673,21 @@ def test_getitem_fancy(self): def test_getitem_error(self): v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]]) - with self.assertRaisesRegexp(IndexError, "labeled multi-"): + with raises_regex(IndexError, "labeled multi-"): v[[[0, 1], [1, 2]]] ind_x = Variable(['a'], [0, 1, 1]) ind_y = Variable(['a'], [0, 1]) - with self.assertRaisesRegexp(IndexError, "Dimensions of indexers "): + with raises_regex(IndexError, "Dimensions of indexers "): v[ind_x, ind_y] ind = Variable(['a', 'b'], [[True, False], [False, True]]) - with self.assertRaisesRegexp(IndexError, '2-dimensional boolean'): + with raises_regex(IndexError, '2-dimensional boolean'): v[dict(x=ind)] v = Variable(['x', 'y', 'z'], np.arange(60).reshape(3, 4, 5)) ind = Variable(['x'], [0, 1]) - with self.assertRaisesRegexp(IndexError, 'Dimensions of indexers mis'): + with raises_regex(IndexError, 'Dimensions of indexers mis'): v[:, ind] @@ -702,7 +702,7 @@ def test_data_and_values(self): self.assertArrayEqual(v.data, self.d) self.assertArrayEqual(v.values, self.d) self.assertIs(source_ndarray(v.values), self.d) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): # wrong size v.values = np.random.random(5) d2 = np.random.random((10, 3)) @@ -861,9 +861,9 @@ def test_as_variable(self): expected_extra.attrs, expected_extra.encoding) self.assertVariableIdentical(expected_extra, as_variable(xarray_tuple)) - with self.assertRaisesRegexp(TypeError, 'tuples to convert'): + with raises_regex(TypeError, 'tuples to convert'): as_variable(tuple(data)) - with self.assertRaisesRegexp( + with raises_regex( TypeError, 'without an explicit list of dimensions'): as_variable(data) @@ -876,10 +876,10 @@ def test_as_variable(self): data = np.arange(9).reshape((3, 3)) expected = Variable(('x', 'y'), data) - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'without explicit dimension names'): as_variable(data, name='x') - with self.assertRaisesRegexp( + with raises_regex( ValueError, 'has more than 1-dimension'): as_variable(expected, name='x') @@ -961,7 +961,7 @@ def test_items(self): # test iteration for n, item in enumerate(v): self.assertVariableIdentical(Variable(['y'], data[n]), item) - with self.assertRaisesRegexp(TypeError, 'iteration over a 0-d'): + with raises_regex(TypeError, 'iteration over a 0-d'): iter(Variable([], 0)) # test setting v.values[:] = 0 @@ -1000,7 +1000,7 @@ def test_isel(self): self.assertVariableIdentical(v.isel(time=0), v[0]) self.assertVariableIdentical(v.isel(time=slice(0, 3)), v[:3]) self.assertVariableIdentical(v.isel(x=0), v[:, 0]) - with self.assertRaisesRegexp(ValueError, 'do not exist'): + with raises_regex(ValueError, 'do not exist'): v.isel(not_a_dim=0) def test_index_0d_numpy_string(self): @@ -1036,7 +1036,7 @@ def test_shift(self): self.assertVariableIdentical(expected, v.shift(x=5)) self.assertVariableIdentical(expected, v.shift(x=6)) - with self.assertRaisesRegexp(ValueError, 'dimension'): + with raises_regex(ValueError, 'dimension'): v.shift(z=0) v = Variable('x', [1, 2, 3, 4, 5], {'foo': 'bar'}) @@ -1065,7 +1065,7 @@ def test_roll(self): self.assertVariableIdentical(expected, v.roll(x=2)) self.assertVariableIdentical(expected, v.roll(x=-3)) - with self.assertRaisesRegexp(ValueError, 'dimension'): + with raises_regex(ValueError, 'dimension'): v.roll(z=0) def test_roll_consistency(self): @@ -1115,7 +1115,7 @@ def test_squeeze(self): v = Variable(['x', 'y'], [[1, 2]]) self.assertVariableIdentical(Variable(['y'], [1, 2]), v.squeeze()) self.assertVariableIdentical(Variable(['y'], [1, 2]), v.squeeze('x')) - with self.assertRaisesRegexp(ValueError, 'cannot select a dimension'): + with raises_regex(ValueError, 'cannot select a dimension'): v.squeeze('y') def test_get_axis_num(self): @@ -1124,7 +1124,7 @@ def test_get_axis_num(self): self.assertEqual(v.get_axis_num(['x']), (0,)) self.assertEqual(v.get_axis_num(['x', 'y']), (0, 1)) self.assertEqual(v.get_axis_num(['z', 'y', 'x']), (2, 1, 0)) - with self.assertRaisesRegexp(ValueError, 'not found in array dim'): + with raises_regex(ValueError, 'not found in array dim'): v.get_axis_num('foobar') def test_set_dims(self): @@ -1145,7 +1145,7 @@ def test_set_dims(self): expected = v self.assertVariableIdentical(actual, expected) - with self.assertRaisesRegexp(ValueError, 'must be a superset'): + with raises_regex(ValueError, 'must be a superset'): v.set_dims(['z']) def test_set_dims_object_dtype(self): @@ -1177,9 +1177,9 @@ def test_stack(self): def test_stack_errors(self): v = Variable(['x', 'y'], [[0, 1], [2, 3]], {'foo': 'bar'}) - with self.assertRaisesRegexp(ValueError, 'invalid existing dim'): + with raises_regex(ValueError, 'invalid existing dim'): v.stack(z=('x1',)) - with self.assertRaisesRegexp(ValueError, 'cannot create a new dim'): + with raises_regex(ValueError, 'cannot create a new dim'): v.stack(x=('x',)) def test_unstack(self): @@ -1198,11 +1198,11 @@ def test_unstack(self): def test_unstack_errors(self): v = Variable('z', [0, 1, 2, 3]) - with self.assertRaisesRegexp(ValueError, 'invalid existing dim'): + with raises_regex(ValueError, 'invalid existing dim'): v.unstack(foo={'x': 4}) - with self.assertRaisesRegexp(ValueError, 'cannot create a new dim'): + with raises_regex(ValueError, 'cannot create a new dim'): v.stack(z=('z',)) - with self.assertRaisesRegexp(ValueError, 'the product of the new dim'): + with raises_regex(ValueError, 'the product of the new dim'): v.unstack(z={'x': 5}) def test_unstack_2d(self): @@ -1254,9 +1254,9 @@ def test_broadcasting_failures(self): a = Variable(['x'], np.arange(10)) b = Variable(['x'], np.arange(5)) c = Variable(['x', 'x'], np.arange(100).reshape(10, 10)) - with self.assertRaisesRegexp(ValueError, 'mismatched lengths'): + with raises_regex(ValueError, 'mismatched lengths'): a + b - with self.assertRaisesRegexp(ValueError, 'duplicate dimensions'): + with raises_regex(ValueError, 'duplicate dimensions'): a + c def test_inplace_math(self): @@ -1269,7 +1269,7 @@ def test_inplace_math(self): self.assertIs(source_ndarray(v.values), x) self.assertArrayEqual(v.values, np.arange(5) + 1) - with self.assertRaisesRegexp(ValueError, 'dimensions cannot change'): + with raises_regex(ValueError, 'dimensions cannot change'): v += Variable('y', np.arange(5)) def test_reduce(self): @@ -1287,7 +1287,7 @@ def test_reduce(self): Variable([], self.d.mean(axis=0).std())) self.assertVariableAllClose(v.mean('x'), v.reduce(np.mean, 'x')) - with self.assertRaisesRegexp(ValueError, 'cannot supply both'): + with raises_regex(ValueError, 'cannot supply both'): v.mean(dim='x', axis=0) @pytest.mark.skipif(LooseVersion(np.__version__) < LooseVersion('1.10.0'), @@ -1308,7 +1308,7 @@ def test_quantile_dask_raises(self): # regression for GH1524 v = Variable(['x', 'y'], self.d).chunk(2) - with self.assertRaisesRegexp(TypeError, 'arrays stored as dask'): + with raises_regex(TypeError, 'arrays stored as dask'): v.quantile(0.5, dim='x') def test_big_endian_reduce(self): @@ -1333,7 +1333,7 @@ def test_reduce_funcs(self): self.assertVariableIdentical(v.var(), Variable([], 2.0 / 3)) if LooseVersion(np.__version__) < '1.9': - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): v.median() else: self.assertVariableIdentical(v.median(), Variable([], 2)) @@ -1343,7 +1343,7 @@ def test_reduce_funcs(self): self.assertVariableIdentical(v.all(dim='x'), Variable([], False)) v = Variable('t', pd.date_range('2000-01-01', periods=3)) - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): v.max(skipna=True) self.assertVariableIdentical( v.max(), Variable([], pd.Timestamp('2000-01-03'))) @@ -1405,7 +1405,7 @@ def test_setitem(self): expected = Variable(['x', 'y'], [[0, 0], [0, 0], [1, 1]]) self.assertVariableIdentical(expected, v) - with self.assertRaisesRegexp(ValueError, "shape mismatch"): + with raises_regex(ValueError, "shape mismatch"): v[ind, ind] = np.zeros((1, 2, 1)) v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]]) @@ -1466,7 +1466,7 @@ class TestIndexVariable(TestCase, VariableSubclassTestCases): cls = staticmethod(IndexVariable) def test_init(self): - with self.assertRaisesRegexp(ValueError, 'must be 1-dimensional'): + with raises_regex(ValueError, 'must be 1-dimensional'): IndexVariable((), 0) def test_to_index(self): @@ -1486,14 +1486,14 @@ def test_data(self): self.assertEqual(float, x.dtype) self.assertArrayEqual(np.arange(3), x) self.assertEqual(float, x.values.dtype) - with self.assertRaisesRegexp(TypeError, 'cannot be modified'): + with raises_regex(TypeError, 'cannot be modified'): x[:] = 0 def test_name(self): coord = IndexVariable('x', [10.0]) self.assertEqual(coord.name, 'x') - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): coord.name = 'y' def test_level_names(self): @@ -1511,7 +1511,7 @@ def test_get_level_variable(self): level_1 = IndexVariable('x', midx.get_level_values('level_1')) self.assertVariableIdentical(x.get_level_variable('level_1'), level_1) - with self.assertRaisesRegexp(ValueError, 'has no MultiIndex'): + with raises_regex(ValueError, 'has no MultiIndex'): IndexVariable('y', [10.0]).get_level_variable('level') def test_concat_periods(self): @@ -1628,7 +1628,7 @@ def test_full_like(self): # override dtype expect.values = [[True, True], [True, True]] - self.assertEquals(expect.dtype, bool) + assert expect.dtype == bool self.assertVariableIdentical(expect, full_like(orig, True, dtype=bool)) @requires_dask From df2d3efe63b1634714dbbf1a4ca4271311e87dab Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Tue, 24 Oct 2017 22:57:09 -0700 Subject: [PATCH 2/8] more warnings fixes --- xarray/core/pycompat.py | 3 ++- xarray/plot/facetgrid.py | 4 ++-- xarray/tests/test_dataset.py | 8 ++++---- xarray/tests/test_groupby.py | 4 ++-- xarray/tests/test_plot.py | 2 +- xarray/tests/test_variable.py | 16 ++++++++-------- 6 files changed, 19 insertions(+), 18 deletions(-) diff --git a/xarray/core/pycompat.py b/xarray/core/pycompat.py index 7eaa0ccc450..305fe38b159 100644 --- a/xarray/core/pycompat.py +++ b/xarray/core/pycompat.py @@ -25,6 +25,7 @@ def itervalues(d): from functools import reduce import builtins from urllib.request import urlretrieve + from inspect import getfullargspec as getargspec else: # pragma: no cover # Python 2 basestring = basestring # noqa @@ -43,7 +44,7 @@ def itervalues(d): reduce = reduce import __builtin__ as builtins from urllib import urlretrieve - + from inspect import getargspec try: from cyordereddict import OrderedDict except ImportError: # pragma: no cover diff --git a/xarray/plot/facetgrid.py b/xarray/plot/facetgrid.py index b2253b926b8..bfe3454d8ce 100644 --- a/xarray/plot/facetgrid.py +++ b/xarray/plot/facetgrid.py @@ -2,13 +2,13 @@ from __future__ import division from __future__ import print_function -import inspect import warnings import itertools import functools import numpy as np +from ..core.pycompat import getargspec from ..core.formatting import format_item from .utils import _determine_cmap_params, _infer_xy_labels @@ -227,7 +227,7 @@ def map_dataarray(self, func, x, y, **kwargs): 'filled': func.__name__ != 'contour', } - cmap_args = inspect.getargspec(_determine_cmap_params).args + cmap_args = getargspec(_determine_cmap_params).args cmap_kwargs.update((a, kwargs[a]) for a in cmap_args if a in kwargs) cmap_params = _determine_cmap_params(**cmap_kwargs) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 87be07f50b0..a9466324249 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -272,7 +272,7 @@ class Arbitrary(object): d = pd.Timestamp('2000-01-01T12') args = [True, None, 3.4, np.nan, 'hello', u'uni', b'raw', - np.datetime64('2000-01-01T00'), d, d.to_datetime(), + np.datetime64('2000-01-01'), d, d.to_pydatetime(), Arbitrary()] for arg in args: print(arg) @@ -684,7 +684,7 @@ def test_coords_merge_mismatched_shape(self): self.assertDatasetIdentical(expected, actual) actual = other_coords.merge(orig_coords) - self.assertDatasetIdentical(expected.T, actual) + self.assertDatasetIdentical(expected.transpose(), actual) orig_coords = Dataset(coords={'a': ('x', [np.nan])}).coords other_coords = Dataset(coords={'a': np.nan}).coords @@ -3279,7 +3279,7 @@ def test_reduce_non_numeric(self): add_vars = {'var4': ['dim1', 'dim2']} for v, dims in sorted(add_vars.items()): size = tuple(data1.dims[d] for d in dims) - data = np.random.random_integers(0, 100, size=size).astype(np.str_) + data = np.random.randint(0, 100, size=size).astype(np.str_) data1[v] = (dims, data, {'foo': 'variable'}) self.assertTrue('var4' not in data1.mean()) @@ -3562,7 +3562,7 @@ def test_dataset_math_errors(self): # verify we can rollback in-place operations if something goes wrong # nb. inplace datetime64 math actually will work with an integer array # but not floats thanks to numpy's inconsistent handling - other = DataArray(np.datetime64('2000-01-01T12'), coords={'c': 2}) + other = DataArray(np.datetime64('2000-01-01'), coords={'c': 2}) actual = ds.copy(deep=True) with pytest.raises(TypeError): actual += other diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 9a153e45da0..7245685e2c7 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -53,7 +53,7 @@ def test_groupby_da_datetime(): times = pd.date_range('2000-01-01', periods=4) foo = xr.DataArray([1,2,3,4], coords=dict(time=times), dims='time') # create test index - dd = times.to_datetime() + dd = times.to_pydatetime() reference_dates = [dd[0], dd[2]] labels = reference_dates[0:1]*2 + reference_dates[1:2]*2 ind = xr.DataArray(labels, coords=dict(time=times), dims='time', name='reference_date') @@ -70,5 +70,5 @@ def test_groupby_duplicate_coordinate_labels(): actual = array.groupby('x').sum() assert expected.equals(actual) - + # TODO: move other groupby tests from test_dataset and test_dataarray over here diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index 3fd4b87a3f5..e2473d6389e 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -165,7 +165,7 @@ def test_subplot_kws(self): d = DataArray(a, dims=['y', 'x', 'z']) d.coords['z'] = list('abcd') g = d.plot(x='x', y='y', col='z', col_wrap=2, cmap='cool', - subplot_kws=dict(axisbg='r')) + subplot_kws=dict(facecolor='r')) for ax in g.axes.flat: try: # mpl V2 diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index 0d59ec632d1..6b621e1b95d 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -206,7 +206,7 @@ def test_index_and_concat_datetime(self): def test_0d_time_data(self): # regression test for #105 x = self.cls('time', pd.date_range('2000-01-01', periods=5)) - expected = np.datetime64('2000-01-01T00Z', 'ns') + expected = np.datetime64('2000-01-01', 'ns') self.assertEqual(x[0].values, expected) def test_datetime64_conversion(self): @@ -721,9 +721,9 @@ def test_numpy_same_methods(self): self.assertEqual(2, v.searchsorted(2)) def test_datetime64_conversion_scalar(self): - expected = np.datetime64('2000-01-01T00:00:00Z', 'ns') + expected = np.datetime64('2000-01-01', 'ns') for values in [ - np.datetime64('2000-01-01T00Z'), + np.datetime64('2000-01-01'), pd.Timestamp('2000-01-01T00'), datetime(2000, 1, 1), ]: @@ -756,7 +756,7 @@ def test_0d_str(self): def test_0d_datetime(self): v = Variable([], pd.Timestamp('2000-01-01')) self.assertEqual(v.dtype, np.dtype('datetime64[ns]')) - self.assertEqual(v.values, np.datetime64('2000-01-01T00Z', 'ns')) + self.assertEqual(v.values, np.datetime64('2000-01-01', 'ns')) def test_0d_timedelta(self): for td in [pd.to_timedelta('1s'), np.timedelta64(1, 's')]: @@ -1592,26 +1592,26 @@ def test_masked_array(self): self.assertEqual(np.dtype(float), actual.dtype) def test_datetime(self): - expected = np.datetime64('2000-01-01T00Z') + expected = np.datetime64('2000-01-01') actual = as_compatible_data(expected) self.assertEqual(expected, actual) self.assertEqual(np.ndarray, type(actual)) self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) - expected = np.array([np.datetime64('2000-01-01T00Z')]) + expected = np.array([np.datetime64('2000-01-01')]) actual = as_compatible_data(expected) self.assertEqual(np.asarray(expected), actual) self.assertEqual(np.ndarray, type(actual)) self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) - expected = np.array([np.datetime64('2000-01-01T00Z', 'ns')]) + expected = np.array([np.datetime64('2000-01-01', 'ns')]) actual = as_compatible_data(expected) self.assertEqual(np.asarray(expected), actual) self.assertEqual(np.ndarray, type(actual)) self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) self.assertIs(expected, source_ndarray(np.asarray(actual))) - expected = np.datetime64('2000-01-01T00Z', 'ns') + expected = np.datetime64('2000-01-01', 'ns') actual = as_compatible_data(datetime(2000, 1, 1)) self.assertEqual(np.asarray(expected), actual) self.assertEqual(np.ndarray, type(actual)) From 8d775bb5b3bd20a0f90872218567ffd2f9177bbc Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Wed, 25 Oct 2017 09:25:54 -0700 Subject: [PATCH 3/8] fix some numpy warnings using numpy.seterr --- xarray/core/dataarray.py | 14 +++++++++----- xarray/core/variable.py | 13 ++++++++----- xarray/tests/test_dataarray.py | 6 ++++++ xarray/tests/test_dataset.py | 6 ++++++ xarray/tests/test_variable.py | 6 ++++++ 5 files changed, 35 insertions(+), 10 deletions(-) diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index ce0a6c113ce..8c381617c16 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -1571,7 +1571,9 @@ def __array_wrap__(self, obj, context=None): def _unary_op(f): @functools.wraps(f) def func(self, *args, **kwargs): - return self.__array_wrap__(f(self.variable.data, *args, **kwargs)) + with np.errstate(all='ignore'): + return self.__array_wrap__(f(self.variable.data, *args, + **kwargs)) return func @@ -1588,9 +1590,10 @@ def func(self, other): other_variable = getattr(other, 'variable', other) other_coords = getattr(other, 'coords', None) - variable = (f(self.variable, other_variable) - if not reflexive - else f(other_variable, self.variable)) + with np.errstate(all='ignore'): + variable = (f(self.variable, other_variable) + if not reflexive + else f(other_variable, self.variable)) coords = self.coords._merge_raw(other_coords) name = self._result_name(other) @@ -1612,7 +1615,8 @@ def func(self, other): other_coords = getattr(other, 'coords', None) other_variable = getattr(other, 'variable', other) with self.coords._merge_inplace(other_coords): - f(self.variable, other_variable) + with np.errstate(all='ignore'): + f(self.variable, other_variable) return self return func diff --git a/xarray/core/variable.py b/xarray/core/variable.py index a3b5a4d0a88..57bb21e4dc3 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -1354,7 +1354,8 @@ def __array_wrap__(self, obj, context=None): def _unary_op(f): @functools.wraps(f) def func(self, *args, **kwargs): - return self.__array_wrap__(f(self.data, *args, **kwargs)) + with np.errstate(all='ignore'): + return self.__array_wrap__(f(self.data, *args, **kwargs)) return func @staticmethod @@ -1364,9 +1365,10 @@ def func(self, other): if isinstance(other, (xr.DataArray, xr.Dataset)): return NotImplemented self_data, other_data, dims = _broadcast_compat_data(self, other) - new_data = (f(self_data, other_data) - if not reflexive - else f(other_data, self_data)) + with np.errstate(all='ignore'): + new_data = (f(self_data, other_data) + if not reflexive + else f(other_data, self_data)) result = Variable(dims, new_data) return result return func @@ -1381,7 +1383,8 @@ def func(self, other): if dims != self.dims: raise ValueError('dimensions cannot change for in-place ' 'operations') - self.values = f(self_data, other_data) + with np.errstate(all='ignore'): + self.values = f(self_data, other_data) return self return func diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 562459db7e6..68bbd7678d0 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -3120,3 +3120,9 @@ def test_rolling_count_correct(): expected = DataArray( [np.nan, np.nan, 2, 3, 3, 4, 5, 5, 5, 5, 5], dims='time') assert_equal(result, expected) + + +def test_raise_no_warning_for_nan_in_binary_ops(): + with pytest.warns(None) as record: + xr.DataArray([1, 2, np.NaN]) > 0 + assert len(record) == 0 diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index a9466324249..a1a0fd629f2 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -4106,3 +4106,9 @@ def test_rolling_reduce(ds, center, min_periods, window, name): # Make sure the dimension order is restored for key, src_var in ds.data_vars.items(): assert src_var.dims == actual[key].dims + + +def test_raise_no_warning_for_nan_in_binary_ops(): + with pytest.warns(None) as record: + Dataset(data_vars={'x': ('y', [1, 2, np.NaN])}) > 0 + assert len(record) == 0 diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index 6b621e1b95d..35c64040a90 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -1675,3 +1675,9 @@ def test_ones_like(self): full_like(orig, 1)) self.assertVariableIdentical(ones_like(orig, dtype=int), full_like(orig, 1, dtype=int)) + + +def test_raise_no_warning_for_nan_in_binary_ops(): + with pytest.warns(None) as record: + Variable('x', [1, 2, np.NaN]) > 0 + assert len(record) == 0 From ed838f68a9efd2ab5a47f796d54f5890a1ab45f8 Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Fri, 27 Oct 2017 12:48:54 -0700 Subject: [PATCH 4/8] remove pytest command line argument that raises errors when warnings are issued --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 19c6dbc8646..496875fcd86 100644 --- a/.travis.yml +++ b/.travis.yml @@ -83,8 +83,7 @@ install: - python setup.py install script: - # temporary mod while cleaning up warnings - - py.test -W error xarray --cov=xarray --cov-config ci/.coveragerc --cov-report term-missing --verbose $EXTRA_FLAGS + - py.test xarray --cov=xarray --cov-config ci/.coveragerc --cov-report term-missing --verbose $EXTRA_FLAGS after_success: - coveralls From 0a79e83821445ae250ee0ff5cff260c25bda2668 Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Fri, 27 Oct 2017 16:35:42 -0700 Subject: [PATCH 5/8] remove extra np.errstate(all=ignore) context managers --- xarray/core/dataarray.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 8c381617c16..c5cb6355fa0 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -1590,10 +1590,9 @@ def func(self, other): other_variable = getattr(other, 'variable', other) other_coords = getattr(other, 'coords', None) - with np.errstate(all='ignore'): - variable = (f(self.variable, other_variable) - if not reflexive - else f(other_variable, self.variable)) + variable = (f(self.variable, other_variable) + if not reflexive + else f(other_variable, self.variable)) coords = self.coords._merge_raw(other_coords) name = self._result_name(other) @@ -1615,8 +1614,7 @@ def func(self, other): other_coords = getattr(other, 'coords', None) other_variable = getattr(other, 'variable', other) with self.coords._merge_inplace(other_coords): - with np.errstate(all='ignore'): - f(self.variable, other_variable) + f(self.variable, other_variable) return self return func From d70258a77fa3e0207c8ce643e9b2121fe286410e Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Fri, 27 Oct 2017 18:32:26 -0700 Subject: [PATCH 6/8] add whats new note --- doc/whats-new.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 241e5b7e49f..b92e6c9f291 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -85,6 +85,11 @@ Breaking changes disk when calling ``repr`` (:issue:`1522`). By `Guido Imperiale `_. +- Suppress ``RuntimeWarning`` issued by ``numpy`` for "invalid value comparisons" + (e.g. NaNs). Xarray now behaves similarly to Pandas in its treatment of + binary and unary operations on objects with ``NaN``s (:issue:`1657`). + By `Joe Hamman `_. + - Several existing features have been deprecated and will change to new behavior in xarray v0.11. If you use any of them with xarray v0.10, you should see a ``FutureWarning`` that describes how to update your code: From bd682224a57cb383993c7653957cc5c1276dde9f Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Sat, 28 Oct 2017 22:56:19 -0700 Subject: [PATCH 7/8] allow cleanup failures on scipy/netcdf4 test --- xarray/tests/test_backends.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index 263bba9de81..b5a929c259e 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -1039,7 +1039,7 @@ def test_netcdf3_endianness(self): @requires_netCDF4 def test_nc4_scipy(self): - with create_tmp_file() as tmp_file: + with create_tmp_file(allow_cleanup_failure=True) as tmp_file: with nc4.Dataset(tmp_file, 'w', format='NETCDF4') as rootgrp: rootgrp.createGroup('foo') From 53b1e4a56ce8ea13d5d5b3ea3f8c432c0206b3de Mon Sep 17 00:00:00 2001 From: Joe Hamman Date: Sat, 28 Oct 2017 23:31:55 -0700 Subject: [PATCH 8/8] fix bad merge resolution --- xarray/tests/test_backends.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index b5a929c259e..eb3176eda13 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -1023,13 +1023,9 @@ def test_array_attrs(self): pass def test_roundtrip_example_1_netcdf_gz(self): - if sys.version_info[:2] < (2, 7): - with raises_regex(ValueError, 'gzipped netCDF not supported'): - open_example_dataset('example_1.nc.gz') - else: - with open_example_dataset('example_1.nc.gz') as expected: - with open_example_dataset('example_1.nc') as actual: - self.assertDatasetIdentical(expected, actual) + with open_example_dataset('example_1.nc.gz') as expected: + with open_example_dataset('example_1.nc') as actual: + self.assertDatasetIdentical(expected, actual) def test_netcdf3_endianness(self): # regression test for GH416