Debian Codegraph @

_pytest/capture.py

raw symbols SCIP
1 """
2 per-test stdout/stderr capturing mechanism.
3
4 """
5 from __future__ import with_statement
6
7 import sys
8 import os
9 from tempfile import TemporaryFile
10
11 import py
12 import pytest
13
14 from py.io import TextIO
15 unicode = py.builtin.text
16
17 patchsysdict = {0: 'stdin', 1: 'stdout', 2: 'stderr'}
18
19
20 def pytest_addoption(parser):
21 group = parser.getgroup("general")
22 group._addoption(
23 '--capture', action="store",
24 default="fd" if hasattr(os, "dup") else "sys",
25 metavar="method", choices=['fd', 'sys', 'no'],
26 help="per-test capturing method: one of fd|sys|no.")
27 group._addoption(
28 '-s', action="store_const", const="no", dest="capture",
29 help="shortcut for --capture=no.")
30
31
32 @pytest.hookimpl(hookwrapper=True)
33 def pytest_load_initial_conftests(early_config, parser, args):
34 _readline_workaround()
35 ns = early_config.known_args_namespace
36 pluginmanager = early_config.pluginmanager
37 capman = CaptureManager(ns.capture)
38 pluginmanager.register(capman, "capturemanager")
39
40 # make sure that capturemanager is properly reset at final shutdown
41 early_config.add_cleanup(capman.reset_capturings)
42
43 # make sure logging does not raise exceptions at the end
44 def silence_logging_at_shutdown():
45 if "logging" in sys.modules:
46 sys.modules["logging"].raiseExceptions = False
47 early_config.add_cleanup(silence_logging_at_shutdown)
48
49 # finally trigger conftest loading but while capturing (issue93)
50 capman.init_capturings()
51 outcome = yield
52 out, err = capman.suspendcapture()
53 if outcome.excinfo is not None:
54 sys.stdout.write(out)
55 sys.stderr.write(err)
56
57
58 class CaptureManager:
59 def __init__(self, method):
60 self._method = method
61
62 def _getcapture(self, method):
63 if method == "fd":
64 return MultiCapture(out=True, err=True, Capture=FDCapture)
65 elif method == "sys":
66 return MultiCapture(out=True, err=True, Capture=SysCapture)
67 elif method == "no":
68 return MultiCapture(out=False, err=False, in_=False)
69 else:
70 raise ValueError("unknown capturing method: %r" % method)
71
72 def init_capturings(self):
73 assert not hasattr(self, "_capturing")
74 self._capturing = self._getcapture(self._method)
75 self._capturing.start_capturing()
76
77 def reset_capturings(self):
78 cap = self.__dict__.pop("_capturing", None)
79 if cap is not None:
80 cap.pop_outerr_to_orig()
81 cap.stop_capturing()
82
83 def resumecapture(self):
84 self._capturing.resume_capturing()
85
86 def suspendcapture(self, in_=False):
87 self.deactivate_funcargs()
88 cap = getattr(self, "_capturing", None)
89 if cap is not None:
90 try:
91 outerr = cap.readouterr()
92 finally:
93 cap.suspend_capturing(in_=in_)
94 return outerr
95
96 def activate_funcargs(self, pyfuncitem):
97 capfuncarg = pyfuncitem.__dict__.pop("_capfuncarg", None)
98 if capfuncarg is not None:
99 capfuncarg._start()
100 self._capfuncarg = capfuncarg
101
102 def deactivate_funcargs(self):
103 capfuncarg = self.__dict__.pop("_capfuncarg", None)
104 if capfuncarg is not None:
105 capfuncarg.close()
106
107 @pytest.hookimpl(hookwrapper=True)
108 def pytest_make_collect_report(self, collector):
109 if isinstance(collector, pytest.File):
110 self.resumecapture()
111 outcome = yield
112 out, err = self.suspendcapture()
113 rep = outcome.get_result()
114 if out:
115 rep.sections.append(("Captured stdout", out))
116 if err:
117 rep.sections.append(("Captured stderr", err))
118 else:
119 yield
120
121 @pytest.hookimpl(hookwrapper=True)
122 def pytest_runtest_setup(self, item):
123 self.resumecapture()
124 yield
125 self.suspendcapture_item(item, "setup")
126
127 @pytest.hookimpl(hookwrapper=True)
128 def pytest_runtest_call(self, item):
129 self.resumecapture()
130 self.activate_funcargs(item)
131 yield
132 #self.deactivate_funcargs() called from suspendcapture()
133 self.suspendcapture_item(item, "call")
134
135 @pytest.hookimpl(hookwrapper=True)
136 def pytest_runtest_teardown(self, item):
137 self.resumecapture()
138 yield
139 self.suspendcapture_item(item, "teardown")
140
141 @pytest.hookimpl(tryfirst=True)
142 def pytest_keyboard_interrupt(self, excinfo):
143 self.reset_capturings()
144
145 @pytest.hookimpl(tryfirst=True)
146 def pytest_internalerror(self, excinfo):
147 self.reset_capturings()
148
149 def suspendcapture_item(self, item, when):
150 out, err = self.suspendcapture()
151 item.add_report_section(when, "stdout", out)
152 item.add_report_section(when, "stderr", err)
153
154 error_capsysfderror = "cannot use capsys and capfd at the same time"
155
156
157 @pytest.fixture
158 def capsys(request):
159 """enables capturing of writes to sys.stdout/sys.stderr and makes
160 captured output available via ``capsys.readouterr()`` method calls
161 which return a ``(out, err)`` tuple.
162 """
163 if "capfd" in request._funcargs:
164 raise request.raiseerror(error_capsysfderror)
165 request.node._capfuncarg = c = CaptureFixture(SysCapture)
166 return c
167
168 @pytest.fixture
169 def capfd(request):
170 """enables capturing of writes to file descriptors 1 and 2 and makes
171 captured output available via ``capfd.readouterr()`` method calls
172 which return a ``(out, err)`` tuple.
173 """
174 if "capsys" in request._funcargs:
175 request.raiseerror(error_capsysfderror)
176 if not hasattr(os, 'dup'):
177 pytest.skip("capfd funcarg needs os.dup")
178 request.node._capfuncarg = c = CaptureFixture(FDCapture)
179 return c
180
181
182 class CaptureFixture:
183 def __init__(self, captureclass):
184 self.captureclass = captureclass
185
186 def _start(self):
187 self._capture = MultiCapture(out=True, err=True, in_=False,
188 Capture=self.captureclass)
189 self._capture.start_capturing()
190
191 def close(self):
192 cap = self.__dict__.pop("_capture", None)
193 if cap is not None:
194 self._outerr = cap.pop_outerr_to_orig()
195 cap.stop_capturing()
196
197 def readouterr(self):
198 try:
199 return self._capture.readouterr()
200 except AttributeError:
201 return self._outerr
202
203
204 def safe_text_dupfile(f, mode, default_encoding="UTF8"):
205 """ return a open text file object that's a duplicate of f on the
206 FD-level if possible.
207 """
208 encoding = getattr(f, "encoding", None)
209 try:
210 fd = f.fileno()
211 except Exception:
212 if "b" not in getattr(f, "mode", "") and hasattr(f, "encoding"):
213 # we seem to have a text stream, let's just use it
214 return f
215 else:
216 newfd = os.dup(fd)
217 if "b" not in mode:
218 mode += "b"
219 f = os.fdopen(newfd, mode, 0) # no buffering
220 return EncodedFile(f, encoding or default_encoding)
221
222
223 class EncodedFile(object):
224 errors = "strict" # possibly needed by py3 code (issue555)
225 def __init__(self, buffer, encoding):
226 self.buffer = buffer
227 self.encoding = encoding
228
229 def write(self, obj):
230 if isinstance(obj, unicode):
231 obj = obj.encode(self.encoding, "replace")
232 self.buffer.write(obj)
233
234 def writelines(self, linelist):
235 data = ''.join(linelist)
236 self.write(data)
237
238 def __getattr__(self, name):
239 return getattr(object.__getattribute__(self, "buffer"), name)
240
241
242 class MultiCapture(object):
243 out = err = in_ = None
244
245 def __init__(self, out=True, err=True, in_=True, Capture=None):
246 if in_:
247 self.in_ = Capture(0)
248 if out:
249 self.out = Capture(1)
250 if err:
251 self.err = Capture(2)
252
253 def start_capturing(self):
254 if self.in_:
255 self.in_.start()
256 if self.out:
257 self.out.start()
258 if self.err:
259 self.err.start()
260
261 def pop_outerr_to_orig(self):
262 """ pop current snapshot out/err capture and flush to orig streams. """
263 out, err = self.readouterr()
264 if out:
265 self.out.writeorg(out)
266 if err:
267 self.err.writeorg(err)
268 return out, err
269
270 def suspend_capturing(self, in_=False):
271 if self.out:
272 self.out.suspend()
273 if self.err:
274 self.err.suspend()
275 if in_ and self.in_:
276 self.in_.suspend()
277 self._in_suspended = True
278
279 def resume_capturing(self):
280 if self.out:
281 self.out.resume()
282 if self.err:
283 self.err.resume()
284 if hasattr(self, "_in_suspended"):
285 self.in_.resume()
286 del self._in_suspended
287
288 def stop_capturing(self):
289 """ stop capturing and reset capturing streams """
290 if hasattr(self, '_reset'):
291 raise ValueError("was already stopped")
292 self._reset = True
293 if self.out:
294 self.out.done()
295 if self.err:
296 self.err.done()
297 if self.in_:
298 self.in_.done()
299
300 def readouterr(self):
301 """ return snapshot unicode value of stdout/stderr capturings. """
302 return (self.out.snap() if self.out is not None else "",
303 self.err.snap() if self.err is not None else "")
304
305 class NoCapture:
306 __init__ = start = done = suspend = resume = lambda *args: None
307
308 class FDCapture:
309 """ Capture IO to/from a given os-level filedescriptor. """
310
311 def __init__(self, targetfd, tmpfile=None):
312 self.targetfd = targetfd
313 try:
314 self.targetfd_save = os.dup(self.targetfd)
315 except OSError:
316 self.start = lambda: None
317 self.done = lambda: None
318 else:
319 if targetfd == 0:
320 assert not tmpfile, "cannot set tmpfile with stdin"
321 tmpfile = open(os.devnull, "r")
322 self.syscapture = SysCapture(targetfd)
323 else:
324 if tmpfile is None:
325 f = TemporaryFile()
326 with f:
327 tmpfile = safe_text_dupfile(f, mode="wb+")
328 if targetfd in patchsysdict:
329 self.syscapture = SysCapture(targetfd, tmpfile)
330 else:
331 self.syscapture = NoCapture()
332 self.tmpfile = tmpfile
333 self.tmpfile_fd = tmpfile.fileno()
334
335 def __repr__(self):
336 return "<FDCapture %s oldfd=%s>" % (self.targetfd, self.targetfd_save)
337
338 def start(self):
339 """ Start capturing on targetfd using memorized tmpfile. """
340 try:
341 os.fstat(self.targetfd_save)
342 except (AttributeError, OSError):
343 raise ValueError("saved filedescriptor not valid anymore")
344 os.dup2(self.tmpfile_fd, self.targetfd)
345 self.syscapture.start()
346
347 def snap(self):
348 f = self.tmpfile
349 f.seek(0)
350 res = f.read()
351 if res:
352 enc = getattr(f, "encoding", None)
353 if enc and isinstance(res, bytes):
354 res = py.builtin._totext(res, enc, "replace")
355 f.truncate(0)
356 f.seek(0)
357 return res
358 return ''
359
360 def done(self):
361 """ stop capturing, restore streams, return original capture file,
362 seeked to position zero. """
363 targetfd_save = self.__dict__.pop("targetfd_save")
364 os.dup2(targetfd_save, self.targetfd)
365 os.close(targetfd_save)
366 self.syscapture.done()
367 self.tmpfile.close()
368
369 def suspend(self):
370 self.syscapture.suspend()
371 os.dup2(self.targetfd_save, self.targetfd)
372
373 def resume(self):
374 self.syscapture.resume()
375 os.dup2(self.tmpfile_fd, self.targetfd)
376
377 def writeorg(self, data):
378 """ write to original file descriptor. """
379 if py.builtin._istext(data):
380 data = data.encode("utf8") # XXX use encoding of original stream
381 os.write(self.targetfd_save, data)
382
383
384 class SysCapture:
385 def __init__(self, fd, tmpfile=None):
386 name = patchsysdict[fd]
387 self._old = getattr(sys, name)
388 self.name = name
389 if tmpfile is None:
390 if name == "stdin":
391 tmpfile = DontReadFromInput()
392 else:
393 tmpfile = TextIO()
394 self.tmpfile = tmpfile
395
396 def start(self):
397 setattr(sys, self.name, self.tmpfile)
398
399 def snap(self):
400 f = self.tmpfile
401 res = f.getvalue()
402 f.truncate(0)
403 f.seek(0)
404 return res
405
406 def done(self):
407 setattr(sys, self.name, self._old)
408 del self._old
409 self.tmpfile.close()
410
411 def suspend(self):
412 setattr(sys, self.name, self._old)
413
414 def resume(self):
415 setattr(sys, self.name, self.tmpfile)
416
417 def writeorg(self, data):
418 self._old.write(data)
419 self._old.flush()
420
421
422 class DontReadFromInput:
423 """Temporary stub class. Ideally when stdin is accessed, the
424 capturing should be turned off, with possibly all data captured
425 so far sent to the screen. This should be configurable, though,
426 because in automated test runs it is better to crash than
427 hang indefinitely.
428 """
429
430 encoding = None
431
432 def read(self, *args):
433 raise IOError("reading from stdin while output is captured")
434 readline = read
435 readlines = read
436 __iter__ = read
437
438 def fileno(self):
439 raise ValueError("redirected Stdin is pseudofile, has no fileno()")
440
441 def isatty(self):
442 return False
443
444 def close(self):
445 pass
446
447
448 def _readline_workaround():
449 """
450 Ensure readline is imported so that it attaches to the correct stdio
451 handles on Windows.
452
453 Pdb uses readline support where available--when not running from the Python
454 prompt, the readline module is not imported until running the pdb REPL. If
455 running py.test with the --pdb option this means the readline module is not
456 imported until after I/O capture has been started.
457
458 This is a problem for pyreadline, which is often used to implement readline
459 support on Windows, as it does not attach to the correct handles for stdout
460 and/or stdin if they have been redirected by the FDCapture mechanism. This
461 workaround ensures that readline is imported before I/O capture is setup so
462 that it can attach to the actual stdin/out for the console.
463
464 See https://github.com/pytest-dev/pytest/pull/1281
465 """
466
467 if not sys.platform.startswith('win32'):
468 return
469 try:
470 import readline # noqa
471 except ImportError:
472 pass