Skip to content

Commit 1aa0510

Browse files
authored
TST: Replace xunit setup with methods (#29605)
1 parent 71eebaf commit 1aa0510

File tree

4 files changed

+97
-82
lines changed

4 files changed

+97
-82
lines changed

numpy/_core/tests/test_half.py

Lines changed: 54 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -18,56 +18,63 @@ def assert_raises_fpe(strmatch, callable, *args, **kwargs):
1818
f"Did not raise floating point {strmatch} error")
1919

2020
class TestHalf:
21-
def setup_method(self):
21+
def _create_arrays_all(self):
2222
# An array of all possible float16 values
23-
self.all_f16 = np.arange(0x10000, dtype=uint16)
24-
self.all_f16 = self.all_f16.view(float16)
23+
all_f16 = np.arange(0x10000, dtype=uint16)
24+
all_f16 = all_f16.view(float16)
2525

2626
# NaN value can cause an invalid FP exception if HW is being used
2727
with np.errstate(invalid='ignore'):
28-
self.all_f32 = np.array(self.all_f16, dtype=float32)
29-
self.all_f64 = np.array(self.all_f16, dtype=float64)
28+
all_f32 = np.array(all_f16, dtype=float32)
29+
all_f64 = np.array(all_f16, dtype=float64)
30+
return all_f16, all_f32, all_f64
3031

32+
def _create_arrays_nonan(self):
3133
# An array of all non-NaN float16 values, in sorted order
32-
self.nonan_f16 = np.concatenate(
34+
nonan_f16 = np.concatenate(
3335
(np.arange(0xfc00, 0x7fff, -1, dtype=uint16),
3436
np.arange(0x0000, 0x7c01, 1, dtype=uint16)))
35-
self.nonan_f16 = self.nonan_f16.view(float16)
36-
self.nonan_f32 = np.array(self.nonan_f16, dtype=float32)
37-
self.nonan_f64 = np.array(self.nonan_f16, dtype=float64)
38-
39-
# An array of all finite float16 values, in sorted order
40-
self.finite_f16 = self.nonan_f16[1:-1]
41-
self.finite_f32 = self.nonan_f32[1:-1]
42-
self.finite_f64 = self.nonan_f64[1:-1]
37+
nonan_f16 = nonan_f16.view(float16)
38+
nonan_f32 = np.array(nonan_f16, dtype=float32)
39+
nonan_f64 = np.array(nonan_f16, dtype=float64)
40+
return nonan_f16, nonan_f32, nonan_f64
41+
42+
def _create_arrays_finite(self):
43+
nonan_f16, nonan_f32, nonan_f64 = self._create_arrays_nonan()
44+
finite_f16 = nonan_f16[1:-1]
45+
finite_f32 = nonan_f32[1:-1]
46+
finite_f64 = nonan_f64[1:-1]
47+
return finite_f16, finite_f32, finite_f64
4348

4449
def test_half_conversions(self):
4550
"""Checks that all 16-bit values survive conversion
4651
to/from 32-bit and 64-bit float"""
4752
# Because the underlying routines preserve the NaN bits, every
4853
# value is preserved when converting to/from other floats.
54+
all_f16, all_f32, all_f64 = self._create_arrays_all()
55+
nonan_f16, _, _ = self._create_arrays_nonan()
4956

5057
# Convert from float32 back to float16
5158
with np.errstate(invalid='ignore'):
52-
b = np.array(self.all_f32, dtype=float16)
59+
b = np.array(all_f32, dtype=float16)
5360
# avoid testing NaNs due to differing bit patterns in Q/S NaNs
5461
b_nn = b == b
55-
assert_equal(self.all_f16[b_nn].view(dtype=uint16),
62+
assert_equal(all_f16[b_nn].view(dtype=uint16),
5663
b[b_nn].view(dtype=uint16))
5764

5865
# Convert from float64 back to float16
5966
with np.errstate(invalid='ignore'):
60-
b = np.array(self.all_f64, dtype=float16)
67+
b = np.array(all_f64, dtype=float16)
6168
b_nn = b == b
62-
assert_equal(self.all_f16[b_nn].view(dtype=uint16),
69+
assert_equal(all_f16[b_nn].view(dtype=uint16),
6370
b[b_nn].view(dtype=uint16))
6471

6572
# Convert float16 to longdouble and back
6673
# This doesn't necessarily preserve the extra NaN bits,
6774
# so exclude NaNs.
68-
a_ld = np.array(self.nonan_f16, dtype=np.longdouble)
75+
a_ld = np.array(nonan_f16, dtype=np.longdouble)
6976
b = np.array(a_ld, dtype=float16)
70-
assert_equal(self.nonan_f16.view(dtype=uint16),
77+
assert_equal(nonan_f16.view(dtype=uint16),
7178
b.view(dtype=uint16))
7279

7380
# Check the range for which all integers can be represented
@@ -171,34 +178,35 @@ def test_half_conversion_denormal_round_even(self, float_t, uint_t, bits):
171178
assert larger_value.astype(np.float16) == smallest_value
172179

173180
def test_nans_infs(self):
181+
all_f16, all_f32, _ = self._create_arrays_all()
174182
with np.errstate(all='ignore'):
175183
# Check some of the ufuncs
176-
assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
177-
assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
178-
assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
179-
assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
184+
assert_equal(np.isnan(all_f16), np.isnan(all_f32))
185+
assert_equal(np.isinf(all_f16), np.isinf(all_f32))
186+
assert_equal(np.isfinite(all_f16), np.isfinite(all_f32))
187+
assert_equal(np.signbit(all_f16), np.signbit(all_f32))
180188
assert_equal(np.spacing(float16(65504)), np.inf)
181189

182190
# Check comparisons of all values with NaN
183191
nan = float16(np.nan)
184192

185-
assert_(not (self.all_f16 == nan).any())
186-
assert_(not (nan == self.all_f16).any())
193+
assert_(not (all_f16 == nan).any())
194+
assert_(not (nan == all_f16).any())
187195

188-
assert_((self.all_f16 != nan).all())
189-
assert_((nan != self.all_f16).all())
196+
assert_((all_f16 != nan).all())
197+
assert_((nan != all_f16).all())
190198

191-
assert_(not (self.all_f16 < nan).any())
192-
assert_(not (nan < self.all_f16).any())
199+
assert_(not (all_f16 < nan).any())
200+
assert_(not (nan < all_f16).any())
193201

194-
assert_(not (self.all_f16 <= nan).any())
195-
assert_(not (nan <= self.all_f16).any())
202+
assert_(not (all_f16 <= nan).any())
203+
assert_(not (nan <= all_f16).any())
196204

197-
assert_(not (self.all_f16 > nan).any())
198-
assert_(not (nan > self.all_f16).any())
205+
assert_(not (all_f16 > nan).any())
206+
assert_(not (nan > all_f16).any())
199207

200-
assert_(not (self.all_f16 >= nan).any())
201-
assert_(not (nan >= self.all_f16).any())
208+
assert_(not (all_f16 >= nan).any())
209+
assert_(not (nan >= all_f16).any())
202210

203211
def test_half_values(self):
204212
"""Confirms a small number of known half values"""
@@ -255,9 +263,10 @@ def test_half_rounding(self):
255263
def test_half_correctness(self):
256264
"""Take every finite float16, and check the casting functions with
257265
a manual conversion."""
266+
finite_f16, finite_f32, finite_f64 = self._create_arrays_finite()
258267

259268
# Create an array of all finite float16s
260-
a_bits = self.finite_f16.view(dtype=uint16)
269+
a_bits = finite_f16.view(dtype=uint16)
261270

262271
# Convert to 64-bit float manually
263272
a_sgn = (-1.0)**((a_bits & 0x8000) >> 15)
@@ -270,29 +279,30 @@ def test_half_correctness(self):
270279

271280
a_manual = a_sgn * a_man * 2.0**a_exp
272281

273-
a32_fail = np.nonzero(self.finite_f32 != a_manual)[0]
282+
a32_fail = np.nonzero(finite_f32 != a_manual)[0]
274283
if len(a32_fail) != 0:
275284
bad_index = a32_fail[0]
276-
assert_equal(self.finite_f32, a_manual,
285+
assert_equal(finite_f32, a_manual,
277286
"First non-equal is half value 0x%x -> %g != %g" %
278287
(a_bits[bad_index],
279-
self.finite_f32[bad_index],
288+
finite_f32[bad_index],
280289
a_manual[bad_index]))
281290

282-
a64_fail = np.nonzero(self.finite_f64 != a_manual)[0]
291+
a64_fail = np.nonzero(finite_f64 != a_manual)[0]
283292
if len(a64_fail) != 0:
284293
bad_index = a64_fail[0]
285-
assert_equal(self.finite_f64, a_manual,
294+
assert_equal(finite_f64, a_manual,
286295
"First non-equal is half value 0x%x -> %g != %g" %
287296
(a_bits[bad_index],
288-
self.finite_f64[bad_index],
297+
finite_f64[bad_index],
289298
a_manual[bad_index]))
290299

291300
def test_half_ordering(self):
292301
"""Make sure comparisons are working right"""
302+
nonan_f16, _, _ = self._create_arrays_nonan()
293303

294304
# All non-NaN float16 values in reverse order
295-
a = self.nonan_f16[::-1].copy()
305+
a = nonan_f16[::-1].copy()
296306

297307
# 32-bit float copy
298308
b = np.array(a, dtype=float32)

numpy/_core/tests/test_indexing.py

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -776,6 +776,7 @@ def test_boolean_index_cast_assign(self):
776776
zero_array.__setitem__, bool_index, np.array([1j]))
777777
assert_equal(zero_array[0, 1], 0)
778778

779+
779780
class TestFancyIndexingEquivalence:
780781
def test_object_assign(self):
781782
# Check that the field and object special case using copyto is active.
@@ -846,10 +847,11 @@ class TestMultiIndexingAutomated:
846847
847848
"""
848849

849-
def setup_method(self):
850-
self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
851-
self.b = np.empty((3, 0, 5, 6))
852-
self.complex_indices = ['skip', Ellipsis,
850+
def _create_array(self):
851+
return np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
852+
853+
def _create_complex_indices(self):
854+
return ['skip', Ellipsis,
853855
0,
854856
# Boolean indices, up to 3-d for some special cases of eating up
855857
# dimensions, also need to test all False
@@ -869,11 +871,6 @@ def setup_method(self):
869871
np.array([2, -1], dtype=np.int8),
870872
np.zeros([1] * 31, dtype=int), # trigger too large array.
871873
np.array([0., 1.])] # invalid datatype
872-
# Some simpler indices that still cover a bit more
873-
self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]),
874-
'skip']
875-
# Very simple ones to fill the rest:
876-
self.fill_indices = [slice(None, None), 0]
877874

878875
def _get_multi_index(self, arr, indices):
879876
"""Mimic multi dimensional indexing.
@@ -1206,16 +1203,23 @@ def test_boolean(self):
12061203
# it is aligned to the left. This is probably correct for
12071204
# consistency with arr[boolean_array,] also no broadcasting
12081205
# is done at all
1206+
a = self._create_array()
12091207
self._check_multi_index(
1210-
self.a, (np.zeros_like(self.a, dtype=bool),))
1208+
a, (np.zeros_like(a, dtype=bool),))
12111209
self._check_multi_index(
1212-
self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],))
1210+
a, (np.zeros_like(a, dtype=bool)[..., 0],))
12131211
self._check_multi_index(
1214-
self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],))
1212+
a, (np.zeros_like(a, dtype=bool)[None, ...],))
12151213

12161214
def test_multidim(self):
12171215
# Automatically test combinations with complex indexes on 2nd (or 1st)
12181216
# spot and the simple ones in one other spot.
1217+
a = self._create_array()
1218+
b = np.empty((3, 0, 5, 6))
1219+
complex_indices = self._create_complex_indices()
1220+
simple_indices = [Ellipsis, None, -1, [1], np.array([True]), 'skip']
1221+
fill_indices = [slice(None, None), 0]
1222+
12191223
with warnings.catch_warnings():
12201224
# This is so that np.array(True) is not accepted in a full integer
12211225
# index, when running the file separately.
@@ -1226,28 +1230,30 @@ def isskip(idx):
12261230
return isinstance(idx, str) and idx == "skip"
12271231

12281232
for simple_pos in [0, 2, 3]:
1229-
tocheck = [self.fill_indices, self.complex_indices,
1230-
self.fill_indices, self.fill_indices]
1231-
tocheck[simple_pos] = self.simple_indices
1233+
tocheck = [fill_indices, complex_indices,
1234+
fill_indices, fill_indices]
1235+
tocheck[simple_pos] = simple_indices
12321236
for index in product(*tocheck):
12331237
index = tuple(i for i in index if not isskip(i))
1234-
self._check_multi_index(self.a, index)
1235-
self._check_multi_index(self.b, index)
1238+
self._check_multi_index(a, index)
1239+
self._check_multi_index(b, index)
12361240

12371241
# Check very simple item getting:
1238-
self._check_multi_index(self.a, (0, 0, 0, 0))
1239-
self._check_multi_index(self.b, (0, 0, 0, 0))
1242+
self._check_multi_index(a, (0, 0, 0, 0))
1243+
self._check_multi_index(b, (0, 0, 0, 0))
12401244
# Also check (simple cases of) too many indices:
1241-
assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0))
1242-
assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0)
1243-
assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0))
1244-
assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0)
1245+
assert_raises(IndexError, a.__getitem__, (0, 0, 0, 0, 0))
1246+
assert_raises(IndexError, a.__setitem__, (0, 0, 0, 0, 0), 0)
1247+
assert_raises(IndexError, a.__getitem__, (0, 0, [1], 0, 0))
1248+
assert_raises(IndexError, a.__setitem__, (0, 0, [1], 0, 0), 0)
12451249

12461250
def test_1d(self):
12471251
a = np.arange(10)
1248-
for index in self.complex_indices:
1252+
complex_indices = self._create_complex_indices()
1253+
for index in complex_indices:
12491254
self._check_single_index(a, index)
12501255

1256+
12511257
class TestFloatNonIntegerArgument:
12521258
"""
12531259
These test that ``TypeError`` is raised when you try to use

numpy/_core/tests/test_numerictypes.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -347,17 +347,16 @@ def test_assign(self):
347347

348348

349349
class TestMultipleFields:
350-
def setup_method(self):
351-
self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')
352-
353350
def _bad_call(self):
354-
return self.ary['f0', 'f1']
351+
ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')
352+
return ary['f0', 'f1']
355353

356354
def test_no_tuple(self):
357355
assert_raises(IndexError, self._bad_call)
358356

359357
def test_return(self):
360-
res = self.ary[['f0', 'f2']].tolist()
358+
ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')
359+
res = ary[['f0', 'f2']].tolist()
361360
assert_(res == [(1, 3), (5, 7)])
362361

363362

numpy/_core/tests/test_records.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -359,26 +359,26 @@ def test_tofile_fromfile(self):
359359

360360

361361
class TestRecord:
362-
def setup_method(self):
363-
self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
362+
def _create_data(self):
363+
return np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
364364
dtype=[("col1", "<i4"),
365365
("col2", "<i4"),
366366
("col3", "<i4")])
367367

368368
def test_assignment1(self):
369-
a = self.data
369+
a = self._create_data()
370370
assert_equal(a.col1[0], 1)
371371
a[0].col1 = 0
372372
assert_equal(a.col1[0], 0)
373373

374374
def test_assignment2(self):
375-
a = self.data
375+
a = self._create_data()
376376
assert_equal(a.col1[0], 1)
377377
a.col1[0] = 0
378378
assert_equal(a.col1[0], 0)
379379

380380
def test_invalid_assignment(self):
381-
a = self.data
381+
a = self._create_data()
382382

383383
def assign_invalid_column(x):
384384
x[0].col5 = 1
@@ -396,14 +396,14 @@ def test_nonwriteable_setfield(self):
396396

397397
def test_out_of_order_fields(self):
398398
# names in the same order, padding added to descr
399-
x = self.data[['col1', 'col2']]
399+
x = self._create_data()[['col1', 'col2']]
400400
assert_equal(x.dtype.names, ('col1', 'col2'))
401401
assert_equal(x.dtype.descr,
402402
[('col1', '<i4'), ('col2', '<i4'), ('', '|V4')])
403403

404404
# names change order to match indexing, as of 1.14 - descr can't
405405
# represent that
406-
y = self.data[['col2', 'col1']]
406+
y = self._create_data()[['col2', 'col1']]
407407
assert_equal(y.dtype.names, ('col2', 'col1'))
408408
assert_raises(ValueError, lambda: y.dtype.descr)
409409

@@ -416,15 +416,15 @@ def test_pickle_1(self):
416416
protocol=proto)))
417417

418418
def test_pickle_2(self):
419-
a = self.data
419+
a = self._create_data()
420420
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
421421
assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto)))
422422
assert_equal(a[0], pickle.loads(pickle.dumps(a[0],
423423
protocol=proto)))
424424

425425
def test_pickle_3(self):
426426
# Issue #7140
427-
a = self.data
427+
a = self._create_data()
428428
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
429429
pa = pickle.loads(pickle.dumps(a[0], protocol=proto))
430430
assert_(pa.flags.c_contiguous)

0 commit comments

Comments
 (0)