如何在Python 3.5 unittest中测试打印值?
我想测试check_board_state函数中的打印值,但这些测试有问题。当我尝试使用 python-m unittests.py 我有个错误: AttributeError:“\u io.TextIOWrapper”对象没有属性“getvalue”如何在Python 3.5 unittest中测试打印值?,python,pydev,python-unittest,Python,Pydev,Python Unittest,我想测试check_board_state函数中的打印值,但这些测试有问题。当我尝试使用 python-m unittests.py 我有个错误: AttributeError:“\u io.TextIOWrapper”对象没有属性“getvalue” 当我使用PythonUnitTest而不是PythonRun时,测试在Eclipse中的PyDev中运行良好。如何解决此问题?解释您的答案。执行得很干净,但您对测试函数的返回值进行了假设。如果你纠正了这一点,我会投赞成票。解释你的答案。执行得很好
当我使用PythonUnitTest而不是PythonRun时,测试在Eclipse中的PyDev中运行良好。如何解决此问题?解释您的答案。执行得很干净,但您对测试函数的返回值进行了假设。如果你纠正了这一点,我会投赞成票。解释你的答案。执行得很好,但是你对被测试函数的返回值做了假设。如果你纠正了这一点,我将投赞成票。你可以更改check_board_state,使其返回结果,而不是将其打印到stdout,或者添加一个默认为sys.stdout的参数,您可以通过测试,就像python3中的函数一样,您需要将
stdout
重定向到可以测试的缓冲区。还可以使用unittest.TestCase
附带的assert
方法,它们更丰富,可读性更强。您可以更改check\u board\u状态,使其返回结果,而不是打印到stdout,或者添加一个默认为sys.stdout的参数,您可以通过测试,有点像python3中的函数,您需要将stdout
重定向到一个可以测试的缓冲区。还可以使用unittest.TestCase
附带的assert
方法,它们更丰富、更可读。
from checker.checker import check_board_state, check_row, check_winner,\
check_column, check_diagonal
import sys
import unittest
class TestChecker(unittest.TestCase):
def test_winner_row(self):
check_board_state([['o', 'x', '.'],
['o', 'o', 'o'],
['.', 'x', 'o']])
output = sys.stdout.getvalue().strip()
assert output == 'o'
def test_draw(self):
check_board_state([['.', 'x', '.', 'o', 'o'],
['o', 'o', 'x', '.', '.'],
['.', 'o', 'x', '.', '.'],
['.', 'o', 'x', '.', '.'],
['.', 'o', 'x', '.', '.']])
output = sys.stdout.getvalue().strip()
assert output == '.'
if __name__ == '__main__':
unittest.main()
from checker import checker
from io import StringIO
import sys
import unittest
class TestChecker(unittest.TestCase):
def setUp(self):
# every test instance the class(setUp)
self.cls = checker()
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
super(TestChecker, self).setUp()
def test_winner_row(self):
# the modules should give a return
self.cls.check_board_state([['o', 'x', '.'],
['o', 'o', 'o'],
['.', 'x', 'o']])
result = sys.stdout.getvalue().strip()
excepted = "o"
# use unittests assertion methods
self.assertEqual(excepted, result)
def test_draw(self):
self.cls.check_board_state([['.', 'x', '.', 'o', 'o'],
['o', 'o', 'x', '.', '.'],
['.', 'o', 'x', '.', '.'],
['.', 'o', 'x', '.', '.'],
['.', 'o', 'x', '.', '.']])
result = sys.stdout.getvalue().strip()
excepted = "."
self.assertEqual(excepted, result)
def tearDown(self):
sys.stdout = old_stdout
super(TestChecker, self).tearDown()
if __name__ == '__main__':
unittest.main()