python - How to extract stdout redirection in unittest code to make it safe reusable by other test cases? -
i want test code includes print statements unfortunately can't rid of. approach capture stdout during tests , perform assertions on captured outputs. wanted extract redirection code make usable many test cases. example simple function this
# something.py def function(): print("something") return 42
would tested this
import io import sys import unittest import # test_something.py class redirecttestcase(unittest.testcase): def setup(self): self.original_stdout = sys.stdout self.temporary_stdout = io.stringio() sys.stdout = self.temporary_stdout def teardown(self): sys.stdout = self.original_stdout def assertoutputequal(self, expected_output): self.temporary_stdout.seek(0) captured_output = self.temporary_stdout.read().strip() self.assertequal(expected_output, captured_output) class testfunction(redirecttestcase): def setup(self): super().setup() def teardown(self): super().teardown() def test_output(self): something.function() self.assertoutputequal("something") def test_return(self): self.assertequal(42, something.function()) if __name__ == "__main__": unittest.main()
i extracted stdout redirection code in base class, don't calling base classes setup
, teardown
methods in each test case implementation. there better way make approach accessible multiple test cases? especially, possible automatically call base classes setup , teardown make tests cleaner , safer? other suggestions improving testing approach highly appreciated!
i found blog post ned betchelder covering similar issue using mixin class. used approach restructure tests. divides code independent pieces , super()
calls avoided in actual test cases.
class basetestcase(unittest.testcase): """base test case.""" def setup(self): super().setup() # basic setup stuff here ... def teardown(self): # basic teardown stuff here ... super().teardown() def assertoutputequal(self, expected_output): self.temporary_stdout.seek(0) captured_output = self.temporary_stdout.read().strip() self.assertequal(expected_output, captured_output) class redirectmixin(object): """mixin class redirecting stdout on setup , teardown.""" def setup(self): super().setup() self.original_stdout = sys.stdout self.temporary_stdout = io.stringio() sys.stdout = self.temporary_stdout def teardown(self): sys.stdout = self.original_stdout super().teardown() class testfunction(redirectmixin, basetestcase): """actual test case using stdout redirection.""" def test_output(self): something.function() self.assertoutputequal("something") def test_return(self): self.assertequal(42, something.function())
Comments
Post a Comment