1"""
2Pytest test running.
3
4This module implements the ``test()`` function for NumPy modules. The usual
5boiler plate for doing that is to put the following in the module
6``__init__.py`` file::
7
8 from numpy._pytesttester import PytestTester
9 test = PytestTester(__name__)
10 del PytestTester
11
12
13Warnings filtering and other runtime settings should be dealt with in the
14``pytest.ini`` file in the numpy repo root. The behavior of the test depends on
15whether or not that file is found as follows:
16
17* ``pytest.ini`` is present (develop mode)
18 All warnings except those explicitly filtered out are raised as error.
19* ``pytest.ini`` is absent (release mode)
20 DeprecationWarnings and PendingDeprecationWarnings are ignored, other
21 warnings are passed through.
22
23In practice, tests run from the numpy repo are run in development mode with
24``spin``, through the standard ``spin test`` invocation or from an inplace
25build with ``pytest numpy``.
26
27This module is imported by every numpy subpackage, so lies at the top level to
28simplify circular import issues. For the same reason, it contains no numpy
29imports at module scope, instead importing numpy within function calls.
30"""
31import sys
32import os
33
34__all__ = ['PytestTester']
35
36
37def _show_numpy_info():
38 import numpy as np
39
40 print("NumPy version %s" % np.__version__)
41 info = np.lib._utils_impl._opt_info()
42 print("NumPy CPU features: ", (info if info else 'nothing enabled'))
43
44
45class PytestTester:
46 """
47 Pytest test runner.
48
49 A test function is typically added to a package's __init__.py like so::
50
51 from numpy._pytesttester import PytestTester
52 test = PytestTester(__name__).test
53 del PytestTester
54
55 Calling this test function finds and runs all tests associated with the
56 module and all its sub-modules.
57
58 Attributes
59 ----------
60 module_name : str
61 Full path to the package to test.
62
63 Parameters
64 ----------
65 module_name : module name
66 The name of the module to test.
67
68 Notes
69 -----
70 Unlike the previous ``nose``-based implementation, this class is not
71 publicly exposed as it performs some ``numpy``-specific warning
72 suppression.
73
74 """
75 def __init__(self, module_name):
76 self.module_name = module_name
77 self.__module__ = module_name
78
79 def __call__(self, label='fast', verbose=1, extra_argv=None,
80 doctests=False, coverage=False, durations=-1, tests=None):
81 """
82 Run tests for module using pytest.
83
84 Parameters
85 ----------
86 label : {'fast', 'full'}, optional
87 Identifies the tests to run. When set to 'fast', tests decorated
88 with `pytest.mark.slow` are skipped, when 'full', the slow marker
89 is ignored.
90 verbose : int, optional
91 Verbosity value for test outputs, in the range 1-3. Default is 1.
92 extra_argv : list, optional
93 List with any extra arguments to pass to pytests.
94 doctests : bool, optional
95 .. note:: Not supported
96 coverage : bool, optional
97 If True, report coverage of NumPy code. Default is False.
98 Requires installation of (pip) pytest-cov.
99 durations : int, optional
100 If < 0, do nothing, If 0, report time of all tests, if > 0,
101 report the time of the slowest `timer` tests. Default is -1.
102 tests : test or list of tests
103 Tests to be executed with pytest '--pyargs'
104
105 Returns
106 -------
107 result : bool
108 Return True on success, false otherwise.
109
110 Notes
111 -----
112 Each NumPy module exposes `test` in its namespace to run all tests for
113 it. For example, to run all tests for numpy.lib:
114
115 >>> np.lib.test() #doctest: +SKIP
116
117 Examples
118 --------
119 >>> result = np.lib.test() #doctest: +SKIP
120 ...
121 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds
122 >>> result
123 True
124
125 """
126 import pytest
127 import warnings
128
129 module = sys.modules[self.module_name]
130 module_path = os.path.abspath(module.__path__[0])
131
132 # setup the pytest arguments
133 pytest_args = ["-l"]
134
135 # offset verbosity. The "-q" cancels a "-v".
136 pytest_args += ["-q"]
137
138 if sys.version_info < (3, 12):
139 with warnings.catch_warnings():
140 warnings.simplefilter("always")
141 # Filter out distutils cpu warnings (could be localized to
142 # distutils tests). ASV has problems with top level import,
143 # so fetch module for suppression here.
144 from numpy.distutils import cpuinfo
145
146 # Filter out annoying import messages. Want these in both develop and
147 # release mode.
148 pytest_args += [
149 "-W ignore:Not importing directory",
150 "-W ignore:numpy.dtype size changed",
151 "-W ignore:numpy.ufunc size changed",
152 "-W ignore::UserWarning:cpuinfo",
153 ]
154
155 # When testing matrices, ignore their PendingDeprecationWarnings
156 pytest_args += [
157 "-W ignore:the matrix subclass is not",
158 "-W ignore:Importing from numpy.matlib is",
159 ]
160
161 if doctests:
162 pytest_args += ["--doctest-modules"]
163
164 if extra_argv:
165 pytest_args += list(extra_argv)
166
167 if verbose > 1:
168 pytest_args += ["-" + "v"*(verbose - 1)]
169
170 if coverage:
171 pytest_args += ["--cov=" + module_path]
172
173 if label == "fast":
174 # not importing at the top level to avoid circular import of module
175 from numpy.testing import IS_PYPY
176 if IS_PYPY:
177 pytest_args += ["-m", "not slow and not slow_pypy"]
178 else:
179 pytest_args += ["-m", "not slow"]
180
181 elif label != "full":
182 pytest_args += ["-m", label]
183
184 if durations >= 0:
185 pytest_args += ["--durations=%s" % durations]
186
187 if tests is None:
188 tests = [self.module_name]
189
190 pytest_args += ["--pyargs"] + list(tests)
191
192 # run tests.
193 _show_numpy_info()
194
195 try:
196 code = pytest.main(pytest_args)
197 except SystemExit as exc:
198 code = exc.code
199
200 return code == 0