單元測試框架 - Py.test 模組



2004年,Holger Krekel 將他的std包(其名稱經常與 Python 附帶的標準庫混淆)重新命名為(略微不那麼令人困惑的)名稱“py”。儘管該包包含多個子包,但現在幾乎完全以其py.test框架而聞名。

py.test 框架為 Python 測試建立了新的標準,並且如今已成為許多開發人員的熱門選擇。它引入的優雅且符合 Python 風格的測試編寫習慣用法使得測試套件能夠以更緊湊的風格編寫。

py.test 是 Python 標準 unittest 模組的無樣板替代方案。儘管它是一個功能齊全且可擴充套件的測試工具,但它擁有簡單的語法。建立測試套件就像編寫一個包含幾個函式的模組一樣簡單。

py.test 可以在所有 POSIX 作業系統和 WINDOWS(XP/7/8)上執行,並支援 Python 2.6 及更高版本。

安裝

使用以下程式碼將 pytest 模組載入到當前 Python 發行版以及 py.test.exe 實用程式中。可以使用兩者執行測試。

pip install pytest

用法

您可以簡單地使用 assert 語句來斷言測試期望。pytest 的 assert 內省將智慧地報告 assert 表示式的中間值,使您無需學習JUnit 遺留方法的眾多名稱。

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

使用以下命令列執行上述測試。測試執行完成後,控制檯將顯示以下結果:

C:\Python27>scripts\py.test -v test_sample.py
============================= test session starts =====================
platform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\Pyth
on27\python.exe
cachedir: .cache
rootdir: C:\Python27, inifile:
collected 1 items
test_sample.py::test_answer FAILED
================================== FAILURES =====================
_________________________________ test_answer _________________________________
   def test_answer():
>  assert func(3) == 5
E     assert 4 == 5
E     + where 4 = func(3)
test_sample.py:7: AssertionError
========================== 1 failed in 0.05 seconds ====================

也可以透過使用 –m 開關包含 pytest 模組,從命令列執行測試。

python -m pytest test_sample.py

在類中分組多個測試

當您開始擁有多個測試時,通常將測試在邏輯上分組到類和模組中是有意義的。讓我們編寫一個包含兩個測試的類:

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

將顯示以下測試結果:

C:\Python27>scripts\py.test -v test_class.py
============================= test session starts =====================
platform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\Pyt
on27\python.exe
cachedir: .cache
rootdir: C:\Python27, inifile:
collected 2 items
test_class.py::TestClass::test_one PASSED
test_class.py::TestClass::test_two FAILED
================================== FAILURES =====================
_____________________________ TestClass.test_two ______________________________
self = <test_class.TestClass instance at 0x01309DA0>

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

test_class.py:7: AssertionError
===================== 1 failed, 1 passed in 0.06 seconds ======================
廣告

© . All rights reserved.