Last active
August 29, 2015 14:06
-
-
Save felixcarmona/2fe6a56cbdb4e4dbccf5 to your computer and use it in GitHub Desktop.
Assert Ouput in python test
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
from unittest import TestCase | |
import sys | |
from StringIO import StringIO | |
class OutputTestCase(TestCase): | |
def assertOutput(self, expected_output): | |
return _AssertOutputContext(expected_output, self) | |
class _AssertOutputContext(): | |
def __init__(self, expected_output, test_case): | |
""" | |
@param expected_output: str | |
@param test_case: unittest.TestCase | |
""" | |
self._expected_output = expected_output | |
self._test_case = test_case | |
def __enter__(self): | |
self._saved_stdout = sys.stdout | |
self._out = StringIO() | |
sys.stdout = self._out | |
def __exit__(self, *args): | |
actual_output = self._out.getvalue().strip() | |
try: | |
self._test_case.assertEquals(self._expected_output, actual_output) | |
finally: | |
sys.stdout = self._saved_stdout | |
# class ExampleTestCase(OutputTestCase): | |
# def test_example(self): | |
# with self.assertOutput('Hello\nWorld'): | |
# print('Hello') | |
# print('World') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment