hbutils.testing.capture

Overview:

Utilities for capturing different kinds of results, which can be useful in testing.

capture_output

hbutils.testing.capture.capture_output(mem: bool = False) → AbstractContextManager[hbutils.testing.capture.output.OutputCaptureResult][source]
Overview:

Capture all the output to sys.stdout and sys.stderr in this with block.

Parameters:

mem – Use memory to put the result or not. Default is False which means the output will be redirected to temporary files.

Examples::
>>> from hbutils.testing import capture_output
>>> import sys
>>>
>>> with capture_output() as r:
...     print('this is stdout')
...     print('this is stderr', file=sys.stderr)
...
>>> r.stdout
'this is stdout\n'
>>> r.stderr
'this is stderr\n'

Note

When mem is set to True, io.StringIO is used, which do not have fileno method. This may cause some problems in some cases (such as subprocess.run()).

OutputCaptureResult

class hbutils.testing.capture.OutputCaptureResult[source]
Overview:

Result model of output capturing.

__init__()[source]

Constructor of OutputCaptureResult.

put_result(stdout: Optional[str], stderr: Optional[str])[source]

Put result inside this model.

Parameters:
  • stdout – Stdout result.

  • stderr – Stderr result.

property stderr

Stderr of the output result.

Note

Do not use this property when capture_output()’s with block is not quited, or this property will be jammed due to the deadlock inside.

property stdout

Stdout of the output result.

Note

Do not use this property when capture_output()’s with block is not quited, or this property will be jammed due to the deadlock inside.

disable_output

hbutils.testing.capture.disable_output() → AbstractContextManager[hbutils.testing.capture.output.OutputCaptureResult][source]
Overview:

Disable all the output to sys.stdout and sys.stderr in this with block.

Examples::
>>> import sys
>>> from hbutils.testing import disable_output
>>>
>>> with disable_output():  # no output will be shown
...     print('this is stdout')
...     print('this is stderr', file=sys.stderr)