conftest.py 5.74 KB
Newer Older
Dean Moldovan's avatar
Dean Moldovan committed
1
2
3
"""pytest configuration

Extends output capture as needed by pybind11: ignore constructors, optional unordered lines.
4
Adds docstring and exceptions message sanitizers.
Dean Moldovan's avatar
Dean Moldovan committed
5
6
7
"""

import contextlib
8
import difflib
Wenzel Jakob's avatar
Wenzel Jakob committed
9
import gc
10
11
import multiprocessing
import os
12
13
import re
import textwrap
14
import traceback
15
16
17
18

import pytest

# Early diagnostic for failed imports
19
20
21
22
23
24
try:
    import pybind11_tests
except Exception:
    # pytest does not show the traceback without this.
    traceback.print_exc()
    raise
Dean Moldovan's avatar
Dean Moldovan committed
25

26
27
28
29
30
31

@pytest.fixture(scope="session", autouse=True)
def always_forkserver_on_unix():
    if os.name == "nt":
        return

32
33
34
35
36
37
38
39
40
    # Full background: https://github.com/pybind/pybind11/issues/4105#issuecomment-1301004592
    # In a nutshell: fork() after starting threads == flakiness in the form of deadlocks.
    # It is actually a well-known pitfall, unfortunately without guard rails.
    # "forkserver" is more performant than "spawn" (~9s vs ~13s for tests/test_gil_scoped.py,
    # visit the issuecomment link above for details).
    # Windows does not have fork() and the associated pitfall, therefore it is best left
    # running with defaults.
    multiprocessing.set_start_method("forkserver")

41

42
43
_long_marker = re.compile(r"([0-9])L")
_hexadecimal = re.compile(r"0x[0-9a-fA-F]+")
Dean Moldovan's avatar
Dean Moldovan committed
44

45
46
47
# Avoid collecting Python3 only files
collect_ignore = []

Dean Moldovan's avatar
Dean Moldovan committed
48
49
50

def _strip_and_dedent(s):
    """For triple-quote strings"""
51
    return textwrap.dedent(s.lstrip("\n").rstrip())
Dean Moldovan's avatar
Dean Moldovan committed
52
53
54
55
56
57
58
59
60


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]"""
61
62
63
    return ["--- actual / +++ expected"] + [
        line.strip("\n") for line in difflib.ndiff(a, b)
    ]
Dean Moldovan's avatar
Dean Moldovan committed
64
65


66
class Output:
Dean Moldovan's avatar
Dean Moldovan committed
67
    """Basic output post-processing and comparison"""
68

Dean Moldovan's avatar
Dean Moldovan committed
69
70
71
72
73
74
75
76
77
    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 "###"
78
79
80
81
82
        a = [
            line
            for line in self.string.strip().splitlines()
            if not line.startswith("###")
        ]
Dean Moldovan's avatar
Dean Moldovan committed
83
84
85
86
87
88
89
90
91
92
        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"""
93

Dean Moldovan's avatar
Dean Moldovan committed
94
95
96
97
98
99
100
101
102
103
    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


104
class Capture:
Dean Moldovan's avatar
Dean Moldovan committed
105
106
107
    def __init__(self, capfd):
        self.capfd = capfd
        self.out = ""
Dean Moldovan's avatar
Dean Moldovan committed
108
        self.err = ""
Dean Moldovan's avatar
Dean Moldovan committed
109
110

    def __enter__(self):
111
        self.capfd.readouterr()
Dean Moldovan's avatar
Dean Moldovan committed
112
113
        return self

Wenzel Jakob's avatar
Wenzel Jakob committed
114
    def __exit__(self, *args):
115
        self.out, self.err = self.capfd.readouterr()
Dean Moldovan's avatar
Dean Moldovan committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

    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
136
137
138
139
    @property
    def stderr(self):
        return Output(self.err)

Dean Moldovan's avatar
Dean Moldovan committed
140
141

@pytest.fixture
142
143
144
def capture(capsys):
    """Extended `capsys` with context manager and custom equality operators"""
    return Capture(capsys)
Dean Moldovan's avatar
Dean Moldovan committed
145
146


147
class SanitizedString:
Dean Moldovan's avatar
Dean Moldovan committed
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    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 = _long_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"""
202
    if hasattr(left, "explanation"):
Dean Moldovan's avatar
Dean Moldovan committed
203
204
205
206
207
208
209
210
211
212
213
214
        return left.explanation


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


Wenzel Jakob's avatar
Wenzel Jakob committed
215
def gc_collect():
216
217
    """Run the garbage collector twice (needed when running
    reference counting tests with PyPy)"""
Wenzel Jakob's avatar
Wenzel Jakob committed
218
219
220
221
    gc.collect()
    gc.collect()


222
223
224
def pytest_configure():
    pytest.suppress = suppress
    pytest.gc_collect = gc_collect
225
226
227
228
229
230
231
232
233
234
235
236


def pytest_report_header(config):
    del config  # Unused.
    assert (
        pybind11_tests.compiler_info is not None
    ), "Please update pybind11_tests.cpp if this assert fails."
    return (
        "C++ Info:"
        f" {pybind11_tests.compiler_info}"
        f" {pybind11_tests.cpp_std}"
        f" {pybind11_tests.PYBIND11_INTERNALS_ID}"
237
        f" PYBIND11_SIMPLE_GIL_MANAGEMENT={pybind11_tests.PYBIND11_SIMPLE_GIL_MANAGEMENT}"
238
    )