How to assert output with nosetest/unittest in python?

后端 未结 12 1427
野趣味
野趣味 2020-11-28 02:56

I\'m writing tests for a function like next one:

def foo():
    print \'hello world!\'

So when I want to test this function the code will b

12条回答
  •  自闭症患者
    2020-11-28 03:30

    In python 3.5 you can use contextlib.redirect_stdout() and StringIO(). Here's the modification to your code

    import contextlib
    from io import StringIO
    from foomodule import foo
    
    def test_foo():
        temp_stdout = StringIO()
        with contextlib.redirect_stdout(temp_stdout):
            foo()
        output = temp_stdout.getvalue().strip()
        assert output == 'hello world!'
    

提交回复
热议问题