Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redirected stdout mock, mostly for testing purposes
import sys
import io
class RedirectedStdout:
def __init__(self):
self.old_stdout = sys.stdout
self.file = io.StringIO()
def __enter__(self):
sys.stdout = self.file
return self
def __exit__(self, *args):
sys.stdout = self.old_stdout
def get_value(self):
self.file.seek(0, io.SEEK_SET)
contents = self.file.read()
self.file.seek(0, io.SEEK_END)
return contents
def test_rso():
def foo():
print("Ala ma kota.")
print("A Tomek ma dwa psy.")
with RedirectedStdout() as so:
foo()
assert so.get_value() == "Ala ma kota.\nA Tomek ma dwa psy.\n"
assert so.get_value() == "Ala ma kota.\nA Tomek ma dwa psy.\n"
foo()
assert so.get_value() == "Ala ma kota.\nA Tomek ma dwa psy.\nAla ma kota.\nA Tomek ma dwa psy.\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.