在Ubuntu上進行Python單元測試,你可以使用Python的內置模塊unittest
或者第三方庫如pytest
方法一:使用Python內置的unittest
模塊
python --version
如果沒有安裝Python,請使用以下命令安裝:
sudo apt update
sudo apt install python3
test_my_module.py
,并在其中編寫你的單元測試。這里是一個簡單的例子:import unittest
from my_module import add
class TestMyModule(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main()
在這個例子中,我們從my_module
模塊中導入了add
函數,并為它編寫了幾個測試用例。
python3 test_my_module.py
你應該會看到類似以下的輸出:
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
方法二:使用pytest
庫
pytest
庫。在終端中輸入以下命令:pip3 install pytest
test_my_module.py
,并在其中編寫你的單元測試。這里是一個簡單的例子:from my_module import add
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
在這個例子中,我們從my_module
模塊中導入了add
函數,并為它編寫了幾個測試用例。
pytest test_my_module.py
你應該會看到類似以下的輸出:
============================= test session starts ==============================
...
collected X items
test_my_module.py .... [100%]
============================== X passed in X.XXs ===============================
這就是在Ubuntu上進行Python單元測試的基本方法。你可以根據自己的需求編寫更多的測試用例,并使用unittest
或pytest
提供的功能來組織和運行這些測試。