conftest.py 7.02 KB
Newer Older
1
# -*- coding: utf-8 -*-
Dean Moldovan's avatar
Dean Moldovan committed
2
3
4
5
6
7
8
9
10
11
12
13
"""pytest configuration

Extends output capture as needed by pybind11: ignore constructors, optional unordered lines.
Adds docstring and exceptions message sanitizers: ignore Python 2 vs 3 differences.
"""

import pytest
import textwrap
import difflib
import re
import sys
import contextlib
Wenzel Jakob's avatar
Wenzel Jakob committed
14
15
import platform
import gc
Dean Moldovan's avatar
Dean Moldovan committed
16
17

_unicode_marker = re.compile(r'u(\'[^\']*\')')
18
19
_long_marker = re.compile(r'([0-9])L')
_hexadecimal = re.compile(r'0x[0-9a-fA-F]+')
Dean Moldovan's avatar
Dean Moldovan committed
20

21
22
23
24
25
# test_async.py requires support for async and await
collect_ignore = []
if sys.version_info[:2] < (3, 5):
    collect_ignore.append("test_async.py")

Dean Moldovan's avatar
Dean Moldovan committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

def _strip_and_dedent(s):
    """For triple-quote strings"""
    return textwrap.dedent(s.lstrip('\n').rstrip())


def _split_and_sort(s):
    """For output which does not require specific line order"""
    return sorted(_strip_and_dedent(s).splitlines())


def _make_explanation(a, b):
    """Explanation for a failed assert -- the a and b arguments are List[str]"""
    return ["--- actual / +++ expected"] + [line.strip('\n') for line in difflib.ndiff(a, b)]


class Output(object):
    """Basic output post-processing and comparison"""
    def __init__(self, string):
        self.string = string
        self.explanation = []

    def __str__(self):
        return self.string

    def __eq__(self, other):
        # Ignore constructor/destructor output which is prefixed with "###"
        a = [line for line in self.string.strip().splitlines() if not line.startswith("###")]
        b = _strip_and_dedent(other).splitlines()
        if a == b:
            return True
        else:
            self.explanation = _make_explanation(a, b)
            return False


class Unordered(Output):
    """Custom comparison for output without strict line ordering"""
    def __eq__(self, other):
        a = _split_and_sort(self.string)
        b = _split_and_sort(other)
        if a == b:
            return True
        else:
            self.explanation = _make_explanation(a, b)
            return False


class Capture(object):
    def __init__(self, capfd):
        self.capfd = capfd
        self.out = ""
Dean Moldovan's avatar
Dean Moldovan committed
78
        self.err = ""
Dean Moldovan's avatar
Dean Moldovan committed
79
80

    def __enter__(self):
81
        self.capfd.readouterr()
Dean Moldovan's avatar
Dean Moldovan committed
82
83
        return self

Wenzel Jakob's avatar
Wenzel Jakob committed
84
    def __exit__(self, *args):
85
        self.out, self.err = self.capfd.readouterr()
Dean Moldovan's avatar
Dean Moldovan committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

    def __eq__(self, other):
        a = Output(self.out)
        b = other
        if a == b:
            return True
        else:
            self.explanation = a.explanation
            return False

    def __str__(self):
        return self.out

    def __contains__(self, item):
        return item in self.out

    @property
    def unordered(self):
        return Unordered(self.out)

Dean Moldovan's avatar
Dean Moldovan committed
106
107
108
109
    @property
    def stderr(self):
        return Output(self.err)

Dean Moldovan's avatar
Dean Moldovan committed
110
111

@pytest.fixture
112
113
114
def capture(capsys):
    """Extended `capsys` with context manager and custom equality operators"""
    return Capture(capsys)
Dean Moldovan's avatar
Dean Moldovan committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186


class SanitizedString(object):
    def __init__(self, sanitizer):
        self.sanitizer = sanitizer
        self.string = ""
        self.explanation = []

    def __call__(self, thing):
        self.string = self.sanitizer(thing)
        return self

    def __eq__(self, other):
        a = self.string
        b = _strip_and_dedent(other)
        if a == b:
            return True
        else:
            self.explanation = _make_explanation(a.splitlines(), b.splitlines())
            return False


def _sanitize_general(s):
    s = s.strip()
    s = s.replace("pybind11_tests.", "m.")
    s = s.replace("unicode", "str")
    s = _long_marker.sub(r"\1", s)
    s = _unicode_marker.sub(r"\1", s)
    return s


def _sanitize_docstring(thing):
    s = thing.__doc__
    s = _sanitize_general(s)
    return s


@pytest.fixture
def doc():
    """Sanitize docstrings and add custom failure explanation"""
    return SanitizedString(_sanitize_docstring)


def _sanitize_message(thing):
    s = str(thing)
    s = _sanitize_general(s)
    s = _hexadecimal.sub("0", s)
    return s


@pytest.fixture
def msg():
    """Sanitize messages and add custom failure explanation"""
    return SanitizedString(_sanitize_message)


# noinspection PyUnusedLocal
def pytest_assertrepr_compare(op, left, right):
    """Hook to insert custom failure explanation"""
    if hasattr(left, 'explanation'):
        return left.explanation


@contextlib.contextmanager
def suppress(exception):
    """Suppress the desired exception"""
    try:
        yield
    except exception:
        pass


Wenzel Jakob's avatar
Wenzel Jakob committed
187
188
189
190
191
192
193
def gc_collect():
    ''' Run the garbage collector twice (needed when running
    reference counting tests with PyPy) '''
    gc.collect()
    gc.collect()


194
def pytest_configure():
Dean Moldovan's avatar
Dean Moldovan committed
195
196
197
198
199
200
201
202
203
204
    """Add import suppression and test requirements to `pytest` namespace"""
    try:
        import numpy as np
    except ImportError:
        np = None
    try:
        import scipy
    except ImportError:
        scipy = None
    try:
205
        from pybind11_tests.eigen import have_eigen
Dean Moldovan's avatar
Dean Moldovan committed
206
207
    except ImportError:
        have_eigen = False
Wenzel Jakob's avatar
Wenzel Jakob committed
208
    pypy = platform.python_implementation() == "PyPy"
Dean Moldovan's avatar
Dean Moldovan committed
209
210

    skipif = pytest.mark.skipif
211
212
213
214
215
216
217
218
    pytest.suppress = suppress
    pytest.requires_numpy = skipif(not np, reason="numpy is not installed")
    pytest.requires_scipy = skipif(not np, reason="scipy is not installed")
    pytest.requires_eigen_and_numpy = skipif(not have_eigen or not np,
                                             reason="eigen and/or numpy are not installed")
    pytest.requires_eigen_and_scipy = skipif(
        not have_eigen or not scipy, reason="eigen and/or scipy are not installed")
    pytest.unsupported_on_pypy = skipif(pypy, reason="unsupported on PyPy")
Isuru Fernando's avatar
Isuru Fernando committed
219
220
221
222
223
    pytest.bug_in_pypy = pytest.mark.xfail(pypy, reason="bug in PyPy")
    pytest.unsupported_on_pypy3 = skipif(pypy and sys.version_info.major >= 3,
                                         reason="unsupported on PyPy3")
    pytest.unsupported_on_pypy_lt_6 = skipif(pypy and sys.pypy_version_info[0] < 6,
                                             reason="unsupported on PyPy<6")
224
225
226
    pytest.unsupported_on_py2 = skipif(sys.version_info.major < 3,
                                       reason="unsupported on Python 2.x")
    pytest.gc_collect = gc_collect
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242


def _test_import_pybind11():
    """Early diagnostic for test module initialization errors

    When there is an error during initialization, the first import will report the
    real error while all subsequent imports will report nonsense. This import test
    is done early (in the pytest configuration file, before any tests) in order to
    avoid the noise of having all tests fail with identical error messages.

    Any possible exception is caught here and reported manually *without* the stack
    trace. This further reduces noise since the trace would only show pytest internals
    which are not useful for debugging pybind11 module issues.
    """
    # noinspection PyBroadException
    try:
243
        import pybind11_tests  # noqa: F401 imported but unused
244
245
246
247
248
249
250
    except Exception as e:
        print("Failed to import pybind11_tests from pytest:")
        print("  {}: {}".format(type(e).__name__, e))
        sys.exit(1)


_test_import_pybind11()