天天看點

Python單元測試架構:Pytest簡介

Pytest簡介

  • 入門簡單,文檔豐富
  • 支援單元測試、功能測試
  • 支援參數化
  • 重複執行,部分執行,測試跳過
  • 相容其他測試架構(nose,unittest等)
  • 支援生成html報告
  • 可內建CI環境(Jenkins 等)

2、Pytest安裝

import pytest
    class Test_class:
        def test_001(self):
            print('用例001')
            assert 8 == 8
        def test_002(self):
            print('用例002')
            assert 6 == 6
        def test_003(self):
            print('用例003')
            assert 3 == 2
    if __name__ == "__main__":
    # 裡面參數需要傳list,多個參數放list就不會有警告了
# pytest.main('-q test_class.py')
        pytest.main(['-q', 'test_class.py'])
           

3、建立一個簡單的test案例

import pytest
    class Test_class:
        def test_001(self):
            print('用例001')
            assert 8 == 8
        def test_002(self):
            print('用例002')
            assert 6 == 6
        def test_003(self):
            print('用例003')
            assert 3 == 2
    if __name__ == "__main__":
    # 裡面參數需要傳list,多個參數放list就不會有警告了
# pytest.main('-q test_class.py')
        pytest.main(['-q', 'test_class.py'])
           

執行結果

pytest 中用例的檢查點 直接用 Python 的 assert 斷言。

assert 後面的表達式結果 為 True ,就是檢查點通過,結果為False ,就是檢查點不通過。

Python單元測試架構:Pytest簡介

執行測試的時候,我們隻需要在測試檔案test_class所在的目錄下,運作py.test即可。pytest會在目前的目錄下,尋找以test開頭的檔案(即測試檔案),找到測試檔案之後,進入到測試檔案中尋找test_開頭的測試函數并執行。

4、Pycharm設定Pytest

#file->Setting->Tools->Python Integrated Tools->項目名稱->Default test runner->選擇py.test
#右鍵選擇pytest運作或者直接運作.py檔案
           

執行結果

Python單元測試架構:Pytest簡介
Python單元測試架構:Pytest簡介

由上可見:Pytest是可以相容UnitTest腳本的,之前寫的UnitTest用例也能用Pytest架構去運作。

5、Pytest自動生成報告

    # 需預先裝上pytest-html
    >>>pip install pytest_html

    # 生成html格式的報告
    >>>pytest -v test_1.py --html=Path

    # 生成xml格式的報告
    >>>pytest -v test_1.py --junitxml=Path

    # 生成txt格式的報告
    >>>pytest -v test_1.py --resultlog=Path
           

注意:檢查運作指令時,路徑(根目錄)是否正确

參考位址:

https://docs.pytest.org/en/latest/warnings.html
           
Python單元測試架構:Pytest簡介
Python單元測試架構:Pytest簡介
生成報告    
    .test_class.py::Test_class::test_001
    .test_class.py::Test_class::test_002
    F
    test_class.py::Test_class::test_003
    self = < test_class.Test_class object at 0x000001582B868978 >
    def test_003(self):
        print('用例003')
    > assert 3 == 2
    E
    assert 3 == 2
    E + 3
    E - 2
    test_class.py: 24: AssertionError
           

PS:如有需要Python學習資料的小夥伴可以加下方的群去找免費管理者領取

Python單元測試架構:Pytest簡介

可以免費領取源碼、項目實戰視訊、PDF檔案等

Python單元測試架構:Pytest簡介

本文的文字及圖檔來源于網絡,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。

作者:顧小魚