本文是针对Python单体测试模块使用有兴趣的童鞋。 同时也来自昨天一名PMP的同学的讨论。 感谢小袁童鞋~
unittest.TestCase提供了很多assert方法来帮助我们做测试。 这针对属性、变量、返回值等内容非常有效。
但是针对print()返回的控制台输出就没有那么简单了。 这里列举了三种测试控制台输出的方法。
- 使用装饰器
@patch
- 使用
with
语句 - 使用
with
语句,同时使用assert_has_calls
( [assert_has_calls]文档 )
编码原则是能用系统库就用系统库,减少学习成本。 python.unittest的官方文档请参考如下链接:Python官方文档
from unittest import mock
from unittest.mock import patch
import io
def foo():
print("田豆芽~あいうえお~hello")
# 方法1, 只用装饰器 @patch
@patch('sys.stdout', new_callable=io.StringIO)
def test_foo_one(mock_stdout):
foo()
assert mock_stdout.getvalue() == '田豆芽~あいうえお~hello\n'
# 方法2, 使用with语句
def test_foo_two():
with mock.patch('sys.stdout', new=io.StringIO()) as fake_stdout:
foo()
assert fake_stdout.getvalue() == '田豆芽~あいうえお~hello\n'
# 方法3, 使用with语句和assert_has_calls
def test_foo_three():
with mock.patch('sys.stdout') as fake_stdout:
foo()
fake_stdout.assert_has_calls([
mock.call.write('田豆芽~あいうえお~hello'),
mock.call.write('\n')
])
运行结果