Created
December 7, 2016 18:04
-
-
Save pidpawel/9a88ef9d89a0ce997867394b67bf7932 to your computer and use it in GitHub Desktop.
Redirected stdout mock, mostly for testing purposes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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