在Debian系統中進行Python單元測試,你可以使用Python的內置模塊unittest或者第三方庫如pytest。以下是兩種方法的簡要說明和示例:
unittest模塊編寫測試用例:
創建一個Python文件,例如test_my_module.py,并編寫你的測試用例。
import unittest
from my_module import my_function
class TestMyModule(unittest.TestCase):
def test_my_function(self):
self.assertEqual(my_function(2, 3), 5)
if __name__ == '__main__':
unittest.main()
運行測試: 在終端中運行以下命令來執行測試:
python3 test_my_module.py
pytest庫安裝pytest:
如果你還沒有安裝pytest,可以使用以下命令進行安裝:
pip3 install pytest
編寫測試用例:
創建一個Python文件,例如test_my_module.py,并編寫你的測試用例。pytest使用簡單的命名約定來識別測試函數。
from my_module import my_function
def test_my_function():
assert my_function(2, 3) == 5
運行測試: 在終端中運行以下命令來執行測試:
pytest test_my_module.py
或者,如果你想測試整個目錄中的所有測試文件,可以直接運行:
pytest
假設你有一個簡單的項目結構如下:
my_project/
├── my_module.py
└── tests/
├── __init__.py
└── test_my_module.py
你可以在tests/test_my_module.py中編寫測試用例,并使用上述方法之一來運行它們。
unittest模塊是一種簡單且直接的方法。pytest庫則提供了更多的功能和靈活性,例如自動發現測試、參數化測試等。根據你的需求和偏好選擇合適的方法即可。