1. 程式人生 > >Python實踐1-Tenacity提高自動測試健壯性

Python實踐1-Tenacity提高自動測試健壯性

在自動化測試工具和自動化測試用例開發過程中,經常需要處理一些待操作物件不穩定的情況,例如,某些介面元素不能及時出現,某些服務暫時不可用。這個時候,測試程式碼必須想方設法應對這種情況,以便提高工具和用例的健壯性,最常見的解決方法就是進行重試:當特定條件不滿足的時候,等待一段時間,然後再次嘗試,直到期望的條件滿足繼續執行,或者重試到達一定數目丟擲異常退出。

下面是一種常用的重試程式碼樣板.

def do_something_unreliable(retry=10): for i in range(retry): try: if random.randint(0, 10) > 1: raise IOError("Unstable status, try again") else: print("Get stable result") return except Exception as e: print(e.message) 

 

其實,已經有高人開發了一個名叫Tenacity的Python庫,幫我們優雅地搞定這些需要重試的情況了,使用起來非常簡單。

我們可以用pip install tenacity來安裝這個庫,然後用@retry裝飾器來重構上面的程式碼。

from tenacity import retry
@retry def do_something_unreliable(): if random.randint(0, 10) > 1: raise IOError("Unstable status, try again") else: print("Get stable result") 

 

上面的例子,實現了遇到異常就重試,如果想要限制重試次數,只需要修改@retry裝飾器那一行即可。

from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))

 

如果想要每5秒鐘重試一次

from tenacity import retry, wait_fixed
@retry(wait=wait_fixed(5))