2017-05-04 55 views
0

我想爲一組測試編寫自定義記錄器,而不對測試做任何重大更改。我想使用像夾具這樣的東西,我可以傳遞給測試方法,並且在測試捕獲stdout和stderr並將其更改爲定製消息的整個持續時間期間,夾具在後臺運行。如何才能做到這一點 ?如何使用在後臺運行的燈具在python中捕獲stdout和stderr

def test_1(): 
    blah 
    blah 
    print('Some msg') 
    blah 
    assert something, assert_msg 

Output: 
Some msg (if assert fails, then assertion error too) 

我要的是

@fixture 
def logger(): 
    capture stdout, stderr 
    custom_msg = cust_msg(stdout, stderr) 
    print(custom_msg) 


def test_1(logger): 
    blah 
    blah 
    print('Some msg') 
    blah 
    assert something, assert_msg 

Output: 
Custom msg (if assert fails, then custom assertion error too) 

回答

0

你不能從模塊中捕捉到標準輸出,而不重新定義要麼sys.stdoutprint。重新定義打印更容易,因爲它已經是一個功能。並且爲了趕上失敗的assert s,就趕上AssertionError s。

import functools 
import sys 

def fixture(f): 
    old_print = print 
    @functools.wraps(f) 
    def wrapped(*args, **kwargs): 
     global print 
     def print(*value, sep=' ', end='\n', file=sys.stdout, flush=False): 
      msg = sep.join(map(str, value)) + end 

      # Manipulate msg here 

      file.write(manipulated) 
      if flush: 
       file.flush() 
     try: 
      return f(*args, **kwargs) 
     except AssertionError as e: 

      # Custom message on failed assertion 
      msg = e.args[0] if len(e.args) == 1 else None 
      old_print(manipulated) 

     finally: 
      print = old_print 
    return wrapped 

但是,assert並沒有提供太多有用的信息。我會使用一個實際的測試庫,如unittest

另一種方法是將其作爲子過程運行。

相關問題