I decided to use Python for business and wanted to test the standard output, so as a memo
--Python 3 series
pip install pytest
I would like to test the program below.
Just use the say
method to output to standard output.
hogehoge.py
class HogeHoge:
def __init__(self, name):
self.name = name
def say(self):
print("Hello ! My name is " + self.name + ".")
Use fixture, capfd in pytest
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 ================================
Use capfd
to test standard output. You can also get standard errors.
Recommended Posts