f4c228260ba3e51404ad2c30d1403f2416ccb1bc
1 """pytest configuration
3 Extends output capture as needed by pybind11: ignore constructors, optional unordered lines.
4 Adds docstring and exceptions message sanitizers: ignore Python 2 vs 3 differences.
16 _unicode_marker
= re
.compile(r
'u(\'[^
\']*\')')
17 _long_marker = re.compile(r'([0-9])L
')
18 _hexadecimal = re.compile(r'0x
[0-9a
-fA
-F
]+')
21 def _strip_and_dedent(s):
22 """For triple-quote strings"""
23 return textwrap.dedent(s.lstrip('\n').rstrip())
26 def _split_and_sort(s):
27 """For output which does not require specific line order"""
28 return sorted(_strip_and_dedent(s).splitlines())
31 def _make_explanation(a, b):
32 """Explanation for a failed assert -- the a and b arguments are List[str]"""
33 return ["--- actual / +++ expected"] + [line.strip('\n') for line in difflib.ndiff(a, b)]
37 """Basic output post-processing and comparison"""
38 def __init__(self, string):
45 def __eq__(self, other):
46 # Ignore constructor/destructor output which is prefixed with "###"
47 a = [line for line in self.string.strip().splitlines() if not line.startswith("###")]
48 b = _strip_and_dedent(other).splitlines()
52 self.explanation = _make_explanation(a, b)
56 class Unordered(Output):
57 """Custom comparison for output without strict line ordering"""
58 def __eq__(self, other):
59 a = _split_and_sort(self.string)
60 b = _split_and_sort(other)
64 self.explanation = _make_explanation(a, b)
68 class Capture(object):
69 def __init__(self, capfd):
75 self.capfd.readouterr()
78 def __exit__(self, *_):
79 self.out, self.err = self.capfd.readouterr()
81 def __eq__(self, other):
87 self.explanation = a.explanation
93 def __contains__(self, item):
94 return item in self.out
98 return Unordered(self.out)
102 return Output(self.err)
107 """Extended `capsys` with context manager and custom equality operators"""
108 return Capture(capsys)
111 class SanitizedString(object):
112 def __init__(self, sanitizer):
113 self.sanitizer = sanitizer
115 self.explanation = []
117 def __call__(self, thing):
118 self.string = self.sanitizer(thing)
121 def __eq__(self, other):
123 b = _strip_and_dedent(other)
127 self.explanation = _make_explanation(a.splitlines(), b.splitlines())
131 def _sanitize_general(s):
133 s = s.replace("pybind11_tests.", "m.")
134 s = s.replace("unicode", "str")
135 s = _long_marker.sub(r"\1", s)
136 s = _unicode_marker.sub(r"\1", s)
140 def _sanitize_docstring(thing):
142 s = _sanitize_general(s)
148 """Sanitize docstrings and add custom failure explanation"""
149 return SanitizedString(_sanitize_docstring)
152 def _sanitize_message(thing):
154 s = _sanitize_general(s)
155 s = _hexadecimal.sub("0", s)
161 """Sanitize messages and add custom failure explanation"""
162 return SanitizedString(_sanitize_message)
165 # noinspection PyUnusedLocal
166 def pytest_assertrepr_compare(op, left, right):
167 """Hook to insert custom failure explanation"""
168 if hasattr(left, 'explanation
'):
169 return left.explanation
172 @contextlib.contextmanager
173 def suppress(exception):
174 """Suppress the desired exception"""
182 ''' Run the garbage collector twice (needed when running
183 reference counting tests with PyPy) '''
188 def pytest_namespace():
189 """Add import suppression and test requirements to `pytest` namespace"""
199 from pybind11_tests.eigen import have_eigen
202 pypy = platform.python_implementation() == "PyPy"
204 skipif = pytest.mark.skipif
206 'suppress
': suppress,
207 'requires_numpy
': skipif(not np, reason="numpy is not installed"),
208 'requires_scipy
': skipif(not np, reason="scipy is not installed"),
209 'requires_eigen_and_numpy
': skipif(not have_eigen or not np,
210 reason="eigen and/or numpy are not installed"),
211 'requires_eigen_and_scipy
': skipif(not have_eigen or not scipy,
212 reason="eigen and/or scipy are not installed"),
213 'unsupported_on_pypy
': skipif(pypy, reason="unsupported on PyPy"),
214 'unsupported_on_py2
': skipif(sys.version_info.major < 3,
215 reason="unsupported on Python 2.x"),
216 'gc_collect
': gc_collect
220 def _test_import_pybind11():
221 """Early diagnostic for test module initialization errors
223 When there is an error during initialization, the first import will report the
224 real error while all subsequent imports will report nonsense. This import test
225 is done early (in the pytest configuration file, before any tests) in order to
226 avoid the noise of having all tests fail with identical error messages.
228 Any possible exception is caught here and reported manually *without* the stack
229 trace. This further reduces noise since the trace would only show pytest internals
230 which are not useful for debugging pybind11 module issues.
232 # noinspection PyBroadException
234 import pybind11_tests # noqa: F401 imported but unused
235 except Exception as e:
236 print("Failed to import pybind11_tests from pytest:")
237 print(" {}: {}".format(type(e).__name__, e))
241 _test_import_pybind11()