pytest簡介



pytest是python的一種單元測試框架,與python自帶的unittest測試框架類似,但是比unittest框架使用起來更簡潔,效率更高。根據pytest的官方網站介紹,它具有如下特點:

  • 非常容易上手,入門簡單,文檔豐富,文檔中有很多實例可以參考
  • 能夠支持簡單的單元測試和復雜的功能測試
  • 支持參數化
  • 執行測試過程中可以將某些測試跳過(skip),或者對某些預期失敗的case標記成失敗
  • 支持重復執行(rerun)失敗的case
  • 支持運行由nose, unittest編寫的測試case
  • 可生成html報告
  • 方便的和持續集成工具jenkins集成
  • 可支持執行部分用例
  • 具有很多第三方插件,並且可以自定義擴展

安裝pytest

 

1.安裝方法

 

pip install -U pytest

 

2.pip show pytest查看安裝版本

 

pip show pytest

 

 

3.也可以pytest --version查看安裝的版本

 

pytest --version

This is pytest version 3.6.3, imported from d:\soft\python3.6\lib\site-packages\ pytest.py 

 

快速開始

 

1.新建一個test_sample.py文件,寫以下代碼

# content of test_sample.py def func(x): return x +1 def test_answer(): assert func(3)==5 

 

2.打開test_sample.py所在的文件夾,cmd窗口輸入:pytest(或者輸入py.test也可以)

 

D:\YOYO>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO, inifile:
collected 1 item

test_sample.py F [100%] ================================== FAILURES =================================== _________________________________ test_answer _________________________________  def test_answer(): > assert func(3)==5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:6: AssertionError ========================== 1 failed in 0.19 seconds =========================== 

3.pytest運行規則:查找當前目錄及其子目錄下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test開頭函數並執行。

寫個測試類

1.前面是寫的一個test開頭的測試函數,當用例用多個的時候,寫函數就不太合適了。這時可以把多個測試用例,寫到一個測試類里。

# test_class.py class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') 

2.pytest會找到符合規則(test_.py和_test.py)所有測試,因此它發現兩個test_前綴功能。 如果只想運行其中一個,可以指定傳遞文件名test_class.py來運行模塊:
備注: -q, --quiet decrease verbosity( 顯示簡單結果)

py.test -q test_class.py

D:\YOYO>py.test -q test_class.py .F [100%] ================================== FAILURES =================================== _____________________________ TestClass.test_two ______________________________ self = <test_class.TestClass object at 0x00000000039F1828> def test_two(self): x = "hello" > assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check') test_class.py:11: AssertionError 1 failed, 1 passed in 0.04 seconds 

第一次測試通過,第二次測試失敗。 您可以在斷言中輕松查看失敗的原因。

pytest用例規則

  • 文件名以test_*.py文件和*_test.py
  • 以test_開頭的函數
  • 以Test開頭的類,test_開頭的方法,並且不能帶有__init__ 方法
  • 所有的包pakege必須要有__init__.py文件
  • 斷言使用assert


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM