You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

239 lines
6.4 KiB

2 months ago
  1. """pytest configuration
  2. Extends output capture as needed by pybind11: ignore constructors, optional unordered lines.
  3. Adds docstring and exceptions message sanitizers: ignore Python 2 vs 3 differences.
  4. """
  5. import pytest
  6. import textwrap
  7. import difflib
  8. import re
  9. import sys
  10. import contextlib
  11. import platform
  12. import gc
  13. _unicode_marker = re.compile(r'u(\'[^\']*\')')
  14. _long_marker = re.compile(r'([0-9])L')
  15. _hexadecimal = re.compile(r'0x[0-9a-fA-F]+')
  16. def _strip_and_dedent(s):
  17. """For triple-quote strings"""
  18. return textwrap.dedent(s.lstrip('\n').rstrip())
  19. def _split_and_sort(s):
  20. """For output which does not require specific line order"""
  21. return sorted(_strip_and_dedent(s).splitlines())
  22. def _make_explanation(a, b):
  23. """Explanation for a failed assert -- the a and b arguments are List[str]"""
  24. return ["--- actual / +++ expected"] + [line.strip('\n') for line in difflib.ndiff(a, b)]
  25. class Output(object):
  26. """Basic output post-processing and comparison"""
  27. def __init__(self, string):
  28. self.string = string
  29. self.explanation = []
  30. def __str__(self):
  31. return self.string
  32. def __eq__(self, other):
  33. # Ignore constructor/destructor output which is prefixed with "###"
  34. a = [line for line in self.string.strip().splitlines() if not line.startswith("###")]
  35. b = _strip_and_dedent(other).splitlines()
  36. if a == b:
  37. return True
  38. else:
  39. self.explanation = _make_explanation(a, b)
  40. return False
  41. class Unordered(Output):
  42. """Custom comparison for output without strict line ordering"""
  43. def __eq__(self, other):
  44. a = _split_and_sort(self.string)
  45. b = _split_and_sort(other)
  46. if a == b:
  47. return True
  48. else:
  49. self.explanation = _make_explanation(a, b)
  50. return False
  51. class Capture(object):
  52. def __init__(self, capfd):
  53. self.capfd = capfd
  54. self.out = ""
  55. self.err = ""
  56. def __enter__(self):
  57. self.capfd.readouterr()
  58. return self
  59. def __exit__(self, *_):
  60. self.out, self.err = self.capfd.readouterr()
  61. def __eq__(self, other):
  62. a = Output(self.out)
  63. b = other
  64. if a == b:
  65. return True
  66. else:
  67. self.explanation = a.explanation
  68. return False
  69. def __str__(self):
  70. return self.out
  71. def __contains__(self, item):
  72. return item in self.out
  73. @property
  74. def unordered(self):
  75. return Unordered(self.out)
  76. @property
  77. def stderr(self):
  78. return Output(self.err)
  79. @pytest.fixture
  80. def capture(capsys):
  81. """Extended `capsys` with context manager and custom equality operators"""
  82. return Capture(capsys)
  83. class SanitizedString(object):
  84. def __init__(self, sanitizer):
  85. self.sanitizer = sanitizer
  86. self.string = ""
  87. self.explanation = []
  88. def __call__(self, thing):
  89. self.string = self.sanitizer(thing)
  90. return self
  91. def __eq__(self, other):
  92. a = self.string
  93. b = _strip_and_dedent(other)
  94. if a == b:
  95. return True
  96. else:
  97. self.explanation = _make_explanation(a.splitlines(), b.splitlines())
  98. return False
  99. def _sanitize_general(s):
  100. s = s.strip()
  101. s = s.replace("pybind11_tests.", "m.")
  102. s = s.replace("unicode", "str")
  103. s = _long_marker.sub(r"\1", s)
  104. s = _unicode_marker.sub(r"\1", s)
  105. return s
  106. def _sanitize_docstring(thing):
  107. s = thing.__doc__
  108. s = _sanitize_general(s)
  109. return s
  110. @pytest.fixture
  111. def doc():
  112. """Sanitize docstrings and add custom failure explanation"""
  113. return SanitizedString(_sanitize_docstring)
  114. def _sanitize_message(thing):
  115. s = str(thing)
  116. s = _sanitize_general(s)
  117. s = _hexadecimal.sub("0", s)
  118. return s
  119. @pytest.fixture
  120. def msg():
  121. """Sanitize messages and add custom failure explanation"""
  122. return SanitizedString(_sanitize_message)
  123. # noinspection PyUnusedLocal
  124. def pytest_assertrepr_compare(op, left, right):
  125. """Hook to insert custom failure explanation"""
  126. if hasattr(left, 'explanation'):
  127. return left.explanation
  128. @contextlib.contextmanager
  129. def suppress(exception):
  130. """Suppress the desired exception"""
  131. try:
  132. yield
  133. except exception:
  134. pass
  135. def gc_collect():
  136. ''' Run the garbage collector twice (needed when running
  137. reference counting tests with PyPy) '''
  138. gc.collect()
  139. gc.collect()
  140. def pytest_namespace():
  141. """Add import suppression and test requirements to `pytest` namespace"""
  142. try:
  143. import numpy as np
  144. except ImportError:
  145. np = None
  146. try:
  147. import scipy
  148. except ImportError:
  149. scipy = None
  150. try:
  151. from pybind11_tests import have_eigen
  152. except ImportError:
  153. have_eigen = False
  154. pypy = platform.python_implementation() == "PyPy"
  155. skipif = pytest.mark.skipif
  156. return {
  157. 'suppress': suppress,
  158. 'requires_numpy': skipif(not np, reason="numpy is not installed"),
  159. 'requires_scipy': skipif(not np, reason="scipy is not installed"),
  160. 'requires_eigen_and_numpy': skipif(not have_eigen or not np,
  161. reason="eigen and/or numpy are not installed"),
  162. 'requires_eigen_and_scipy': skipif(not have_eigen or not scipy,
  163. reason="eigen and/or scipy are not installed"),
  164. 'unsupported_on_pypy': skipif(pypy, reason="unsupported on PyPy"),
  165. 'gc_collect': gc_collect
  166. }
  167. def _test_import_pybind11():
  168. """Early diagnostic for test module initialization errors
  169. When there is an error during initialization, the first import will report the
  170. real error while all subsequent imports will report nonsense. This import test
  171. is done early (in the pytest configuration file, before any tests) in order to
  172. avoid the noise of having all tests fail with identical error messages.
  173. Any possible exception is caught here and reported manually *without* the stack
  174. trace. This further reduces noise since the trace would only show pytest internals
  175. which are not useful for debugging pybind11 module issues.
  176. """
  177. # noinspection PyBroadException
  178. try:
  179. import pybind11_tests # noqa: F401 imported but unused
  180. except Exception as e:
  181. print("Failed to import pybind11_tests from pytest:")
  182. print(" {}: {}".format(type(e).__name__, e))
  183. sys.exit(1)
  184. _test_import_pybind11()