原始碼: https://github.com/pytest-dev/pytest
文件: https://docs.pytest.org/en/8.2.x/
安裝: pip install pytest
簡單樣例
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
命令列執行python
可以看到執行結果
命名規範
- 測試模組: 檔案以
test_
開頭 - 測試類: 以
Test
開頭 - 測試方法: 函式以
test
開頭
# content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
命令列執行pytest -q test_class.py
執行方式
# Run tests in a module
pytest test_mod.py
# Run tests in a directory
pytest testing/
# Run tests by keyword expressions
# 執行 TestMyClass.test_something, 不執行 TestMyClass.test_method_simple
pytest -k 'MyClass and not method'