2011-01-12 180 views
29

我想在測試函數中放一些日誌語句來檢查一些狀態變量。在py.test測試中記錄

我有下面的代碼片斷:

import pytest,os 
import logging 

logging.basicConfig(level=logging.DEBUG) 
mylogger = logging.getLogger() 

############################################################################# 

def setup_module(module): 
    ''' Setup for the entire module ''' 
    mylogger.info('Inside Setup') 
    # Do the actual setup stuff here 
    pass 

def setup_function(func): 
    ''' Setup for test functions ''' 
    if func == test_one: 
     mylogger.info(' Hurray !!') 

def test_one(): 
    ''' Test One ''' 
    mylogger.info('Inside Test 1') 
    #assert 0 == 1 
    pass 

def test_two(): 
    ''' Test Two ''' 
    mylogger.info('Inside Test 2') 
    pass 

if __name__ == '__main__': 
    mylogger.info(' About to start the tests ') 

    pytest.main(args=[os.path.abspath(__file__)]) 

    mylogger.info(' Done executing the tests ') 

我得到以下輸出:只有來自'__name__ == __main__'塊的日誌消息得到發送到控制檯

[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py 
INFO:root: About to start the tests 
======================================================== test session starts ========================================================= 
platform darwin -- Python 2.6.2 -- pytest-2.0.0 
collected 2 items 

minitest.py .. 

====================================================== 2 passed in 0.01 seconds ====================================================== 
INFO:root: Done executing the tests 

的通知。

有沒有辦法強制pytest從測試方法向控制檯發出日誌記錄呢?

+2

你可能會看看[這個答案](http://stackoverflow.com/a/11877951/148680),由py.test的創建者張貼。他提出了一個pytest插件,它提供了高度的多功能性。 – chb

回答

17

工作對我來說,這裏的輸出我得到:[剪斷 - >例子是不正確]

編輯:看來,你必須通過-s選項py.test所以它不會捕獲標準輸出。這裏(py.test沒有安裝),它足夠使用python pytest.py -s pyt.py

爲您的代碼,你需要的是通過-sargsmain

pytest.main(args=['-s', os.path.abspath(__file__)]) 

參見capturing output的py.test文檔。

+0

對不起。我匆忙地粘貼了代碼。請從'test_one'函數中刪除'assert 0 == 1'以注意'問題'。只有當有一些失敗時(我強制錯誤斷言),py.test似乎打印日誌信息。 – superselector

+0

沒問題,我發現如何修復命令行,尋找一個編程方式。 – TryPyPy

+1

您也可以將日誌輸出重定向到某個文件而不是默認的隱式stderr。 – hpk42