Mock Python's built in print function

前端 未结 11 1971
醉话见心
醉话见心 2020-12-06 09:10

I\'ve tried

from mock import Mock
import __builtin__

__builtin__.print = Mock()

But that raises a syntax error. I\'ve also tried patching

11条回答
  •  隐瞒了意图╮
    2020-12-06 09:48

    This Python 3 example builds upon the Python 2 answer by Krzysztof. It uses unittest.mock. It uses a reusable helper method for making the assertion.

    import io
    import unittest
    import unittest.mock
    
    from .solution import fizzbuzz
    
    
    class TestFizzBuzz(unittest.TestCase):
    
        @unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
        def assert_stdout(self, n, expected_output, mock_stdout):
            fizzbuzz(n)
            self.assertEqual(mock_stdout.getvalue(), expected_output)
    
        def test_only_numbers(self):
            self.assert_stdout(2, '1\n2\n')
    

提交回复
热议问题