在 Linux 下,Python 的單元測試通常使用 unittest
模塊或者第三方庫如 pytest
unittest
模塊進行單元測試:首先,確保你已經安裝了 Python。然后,創建一個名為 test_example.py
的文件,其中包含你的測試用例。例如:
import unittest
def add(a, b):
return a + b
class TestExample(unittest.TestCase):
def test_addition(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main()
在這個例子中,我們定義了一個簡單的 add
函數,并編寫了一個測試類 TestExample
,其中包含一個測試方法 test_addition
。這個方法使用 assertEqual
來檢查 add
函數的輸出是否與預期相符。
要運行測試,打開終端,導航到包含 test_example.py
的目錄,然后輸入以下命令:
python test_example.py
如果所有測試都通過,你將看到類似以下的輸出:
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
pytest
進行單元測試:首先,確保你已經安裝了 pytest
。如果沒有,可以使用以下命令安裝:
pip install pytest
接下來,將你的測試文件重命名為 test_example.py
(或者任何你喜歡的名稱),并確保它位于一個合適的目錄中。
現在,你可以使用以下命令運行測試:
pytest test_example.py
如果所有測試都通過,你將看到類似以下的輸出:
=========================== test session starts ============================
collected 4 items
test_example.py . [100%]
============================ 4 passed in 0.03s =============================
這就是在 Linux 下使用 Python 進行單元測試的基本方法。你可以根據自己的需求編寫更多的測試用例,并使用 unittest
或 pytest
運行它們。