이 스레드의 모든 멋진 답변을 바탕으로 이것이 제가 해결 한 방법입니다. 가능한 한 재고로 유지하고 싶었습니다. 내가 사용하는 단위 테스트 메커니즘 증강 setUp()
캡처를 sys.stdout
하고 sys.stderr
, 새로운 어설 션 API를 예상 값과 캡처 된 값을 확인하고 복원하기 위해 추가 sys.stdout
및 sys.stderr
시 tearDown(). I did this to keep a similar unit test API as the built-in
유닛 테스트 API while still being able to unit test values printed to
sys.stdout or
sys.stderr`.
import io
import sys
import unittest
class TestStdout(unittest.TestCase):
# before each test, capture the sys.stdout and sys.stderr
def setUp(self):
self.test_out = io.StringIO()
self.test_err = io.StringIO()
self.original_output = sys.stdout
self.original_err = sys.stderr
sys.stdout = self.test_out
sys.stderr = self.test_err
# restore sys.stdout and sys.stderr after each test
def tearDown(self):
sys.stdout = self.original_output
sys.stderr = self.original_err
# assert that sys.stdout would be equal to expected value
def assertStdoutEquals(self, value):
self.assertEqual(self.test_out.getvalue().strip(), value)
# assert that sys.stdout would not be equal to expected value
def assertStdoutNotEquals(self, value):
self.assertNotEqual(self.test_out.getvalue().strip(), value)
# assert that sys.stderr would be equal to expected value
def assertStderrEquals(self, value):
self.assertEqual(self.test_err.getvalue().strip(), value)
# assert that sys.stderr would not be equal to expected value
def assertStderrNotEquals(self, value):
self.assertNotEqual(self.test_err.getvalue().strip(), value)
# example of unit test that can capture the printed output
def test_print_good(self):
print("------")
# use assertStdoutEquals(value) to test if your
# printed value matches your expected `value`
self.assertStdoutEquals("------")
# fails the test, expected different from actual!
def test_print_bad(self):
print("@=@=")
self.assertStdoutEquals("@-@-")
if __name__ == '__main__':
unittest.main()
단위 테스트가 실행되면 출력은 다음과 같습니다.
$ python3 -m unittest -v tests/print_test.py
test_print_bad (tests.print_test.TestStdout) ... FAIL
test_print_good (tests.print_test.TestStdout) ... ok
======================================================================
FAIL: test_print_bad (tests.print_test.TestStdout)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tests/print_test.py", line 51, in test_print_bad
self.assertStdoutEquals("@-@-")
File "/tests/print_test.py", line 24, in assertStdoutEquals
self.assertEqual(self.test_out.getvalue().strip(), value)
AssertionError: '@=@=' != '@-@-'
- @=@=
+ @-@-
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
with mock.patch('sys.stdout', new_callable=StringIO.StringIO):
pypi.python.org/pypi/mock