How to print to console in pytest?

后端 未结 6 1580
盖世英雄少女心
盖世英雄少女心 2020-12-12 12:13

I\'m trying to use TDD (test-driven development) with pytest. pytest will not print to the console when I use print.

6条回答
  •  再見小時候
    2020-12-12 12:44

    I needed to print important warning about skipped tests exactly when PyTest muted literally everything.

    I didn't want to fail a test to send a signal, so I did a hack as follow:

    def test_2_YellAboutBrokenAndMutedTests():
        import atexit
        def report():
            print C_patch.tidy_text("""
    In silent mode PyTest breaks low level stream structure I work with, so
    I cannot test if my functionality work fine. I skipped corresponding tests.
    Run `py.test -s` to make sure everything is tested.""")
        if sys.stdout != sys.__stdout__:
            atexit.register(report)
    

    The atexit module allows me to print stuff after PyTest released the output streams. The output looks as follow:

    ============================= test session starts ==============================
    platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
    rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile: 
    collected 15 items 
    
    test_C_patch.py .....ssss....s.
    
    ===================== 10 passed, 5 skipped in 0.15 seconds =====================
    In silent mode PyTest breaks low level stream structure I work with, so
    I cannot test if my functionality work fine. I skipped corresponding tests.
    Run `py.test -s` to make sure everything is tested.
    ~/.../sources/C_patch$
    

    Message is printed even when PyTest is in silent mode, and is not printed if you run stuff with py.test -s, so everything is tested nicely already.

提交回复
热议问题