Skip to content

Commit f3deb2f

Browse files
authored
pytest-ification (#1828)
* deprecation notes in testing functions * gitignore additions * self_assert from unittest2pytest * pytest.warns needs a warning * assert_equal * future warnings * assert identical * pytest warning fix * revert assert_equal, as assert_array_equal needs to be separate * assert dataset & dataarray equal * imports * assertItemsEqual (but may need coercion to sets) * Revert "assertItemsEqual (but may need coercion to sets)" This reverts commit fa8f89a. * add back in assertitemsequal * self.assert_equal -> assert_equal * pytest.warns message matching * undo backend changes - too many errors * a few triages * another import * can't deprecate importorskip yet * assert_array_equal * assert_identical half way in ufuncs * backends merge * lint v1 * lint v2 * autopep8 all the things * lint final * undo some of the yapf crazyness * @Zac-HD dtype * remove more yapf overeagerness * test_ufuncs normal again * final lint normalize * a few left overs * xarray-specific functions changed in backends * undo self.AllClose * remove some old xarray funcs * assert_array_equal complete * remove assertVariable* * more parentheses please * install pytest through pip in 3.4 CI * flake8 fails on 3.4 only without this?
1 parent 0d69bf9 commit f3deb2f

28 files changed

+2471
-2500
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pip-log.txt
3232
.tox
3333
nosetests.xml
3434
.cache
35+
.ropeproject/
3536

3637
# Translations
3738
*.mo
@@ -51,4 +52,7 @@ doc/_build
5152
doc/generated
5253
xarray/version.py
5354

55+
# Sync tools
56+
Icon*
57+
5458
.ipynb_checkpoints

ci/requirements-py34.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ name: test_env
22
dependencies:
33
- python=3.4
44
- bottleneck
5-
- pytest
65
- flake8
76
- pandas
87
- pip:
98
- coveralls
109
- pytest-cov
10+
- pytest

xarray/conventions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ def ensure_dtype_not_object(var, name=None):
355355
fill_value = u''
356356
else:
357357
# insist on using float for numeric values
358-
if not np.issubdtype(inferred_dtype, float):
358+
if not np.issubdtype(inferred_dtype, np.floating):
359359
inferred_dtype = np.dtype(float)
360360
fill_value = inferred_dtype.type(np.nan)
361361

xarray/core/dataset.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1573,7 +1573,8 @@ def relevant_keys(mapping):
15731573
dim_name = dim
15741574
dim_coord = None
15751575

1576-
reordered = self.transpose(*(list(indexer_dims) + list(non_indexed_dims)))
1576+
reordered = self.transpose(
1577+
*(list(indexer_dims) + list(non_indexed_dims)))
15771578

15781579
variables = OrderedDict()
15791580

@@ -3383,7 +3384,8 @@ def rank(self, dim, pct=False, keep_attrs=False):
33833384
Variables that do not depend on `dim` are dropped.
33843385
"""
33853386
if dim not in self.dims:
3386-
raise ValueError('Dataset does not contain the dimension: %s' % dim)
3387+
raise ValueError(
3388+
'Dataset does not contain the dimension: %s' % dim)
33873389

33883390
variables = OrderedDict()
33893391
for name, var in iteritems(self.variables):

xarray/core/dtypes.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,15 @@ def maybe_promote(dtype):
2020
fill_value : Valid missing value for the promoted dtype.
2121
"""
2222
# N.B. these casting rules should match pandas
23-
if np.issubdtype(dtype, float):
23+
if np.issubdtype(dtype, np.floating):
2424
fill_value = np.nan
25-
elif np.issubdtype(dtype, int):
26-
# convert to floating point so NaN is valid
27-
dtype = float
25+
elif np.issubdtype(dtype, np.integer):
26+
if dtype.itemsize <= 2:
27+
dtype = np.float32
28+
else:
29+
dtype = np.float64
2830
fill_value = np.nan
29-
elif np.issubdtype(dtype, complex):
31+
elif np.issubdtype(dtype, np.complexfloating):
3032
fill_value = np.nan + np.nan * 1j
3133
elif np.issubdtype(dtype, np.datetime64):
3234
fill_value = np.datetime64('NaT')

xarray/core/indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -879,7 +879,7 @@ def __array__(self, dtype=None):
879879
if isinstance(array, pd.PeriodIndex):
880880
with suppress(AttributeError):
881881
# this might not be public API
882-
array = array.asobject
882+
array = array.astype('object')
883883
return np.asarray(array.values, dtype=dtype)
884884

885885
@property

xarray/core/missing.py

+3
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class NumpyInterpolator(BaseInterpolator):
4141
--------
4242
numpy.interp
4343
'''
44+
4445
def __init__(self, xi, yi, method='linear', fill_value=None, **kwargs):
4546

4647
if method != 'linear':
@@ -83,6 +84,7 @@ class ScipyInterpolator(BaseInterpolator):
8384
--------
8485
scipy.interpolate.interp1d
8586
'''
87+
8688
def __init__(self, xi, yi, method=None, fill_value=None,
8789
assume_sorted=True, copy=False, bounds_error=False, **kwargs):
8890
from scipy.interpolate import interp1d
@@ -118,6 +120,7 @@ class SplineInterpolator(BaseInterpolator):
118120
--------
119121
scipy.interpolate.UnivariateSpline
120122
'''
123+
121124
def __init__(self, xi, yi, method='spline', fill_value=None, order=3,
122125
**kwargs):
123126
from scipy.interpolate import UnivariateSpline

xarray/core/utils.py

+1
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,7 @@ class HiddenKeyDict(MutableMapping):
542542
Acts like a normal dictionary, but hides certain keys.
543543
'''
544544
# ``__init__`` method required to create instance from class.
545+
545546
def __init__(self, data, hidden_keys):
546547
self._data = data
547548
if type(hidden_keys) not in (list, tuple):

xarray/tests/__init__.py

+6-50
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,15 @@
88
import importlib
99

1010
import numpy as np
11-
from numpy.testing import assert_array_equal
11+
from numpy.testing import assert_array_equal # noqa: F401
1212
from xarray.core.duck_array_ops import allclose_or_equiv
1313
import pytest
1414

1515
from xarray.core import utils
1616
from xarray.core.pycompat import PY3
1717
from xarray.core.indexing import ExplicitlyIndexed
18-
from xarray.testing import assert_equal, assert_identical, assert_allclose
18+
from xarray.testing import (assert_equal, assert_identical, # noqa: F401
19+
assert_allclose)
1920
from xarray.plot.utils import import_seaborn
2021

2122
try:
@@ -109,6 +110,9 @@ def _importorskip(modname, minversion=None):
109110

110111

111112
class TestCase(unittest.TestCase):
113+
"""
114+
These functions are all deprecated. Instead, use functions in xr.testing
115+
"""
112116
if PY3:
113117
# Python 3 assertCountEqual is roughly equivalent to Python 2
114118
# assertItemsEqual
@@ -125,26 +129,10 @@ def assertWarns(self, message):
125129
assert len(w) > 0
126130
assert any(message in str(wi.message) for wi in w)
127131

128-
def assertVariableEqual(self, v1, v2):
129-
__tracebackhide__ = True # noqa: F841
130-
assert_equal(v1, v2)
131-
132-
def assertVariableIdentical(self, v1, v2):
133-
__tracebackhide__ = True # noqa: F841
134-
assert_identical(v1, v2)
135-
136-
def assertVariableAllClose(self, v1, v2, rtol=1e-05, atol=1e-08):
137-
__tracebackhide__ = True # noqa: F841
138-
assert_allclose(v1, v2, rtol=rtol, atol=atol)
139-
140132
def assertVariableNotEqual(self, v1, v2):
141133
__tracebackhide__ = True # noqa: F841
142134
assert not v1.equals(v2)
143135

144-
def assertArrayEqual(self, a1, a2):
145-
__tracebackhide__ = True # noqa: F841
146-
assert_array_equal(a1, a2)
147-
148136
def assertEqual(self, a1, a2):
149137
__tracebackhide__ = True # noqa: F841
150138
assert a1 == a2 or (a1 != a1 and a2 != a2)
@@ -153,38 +141,6 @@ def assertAllClose(self, a1, a2, rtol=1e-05, atol=1e-8):
153141
__tracebackhide__ = True # noqa: F841
154142
assert allclose_or_equiv(a1, a2, rtol=rtol, atol=atol)
155143

156-
def assertDatasetEqual(self, d1, d2):
157-
__tracebackhide__ = True # noqa: F841
158-
assert_equal(d1, d2)
159-
160-
def assertDatasetIdentical(self, d1, d2):
161-
__tracebackhide__ = True # noqa: F841
162-
assert_identical(d1, d2)
163-
164-
def assertDatasetAllClose(self, d1, d2, rtol=1e-05, atol=1e-08,
165-
decode_bytes=True):
166-
__tracebackhide__ = True # noqa: F841
167-
assert_allclose(d1, d2, rtol=rtol, atol=atol,
168-
decode_bytes=decode_bytes)
169-
170-
def assertCoordinatesEqual(self, d1, d2):
171-
__tracebackhide__ = True # noqa: F841
172-
assert_equal(d1, d2)
173-
174-
def assertDataArrayEqual(self, ar1, ar2):
175-
__tracebackhide__ = True # noqa: F841
176-
assert_equal(ar1, ar2)
177-
178-
def assertDataArrayIdentical(self, ar1, ar2):
179-
__tracebackhide__ = True # noqa: F841
180-
assert_identical(ar1, ar2)
181-
182-
def assertDataArrayAllClose(self, ar1, ar2, rtol=1e-05, atol=1e-08,
183-
decode_bytes=True):
184-
__tracebackhide__ = True # noqa: F841
185-
assert_allclose(ar1, ar2, rtol=rtol, atol=atol,
186-
decode_bytes=decode_bytes)
187-
188144

189145
@contextmanager
190146
def raises_regex(error, pattern):

xarray/tests/test_accessors.py

+15-14
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
import numpy as np
77
import pandas as pd
88

9-
from . import TestCase, requires_dask, raises_regex
9+
from . import (TestCase, requires_dask, raises_regex, assert_equal,
10+
assert_array_equal)
1011

1112

1213
class TestDatetimeAccessor(TestCase):
@@ -36,10 +37,10 @@ def test_field_access(self):
3637
hours = xr.DataArray(self.times.hour, name='hour',
3738
coords=[self.times, ], dims=['time', ])
3839

39-
self.assertDataArrayEqual(years, self.data.time.dt.year)
40-
self.assertDataArrayEqual(months, self.data.time.dt.month)
41-
self.assertDataArrayEqual(days, self.data.time.dt.day)
42-
self.assertDataArrayEqual(hours, self.data.time.dt.hour)
40+
assert_equal(years, self.data.time.dt.year)
41+
assert_equal(months, self.data.time.dt.month)
42+
assert_equal(days, self.data.time.dt.day)
43+
assert_equal(hours, self.data.time.dt.hour)
4344

4445
def test_not_datetime_type(self):
4546
nontime_data = self.data.copy()
@@ -75,16 +76,16 @@ def test_dask_field_access(self):
7576

7677
# Double check that outcome chunksize is unchanged
7778
dask_chunks = dask_times_2d.chunks
78-
self.assertEqual(dask_year.data.chunks, dask_chunks)
79-
self.assertEqual(dask_month.data.chunks, dask_chunks)
80-
self.assertEqual(dask_day.data.chunks, dask_chunks)
81-
self.assertEqual(dask_hour.data.chunks, dask_chunks)
79+
assert dask_year.data.chunks == dask_chunks
80+
assert dask_month.data.chunks == dask_chunks
81+
assert dask_day.data.chunks == dask_chunks
82+
assert dask_hour.data.chunks == dask_chunks
8283

8384
# Check the actual output from the accessors
84-
self.assertDataArrayEqual(years, dask_year.compute())
85-
self.assertDataArrayEqual(months, dask_month.compute())
86-
self.assertDataArrayEqual(days, dask_day.compute())
87-
self.assertDataArrayEqual(hours, dask_hour.compute())
85+
assert_equal(years, dask_year.compute())
86+
assert_equal(months, dask_month.compute())
87+
assert_equal(days, dask_day.compute())
88+
assert_equal(hours, dask_hour.compute())
8889

8990
def test_seasons(self):
9091
dates = pd.date_range(start="2000/01/01", freq="M", periods=12)
@@ -93,4 +94,4 @@ def test_seasons(self):
9394
"SON", "SON", "SON", "DJF"]
9495
seasons = xr.DataArray(seasons)
9596

96-
self.assertArrayEqual(seasons.values, dates.dt.season.values)
97+
assert_array_equal(seasons.values, dates.dt.season.values)

0 commit comments

Comments
 (0)