How to assert output with nosetest/unittest in python?

后端 未结 12 1486
野趣味
野趣味 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:44

    If you really want to do this, you can reassign sys.stdout for the duration of the test.

    def test_foo():
        import sys
        from foomodule import foo
        from StringIO import StringIO
    
        saved_stdout = sys.stdout
        try:
            out = StringIO()
            sys.stdout = out
            foo()
            output = out.getvalue().strip()
            assert output == 'hello world!'
        finally:
            sys.stdout = saved_stdout
    

    If I were writing this code, however, I would prefer to pass an optional out parameter to the foo function.

    def foo(out=sys.stdout):
        out.write("hello, world!")
    

    Then the test is much simpler:

    def test_foo():
        from foomodule import foo
        from StringIO import StringIO
    
        out = StringIO()
        foo(out=out)
        output = out.getvalue().strip()
        assert output == 'hello world!'
    

提交回复
热议问题