Pytest 安裝踩坑總結

pytest 是 python 測試工具之一。LeetCode 部署 pytest 用來單元測試。詳細說明見官網文檔(http://www.pytest.org/en/latest/)。

今天安裝這個測試工具踩坑不少,簡單總結一下。

安裝pytest

1.安裝方法

sudo pip install -U pytest
# 如果沒有安裝 pip,首先需要安裝 wget brew pip 等工具

2.查看安裝的版本

pytest --version
# 如果顯示版本號,就說明安裝正確

3.注意事項

安裝過程中,界面報錯

pip “Cannot uninstall ‘six’. It is a distutils installed project…”

sudo pip install pytest -U

# 安裝,報錯
Cannot uninstall 'six'. It is a distutils installed project and 
thus we cannot accurately determine which files belong to it 
which would lead to only a partial uninstall.

# 首先更新這個第三方工具
sudo pip install six --upgrade --ignore-installed six

# 繼續安裝,報錯
Cannot uninstall 'pyparsing'. It is a distutils installed project
and thus we cannot accurately determine which files belong to it
which would lead to only a partial uninstall.

# 需要手動更新到最新版
sudo pip install -I pyparsing==2.2.0

# 繼續安裝,成功

測試實例

# 將代碼保存,命名爲test_sample.py
def func(x):
    return x +1

def test_answer():
    assert func(3)==5

在當前目錄下執行 pytes t或者 pytest -q(q是quiet的簡拼),會尋找當前目錄及其子目錄下以test開頭的py文件或者以test結尾的py文件,找到文件後,在文件中找到以test開頭函數並執行。

測試結果爲F,並在FALURES中輸出部分詳細的錯誤原因,實際是 assert func(3)==5出現問題了,錯誤的原因是 4 = func(3)而我們的斷言是 func(3)=5

F                                                                                                                                  [100%]
=================================================================
FAILURES
==================================================================
________________________________________________________________
test_answer
_______________________________________________________________


    def test_answer():
>       assert inc(3) == 5
E       assert 4 == 5
E        +  where 4 = inc(3)

當我們把結果改成正確的 4

1 passed in 0.03 seconds

實例二(多個測試樣例)

多個測試樣例,可以將其放到一個測試類中:

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

編寫pytest測試樣例的規則

  • 測試文件以test_開頭(以_test結尾也可以)
  • 測試類以Test開頭,並且不能帶有 init 方法
  • 測試函數以test_開頭
  • 斷言使用基本的assert即可

參考鏈接:https://www.cnblogs.com/shenh/p/11572657.html

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