Skip to content

Commit

Permalink
Merge pull request #22489 from charris/backport-22487
Browse files Browse the repository at this point in the history
TST, MAINT: Replace most setup with setup_method (also teardown)
  • Loading branch information
charris committed Oct 28, 2022
2 parents 52ba138 + 9b31daf commit 3b22591
Show file tree
Hide file tree
Showing 35 changed files with 224 additions and 157 deletions.
17 changes: 10 additions & 7 deletions doc/TESTS.rst.txt
Expand Up @@ -178,30 +178,33 @@ Similarly for methods::
Easier setup and teardown functions / methods
---------------------------------------------

Testing looks for module-level or class-level setup and teardown functions by
name; thus::
Testing looks for module-level or class method-level setup and teardown
functions by name; thus::

def setup():
def setup_module():
"""Module-level setup"""
print('doing setup')

def teardown():
def teardown_module():
"""Module-level teardown"""
print('doing teardown')


class TestMe:
def setup():
def setup_method(self):
"""Class-level setup"""
print('doing setup')

def teardown():
def teardown_method():
"""Class-level teardown"""
print('doing teardown')


Setup and teardown functions to functions and methods are known as "fixtures",
and their use is not encouraged.
and they should be used sparingly.
``pytest`` supports more general fixture at various scopes which may be used
automatically via special arguments. For example, the special argument name
``tmpdir`` is used in test to create a temporary directory.

Parametric tests
----------------
Expand Down
4 changes: 2 additions & 2 deletions numpy/core/tests/test_arrayprint.py
Expand Up @@ -498,10 +498,10 @@ def test_refcount(self):
class TestPrintOptions:
"""Test getting and setting global print options."""

def setup(self):
def setup_method(self):
self.oldopts = np.get_printoptions()

def teardown(self):
def teardown_method(self):
np.set_printoptions(**self.oldopts)

def test_basic(self):
Expand Down
20 changes: 10 additions & 10 deletions numpy/core/tests/test_defchararray.py
Expand Up @@ -132,7 +132,7 @@ def fail():


class TestWhitespace:
def setup(self):
def setup_method(self):
self.A = np.array([['abc ', '123 '],
['789 ', 'xyz ']]).view(np.chararray)
self.B = np.array([['abc', '123'],
Expand All @@ -147,15 +147,15 @@ def test1(self):
assert_(not np.any(self.A != self.B))

class TestChar:
def setup(self):
def setup_method(self):
self.A = np.array('abc1', dtype='c').view(np.chararray)

def test_it(self):
assert_equal(self.A.shape, (4,))
assert_equal(self.A.upper()[:2].tobytes(), b'AB')

class TestComparisons:
def setup(self):
def setup_method(self):
self.A = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
self.B = np.array([['efg', '123 '],
Expand Down Expand Up @@ -188,21 +188,21 @@ def test_type(self):
class TestComparisonsMixed1(TestComparisons):
"""Ticket #1276"""

def setup(self):
TestComparisons.setup(self)
def setup_method(self):
TestComparisons.setup_method(self)
self.B = np.array([['efg', '123 '],
['051', 'tuv']], np.unicode_).view(np.chararray)

class TestComparisonsMixed2(TestComparisons):
"""Ticket #1276"""

def setup(self):
TestComparisons.setup(self)
def setup_method(self):
TestComparisons.setup_method(self)
self.A = np.array([['abc', '123'],
['789', 'xyz']], np.unicode_).view(np.chararray)

class TestInformation:
def setup(self):
def setup_method(self):
self.A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
Expand Down Expand Up @@ -308,7 +308,7 @@ def fail():


class TestMethods:
def setup(self):
def setup_method(self):
self.A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']],
Expand Down Expand Up @@ -581,7 +581,7 @@ def fail():


class TestOperations:
def setup(self):
def setup_method(self):
self.A = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
self.B = np.array([['efg', '456'],
Expand Down
8 changes: 4 additions & 4 deletions numpy/core/tests/test_deprecations.py
Expand Up @@ -32,7 +32,7 @@ class _DeprecationTestCase:
message = ''
warning_cls = DeprecationWarning

def setup(self):
def setup_method(self):
self.warn_ctx = warnings.catch_warnings(record=True)
self.log = self.warn_ctx.__enter__()

Expand All @@ -46,7 +46,7 @@ def setup(self):
warnings.filterwarnings("always", message=self.message,
category=self.warning_cls)

def teardown(self):
def teardown_method(self):
self.warn_ctx.__exit__()

def assert_deprecated(self, function, num=1, ignore_others=False,
Expand Down Expand Up @@ -297,7 +297,7 @@ class vdt(np.void):
class TestTestDeprecated:
def test_assert_deprecated(self):
test_case_instance = _DeprecationTestCase()
test_case_instance.setup()
test_case_instance.setup_method()
assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
Expand All @@ -306,7 +306,7 @@ def foo():
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)

test_case_instance.assert_deprecated(foo)
test_case_instance.teardown()
test_case_instance.teardown_method()


class TestNonNumericConjugate(_DeprecationTestCase):
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/tests/test_half.py
Expand Up @@ -17,7 +17,7 @@ def assert_raises_fpe(strmatch, callable, *args, **kwargs):
"Did not raise floating point %s error" % strmatch)

class TestHalf:
def setup(self):
def setup_method(self):
# An array of all possible float16 values
self.all_f16 = np.arange(0x10000, dtype=uint16)
self.all_f16.dtype = float16
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/tests/test_indexing.py
Expand Up @@ -826,7 +826,7 @@ class TestMultiIndexingAutomated:
"""

def setup(self):
def setup_method(self):
self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
self.b = np.empty((3, 0, 5, 6))
self.complex_indices = ['skip', Ellipsis,
Expand Down
4 changes: 2 additions & 2 deletions numpy/core/tests/test_memmap.py
Expand Up @@ -15,14 +15,14 @@
)

class TestMemmap:
def setup(self):
def setup_method(self):
self.tmpfp = NamedTemporaryFile(prefix='mmap')
self.shape = (3, 4)
self.dtype = 'float32'
self.data = arange(12, dtype=self.dtype)
self.data.resize(self.shape)

def teardown(self):
def teardown_method(self):
self.tmpfp.close()
self.data = None
if IS_PYPY:
Expand Down
18 changes: 9 additions & 9 deletions numpy/core/tests/test_multiarray.py
Expand Up @@ -74,7 +74,7 @@ def _aligned_zeros(shape, dtype=float, order="C", align=None):


class TestFlags:
def setup(self):
def setup_method(self):
self.a = np.arange(10)

def test_writeable(self):
Expand Down Expand Up @@ -275,7 +275,7 @@ def test_int(self):


class TestAttributes:
def setup(self):
def setup_method(self):
self.one = np.arange(10)
self.two = np.arange(20).reshape(4, 5)
self.three = np.arange(60, dtype=np.float64).reshape(2, 5, 6)
Expand Down Expand Up @@ -652,7 +652,7 @@ def test_structured_non_void(self):


class TestZeroRank:
def setup(self):
def setup_method(self):
self.d = np.array(0), np.array('x', object)

def test_ellipsis_subscript(self):
Expand Down Expand Up @@ -756,7 +756,7 @@ def test_real_imag(self):


class TestScalarIndexing:
def setup(self):
def setup_method(self):
self.d = np.array([0, 1])[0]

def test_ellipsis_subscript(self):
Expand Down Expand Up @@ -5672,7 +5672,7 @@ def test_mmap_close(self):
mm.close()

class TestFlat:
def setup(self):
def setup_method(self):
a0 = np.arange(20.0)
a = a0.reshape(4, 5)
a0.shape = (4, 5)
Expand Down Expand Up @@ -5995,7 +5995,7 @@ class TestStats:

funcs = [_mean, _var, _std]

def setup(self):
def setup_method(self):
np.random.seed(range(3))
self.rmat = np.random.random((4, 5))
self.cmat = self.rmat + 1j * self.rmat
Expand Down Expand Up @@ -6422,7 +6422,7 @@ def test_vdot_uncontiguous(self):


class TestDot:
def setup(self):
def setup_method(self):
np.random.seed(128)
self.A = np.random.rand(4, 2)
self.b1 = np.random.rand(2, 1)
Expand Down Expand Up @@ -7214,7 +7214,7 @@ def test_3d_tensor(self):


class TestChoose:
def setup(self):
def setup_method(self):
self.x = 2*np.ones((3,), dtype=int)
self.y = 3*np.ones((3,), dtype=int)
self.x2 = 2*np.ones((2, 3), dtype=int)
Expand Down Expand Up @@ -7244,7 +7244,7 @@ def test_output_dtype(self, ops):


class TestRepeat:
def setup(self):
def setup_method(self):
self.m = np.array([1, 2, 3, 4, 5, 6])
self.m_rect = self.m.reshape((2, 3))

Expand Down
26 changes: 13 additions & 13 deletions numpy/core/tests/test_numeric.py
Expand Up @@ -347,7 +347,7 @@ def test_bitwise_xor(self):


class TestBoolArray:
def setup(self):
def setup_method(self):
# offset for simd tests
self.t = np.array([True] * 41, dtype=bool)[1::]
self.f = np.array([False] * 41, dtype=bool)[1::]
Expand Down Expand Up @@ -434,7 +434,7 @@ def test_logical_and_or_xor(self):


class TestBoolCmp:
def setup(self):
def setup_method(self):
self.f = np.ones(256, dtype=np.float32)
self.ef = np.ones(self.f.size, dtype=bool)
self.d = np.ones(128, dtype=np.float64)
Expand Down Expand Up @@ -1813,7 +1813,7 @@ def assert_array_strict_equal(x, y):


class TestClip:
def setup(self):
def setup_method(self):
self.nr = 5
self.nc = 3

Expand Down Expand Up @@ -2442,10 +2442,10 @@ class TestAllclose:
rtol = 1e-5
atol = 1e-8

def setup(self):
def setup_method(self):
self.olderr = np.seterr(invalid='ignore')

def teardown(self):
def teardown_method(self):
np.seterr(**self.olderr)

def tst_allclose(self, x, y):
Expand Down Expand Up @@ -2527,7 +2527,7 @@ class TestIsclose:
rtol = 1e-5
atol = 1e-8

def setup(self):
def _setup(self):
atol = self.atol
rtol = self.rtol
arr = np.array([100, 1000])
Expand Down Expand Up @@ -2573,7 +2573,7 @@ def setup(self):
]

def test_ip_isclose(self):
self.setup()
self._setup()
tests = self.some_close_tests
results = self.some_close_results
for (x, y), result in zip(tests, results):
Expand All @@ -2595,17 +2595,17 @@ def tst_isclose_allclose(self, x, y):
assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y))

def test_ip_all_isclose(self):
self.setup()
self._setup()
for (x, y) in self.all_close_tests:
self.tst_all_isclose(x, y)

def test_ip_none_isclose(self):
self.setup()
self._setup()
for (x, y) in self.none_close_tests:
self.tst_none_isclose(x, y)

def test_ip_isclose_allclose(self):
self.setup()
self._setup()
tests = (self.all_close_tests + self.none_close_tests +
self.some_close_tests)
for (x, y) in tests:
Expand Down Expand Up @@ -2671,7 +2671,7 @@ def test_timedelta(self):


class TestStdVar:
def setup(self):
def setup_method(self):
self.A = np.array([1, -1, 1, -1])
self.real_var = 1

Expand Down Expand Up @@ -2724,7 +2724,7 @@ def test_scalars(self):
class TestCreationFuncs:
# Test ones, zeros, empty and full.

def setup(self):
def setup_method(self):
dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())}
# void, bytes, str
variable_sized = {tp for tp in dtypes if tp.str.endswith('0')}
Expand Down Expand Up @@ -2795,7 +2795,7 @@ def test_for_reference_leak(self):
class TestLikeFuncs:
'''Test ones_like, zeros_like, empty_like and full_like'''

def setup(self):
def setup_method(self):
self.data = [
# Array scalars
(np.array(3.), None),
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/tests/test_numerictypes.py
Expand Up @@ -357,7 +357,7 @@ def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose
assert_(res == 'f8')

class TestMultipleFields:
def setup(self):
def setup_method(self):
self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')

def _bad_call(self):
Expand Down

0 comments on commit 3b22591

Please sign in to comment.