From c79ecbf708a63a54a9c3e8d189b65d4794930082 Mon Sep 17 00:00:00 2001 From: Scott Gasch Date: Sat, 17 Jul 2021 14:47:01 -0700 Subject: Record streams. --- unittest_utils.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 3 deletions(-) (limited to 'unittest_utils.py') diff --git a/unittest_utils.py b/unittest_utils.py index e7090bc..5987da6 100644 --- a/unittest_utils.py +++ b/unittest_utils.py @@ -6,17 +6,16 @@ so that we getLogger config, commandline args, logging control, etc... this works fine but it's a little hacky so caveat emptor. """ +import contextlib import functools import inspect -import io import logging import pickle import random import statistics -import sys import time import tempfile -from typing import Callable, Iterable +from typing import Callable import unittest import bootstrap @@ -152,3 +151,70 @@ def breakpoint(): pdb.set_trace() +class RecordStdout(object): + """ + with uu.RecordStdout() as record: + print("This is a test!") + print({record().readline()}) + """ + + def __init__(self) -> None: + self.destination = tempfile.SpooledTemporaryFile(mode='r+') + self.recorder = None + + def __enter__(self) -> Callable[[], tempfile.SpooledTemporaryFile]: + self.recorder = contextlib.redirect_stdout(self.destination) + self.recorder.__enter__() + return lambda: self.destination + + def __exit__(self, *args) -> bool: + self.recorder.__exit__(*args) + self.destination.seek(0) + return True + + +class RecordStderr(object): + """ + with uu.RecordStderr() as record: + print("This is a test!", file=sys.stderr) + print({record().readline()}) + """ + + def __init__(self) -> None: + self.destination = tempfile.SpooledTemporaryFile(mode='r+') + self.recorder = None + + def __enter__(self) -> Callable[[], tempfile.SpooledTemporaryFile]: + self.recorder = contextlib.redirect_stderr(self.destination) + self.recorder.__enter__() + return lambda: self.destination + + def __exit__(self, *args) -> bool: + self.recorder.__exit__(*args) + self.destination.seek(0) + return True + + +class RecordMultipleStreams(object): + """ + with uu.RecordStreams(sys.stderr, sys.stdout) as record: + print("This is a test!") + print("This is one too.", file=sys.stderr) + + print(record().readlines()) + """ + def __init__(self, *files) -> None: + self.files = [*files] + self.destination = tempfile.SpooledTemporaryFile(mode='r+') + self.saved_writes = [] + + def __enter__(self) -> Callable[[], tempfile.SpooledTemporaryFile]: + for f in self.files: + self.saved_writes.append(f.write) + f.write = self.destination.write + return lambda: self.destination + + def __exit__(self, *args) -> bool: + for f in self.files: + f.write = self.saved_writes.pop() + self.destination.seek(0) -- cgit v1.3