Iwko Czerniawski
Iwko Czerniawski

Reputation: 83

How to test printed value in Python 3.5 unittest?

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

I want to test printed value in check_board_state function but I have problem with these tests. When I try to run them using

python -m unittest tests.py

i've got error:

AttributeError: '_io.TextIOWrapper' object has no attribute 'getvalue'

Tests works fine in PyDev in Eclipse when I use Python unittest instead of Python run. How Can I resolve this problem?

Upvotes: 0

Views: 1014

Answers (1)

Ari Gold
Ari Gold

Reputation: 1548

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

Upvotes: 2

Related Questions