LoginSignup
3
1

More than 3 years have passed since last update.

Pytestで標準出力をテストする

Posted at

業務でPythonを使うことになり、標準出力をテストしたかったのでメモとして

準備

  • Python 3系
  • pytest
pip install pytest

テスト対象コード

下記プログラムをテストしたいと思います。
sayメソッドで標準出力へ出すだけです。

hogehoge.py
class HogeHoge:
  def __init__(self, name):
    self.name = name

  def say(self):
    print("Hello ! My name is " + self.name + ".")

テストコード

pytestにある fixture、capfdを使う

test_hogehoge.py
from hogehoge import HogeHoge

def test_say(capfd):
  instance = HogeHoge("Taro")
  instance.say()

  out, err = capfd.readouterr()
  assert out == "Hello ! My name is Taro.\n"
  assert err is ''
[Sun Nov 24 17:58:49 2019] Running: c:\python\python.exe -m pytest
============================== test session starts =============================== 
platform win32 -- Python 3.7.2, pytest-5.3.0, py-1.8.0, pluggy-0.13.1
rootdir: D:\Document\repository\study_pytest
collected 1 item

test\test_hogehoge.py .                                                     [100%] 

=============================== 1 passed in 0.08s ================================ 

まとめ

標準出力のテストには、capfdを使おう。標準エラーも取得できます。

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1