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.

227 lines
6.0 KiB

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