在Debian上進行Python測試可按以下步驟操作:
安裝Python及工具
sudo apt update
sudo apt install python3
pytest
為例):pip3 install pytest
編寫測試用例
test_example.py
),使用unittest
或pytest
編寫測試函數。
unittest
示例:import unittest
def add(a, b): return a + b
class TestAdd(unittest.TestCase):
def test_add(self): self.assertEqual(add(1, 2), 3)
if __name__ == '__main__': unittest.main()
pytest
示例:def add(a, b): return a + b
def test_add(): assert add(1, 2) == 3
運行測試
unittest
:在終端執行python3 -m unittest test_example.py
。pytest
:在終端執行pytest test_example.py
。查看結果
可選步驟:
python3 -m venv venv
,激活后安裝包。根據項目需求選擇框架:unittest
適合基礎單元測試,pytest
適合復雜場景(支持插件、參數化等)。