pytest 用例依賴

應用場景:

     1. 創建訂單之前,需要先添加購物車

     2. 在執行訂單接口用例之前,要保證添加購物車接口用例完成,並且是pass

 

應用辦法:

  •     可以使用pytest插件

pytest插件介紹

    1.官方插件地址介紹:https://docs.pytest.org/en/latest/plugins.html,可點擊,查看插件列表,或直接訪問第2步地址

    2. 插件列表網址:https://plugincompat.herokuapp.com 包含很多插件包,大家可依據工作的需求選擇使用。

    3. 在插件列表中找到,dependency名字,該插件管理測試用例依賴關係    

 

 

pytest 插件dependency安裝

1. 點擊上面圖片中pytest-dependency鏈接,進入下個頁面,裏面詳細介紹了該插件以及安裝方法

2. 直接pip進行安裝即可,如果python3,可以使用pip3 install pytest-dependency進行安裝,看到如下內容,表示安裝成功

pytest 插件dependency使用

英文好的可以直接看官方文檔:https://pytest-dependency.readthedocs.io/en/stable/usage.html#basic-usage

1. 單獨運行訂單接口(test_order),代碼如下

import pytest



def test_cart():
    print("添加到購物車")



def test_order():
    print("創建訂單")

2. 我們的目的是要增加依賴

3. 可以使用安裝的插件dependency來實現,代碼如下

@pytest.mark.dependency()
def test_cart():
    print("添加到購物車")

@pytest.mark.dependency(depends=["test_cart"])
def test_order():
    print("創建訂單")

   代碼解釋:

      * 只需要在測試用例增加@pytest.mark.dependency() 標識即可,這裏面要注意,假如是order依賴cart,故在order的用例上,需要增加參數depends,depends對應測試用例的名稱,這裏要注意,如果要執行用例必須按pytest的默認運行規則,即用例前要加上test_,而且順序要注意,要先執行test_cart在執行test_order,如果要先執行test_order,查看依賴時發現test_cart這個用例沒有執行認爲結果不通過,所以就不會執行,結果會顯示skip

4. 來,我們執行一下,看下結果

5. 假如先執行創建訂單,後添加購物車,結果是不是上面我們分析的那樣呢,我們還看一下代碼和結果

代碼:只是調換了用例的順序,執行順序:test_order -> test_cart

@pytest.mark.dependency(depends=["cart"],scope="module")
def test_order():
    print("創建訂單")

@pytest.mark.dependency(name='cart')
def test_cart():
    print("添加到購物車")

結果,會發現test_order是skipped,忽略掉了未執行:

6. 下面我們調回最開始的順序,讓test_cart置爲false,我們來看一下test_order的結果,應該也是skipped

代碼:

@pytest.mark.dependency(name='cart')
def test_cart():
    print("添加到購物車")
    assert False

@pytest.mark.dependency(depends=["cart"])
def test_order():
    print("創建訂單")

結果,一個失敗,一個忽略未執行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章