Writing a pytest function for checking the output on console (stdout)

后端 未结 2 1432
南方客
南方客 2020-12-29 22:57

This link gives a description how to use pytest for capturing console outputs. I tried on this following simple code, but I get error

import sys
import pytest         


        
2条回答
  •  一整个雨季
    2020-12-29 23:39

    Use the capfd fixture.

    Example:

    def test_foo(capfd):
        foo()  # Writes "Hello World!" to stdout
        out, err = capfd.readouterr()
        assert out == "Hello World!"
    

    See: http://pytest.org/en/latest/fixture.html for more details

    And see: py.test --fixtures for a list of builtin fixtures.

    Your example has a few problems. Here is a corrected version:

    def f(name):
        print "hello {}".format(name)
    
    
    def test_f(capfd):
        f("Tom")
    
        out, err = capfd.readouterr()
        assert out == "hello Tom\n"
    

    Note:

    • Do not use sys.stdout -- Use the capfd fixture as-is as provided by pytest.
    • Run the test with: py.test foo.py

    Test Run Output:

    $ py.test foo.py
    ====================================================================== test session starts ======================================================================
    platform linux2 -- Python 2.7.5 -- pytest-2.4.2
    plugins: flakes, cache, pep8, cov
    collected 1 items 
    
    foo.py .
    
    =================================================================== 1 passed in 0.01 seconds ====================================================================
    

    Also Note:

    • You do not need to run your Test Function(s) in your test modules. py.test (The CLI tool and Test Runner) does this for you.

    py.test does mainly three things:

    1. Collect your tests
    2. Run your tests
    3. Display statistics and possibly errors

    By default py.test looks for (configurable iirc) test_foo.py test modules and test_foo() test functions in your test modules.

提交回复
热议问题