Python自動化測試框架-pytest

rustling發表於2024-06-15

原始碼: 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'

相關文章