在 Ubuntu 上测试 Python 代码,常见方式有以下几种,从最简单到更规范依次说明:
python3
然后输入:
print("hello")
按 Ctrl + D 退出。
.py 文件python3 test.py
例如 test.py:
def add(a, b):
return a + b
print(add(1, 2))
运行:
python3 test.py
assert 做基础测试def add(a, b):
return a + b
assert add(1, 2) == 3
assert add(-1, 1) == 0
print("测试通过")
运行:
python3 test.py
unittest(Python 内置)test_math.py:
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
运行:
python3 test_math.py
pytest(推荐,更简洁)pip3 install pytest
test_sample.py:
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
运行:
pytest
python3 -m venv venv
source venv/bin/activate
pip install pytest
pytest
退出环境:
deactivate
python3 --version
pip3 --version
which python3
如果你是:
python3 xxx.pypytestunittest 或 assert可以告诉我你是测试什么类型的代码(算法 / Web / 脚本 / 作业),我可以给你更具体的示例。