如何在Python 3.5 unittest中测试打印值?

时间:2016-10-14 14:43:44

标签: python pydev python-unittest

"\n"

我想在check_board_state函数中测试打印值,但我对这些测试有疑问。当我尝试使用

运行它们时
  

python -m unittest tests.py

我有错误:

  

AttributeError:' _io.TextIOWrapper'对象没有属性' getvalue'

当我使用Python unittest而不是Python运行时,测试在Eclipse中的PyDev中运行良好。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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()