Python: Write unittest for console print

后端 未结 4 2217
无人及你
无人及你 2020-12-02 11:03

Function foo prints to console. I want to test the console print. How can I achieve this in python?

Need to test this function, has NO return statement

4条回答
  •  感动是毒
    2020-12-02 11:45

    If you happen to use pytest, it has builtin output capturing. Example (pytest-style tests):

    def eggs():
        print('eggs')
    
    
    def test_spam(capsys):
        eggs()
        captured = capsys.readouterr()
        assert captured.out == 'eggs\n'
    

    You can also use it with unittest test classes, although you need to passthrough the fixture object into the test class, for example via an autouse fixture:

    import unittest
    import pytest
    
    
    class TestSpam(unittest.TestCase):
    
        @pytest.fixture(autouse=True)
        def _pass_fixtures(self, capsys):
            self.capsys = capsys
    
        def test_eggs(self):
            eggs()
            captured = self.capsys.readouterr()
            self.assertEqual('eggs\n', captured.out)
    

    Check out Accessing captured output from a test function for more info.

提交回复
热议问题