在上一章中,文末留下了一個坑待填補,疑問是這樣的:html
目前從官方文檔中看到的是mysql
We have to be careful though, because pytest will run that finalizer once it’s been added, even if that fixture raises an exception after adding the finalizer.
一旦添加了終結器,pytest便會執行。git
可是,當我嘗試在setup代碼中進行拋錯,終結器的代碼卻並無執行。
嘗試搜索外網暫時也沒獲得有效的幫助,只能在GitHub上向pytest提了issue了,這裏算是埋下一個坑,待後續解決。github
其實說到底仍是我理解的不對,可能當時本身處在疑問中不免就會陷入進死循環,後來在github上通過別人提點方纔醒悟。
先來看下當時我嘗試演示出上述結果的代碼,也就是:setup代碼中進行拋錯,終結器的代碼卻並無執行。sql
代碼分爲2部分,一個是fixture函數代碼,另外一個則是測試用例。代碼是不能直接copy出來運行的,是我在項目的用例中
進行改造的,在這裏僅僅幫助說明意思。json
# content of conftest.py @pytest.fixture() def init_data_allot_task(request): query_sql = """ SELECT id FROM `sm_purchase_allot` WHERE `status`!=5 """ db = DB() data = db.fetch_one(query_sql) db.close() def demo_finalizer(): print("running finalizer code...") request.addfinalizer(demo_finalizer) return data
# content of testcase ... def test_allot_detail(init_data_allot_task): """ """ payload = { "allotId": init_data_allot_task[0] } r = requests.post(QA_URL + API_URL, json=payload, headers=HEADER) result = r.json() assert result["result"] == "ok" assert result["errmsg"] == "success" assert len(result["row"]["taskListOfPage"]["resultData"]) > 0
最開始我想作的是,在fixture函數中,讓代碼db = DB()
拋出一個mysql鏈接超時的錯誤,
而後就能在控制檯中看到"running finalizer code..."
的輸出。函數
可是我執行後,並無看到預期的輸出,說明setup代碼
拋錯後,addfinalizer代碼
並無執行。post
最後通過github上朋友指點後,發現仍是我本身理解錯了。測試
仍是來看下官方的原文:fetch
We have to be careful though, because pytest will run that finalizer once it’s been added, even if that fixture raises an exception after adding the finalizer.
這句話意思實際上是說,當finalizer
一旦添加成功後,pytest就會去執行它。就算是fixture函數在添加了finalizer
以後
拋出了異常。
按照這樣理解的話,那我在fixture函數中的代碼就有問題了。由於db = DB()
代碼在request.addfinalizer(demo_finalizer)
以前就拋錯了,那麼實際上並無執行到添加終結器的這行代碼,因此終結器都還沒添加成功,又怎麼會去執行呢?
終於我明白過來了,因而調整了代碼順序,把request.addfinalizer(demo_finalizer)
放到前面去,而後再接上fixture的代碼:
# content of conftest.py @pytest.fixture() def init_data_allot_task(request): query_sql = """ SELECT id FROM `sm_purchase_allot` WHERE `status`!=5 """ def demo_finalizer(): print("running finalizer code...") request.addfinalizer(demo_finalizer) print("running setup code...") db = DB() data = db.fetch_one(query_sql) db.close() return data
如此來看,咱們會先看到"running setup code..."
的輸出,而後看到mysql拋錯,
最後仍然能夠看到"running setup code..."
的輸出。
運行代碼驗證一下:
這下就對了。