I'm using unittest
to test my terminal interactive utility. I have 2 test cases with very similar contexts: one tests for correct output and other for correct handling of user commands in interactive mode. Although, both cases mock sys.stdout
to suppress actual output (output is performed in process of interactive work as well).
Consider the following:
class StdoutOutputTestCase(unittest.TestCase):
"""Tests whether the stuff is printed correctly."""
def setUp(self):
self.patcher_stdout = mock.patch('sys.stdout', StringIO())
self.patcher_stdout.start()
# Do testing
def tearDown(self):
self.patcher_stdout.stop()
class UserInteractionTestCase(unittest.TestCase):
"""Tests whether user input is handled correctly."""
def setUp(self):
self.patcher_stdout = mock.patch('sys.stdout', StringIO())
self.patcher_stdout.start()
# Do testing
def tearDown(self):
self.patcher_stdout.stop()
What I don't like is that context setup is repeated here twice (for now; may be even more with time).
Is there a good way to set up common context for both cases? Can unittest.TestSuite
help me? If yes, how? I couldn't find any example of common context setup.
I've also thought about defining a function setup_common_context
, which would have been called from setUp
of both cases, but it's still repetition.