Pythonで標準出力の単体テストを行う
上書きしている間は、標準出力に文字列を書き出してもコンソールには表示されない
code:modified_stdout.py
import sys
from io import StringIO
# 標準出力をキャプチャできるような状態にする
io = StringIO()
sys.stdout = io
# キャプチャできているかを試す
print("printする")
text = io.getvalue()
# 標準出力の状態を戻し、コンソールに書き出されるような状態に戻す
sys.stdout = sys.__stdout__
# 取得した文字列を確認してみる
if text == "printする\n":
print("取得できた")
else:
print("取得できなかった")
もう少し使いやすくする
code:stdout_capture.py
import sys
from io import StringIO
from typing import Any
class StdOutCapture:
def __enter__(self) -> StringIO:
io = StringIO()
sys.stdout = io
return io
def __exit__(self, *args: Any) -> None:
sys.stdout = sys.__stdout__
これを使って単体テストをしてみる
code:py
from unittest import TestCase
from .stdout_capture import StdOutCapture
class TestUtil(TestCase):
def test_print_with_timestamp(self) -> None:
with StdOutCapture() as io:
# with文の中だけ標準出力をキャプチャできる
print("printする")
# 忘れずにキャプチャした文字列を取得しておく
stdout = io.getvalue()
# 標準出力が意図したものになっているかをテストする
assert stdout == "printする\n", f"stdout must be \"printする\" but \"{stdout}\""
参考