2016-03-03 35 views
0

我有一個裝飾器,它包裝從鼻子測試用例中產生的發生器。對於每一次迭代,如果發生異常,我希望捕獲並運行特定的拆卸,但它看起來並不像預期的那樣。在裝飾器中捕捉髮生器的異常

def print_log(test_case): 
    @wraps(test_case) 
    def run_test(self): 
     try: 
      for _ in test_case(self): pass 
     except: 
      Test_Loop.failure_teardown(self) 
      raise 
    return run_test 

有什麼我做錯了嗎?

回答

0

我不確定究竟是什麼意外的行爲,但也許這是因爲你沒有單獨嘗試每個循環迭代。

也許這會工作嗎?

def print_log(test_case): 
    @wraps(test_case) 
    def run_test(self): 
     from six.moves import next 
     test_iter = iter(test_case(self)) 
     while True: 
      try: 
       next(test_iter) 
      except StopIteration: 
       break 
      except Exception: 
       Test_Loop.failure_teardown(self) 
       raise 
    return run_test 
+0

意外的行爲是它甚至沒有達到預期的區塊。爲了測試,我強制在yield函數中的某處發生異常,並且它被喚起,但它只是繼續進行常規拆卸,而不是我寫的特定拆解。 – ILostMySpoon