溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何用pytest編寫單元測試

發布時間:2025-03-30 19:01:31 來源:億速云 閱讀:145 作者:小樊 欄目:編程語言

使用 pytest 編寫單元測試是一個相對簡單且強大的過程。以下是一些基本步驟和示例,幫助你開始使用 pytest 進行單元測試。

1. 安裝 pytest

首先,你需要安裝 pytest。你可以使用 pip 來安裝:

pip install pytest

2. 編寫測試代碼

假設你有一個簡單的 Python 模塊 math_utils.py,其中包含一些數學函數:

# math_utils.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

3. 編寫測試用例

接下來,你需要編寫測試用例。測試用例通常放在一個以 test_ 開頭的文件中,例如 test_math_utils.py。

# test_math_utils.py

from math_utils import add, subtract, multiply, divide

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(-1, -1) == -2

def test_subtract():
    assert subtract(5, 3) == 2
    assert subtract(0, 0) == 0
    assert subtract(-1, -1) == 0

def test_multiply():
    assert multiply(2, 3) == 6
    assert multiply(-1, 1) == -1
    assert multiply(-1, -1) == 1

def test_divide():
    assert divide(6, 3) == 2
    assert divide(0, 1) == 0
    assert divide(-6, 3) == -2

def test_divide_by_zero():
    with pytest.raises(ValueError):
        divide(1, 0)

4. 運行測試

在命令行中,導航到包含 test_math_utils.py 文件的目錄,然后運行 pytest

pytest

pytest 會自動發現并運行所有以 test_ 開頭的函數,并報告測試結果。

5. 查看測試結果

pytest 會輸出測試結果,包括通過的測試和失敗的測試。例如:

============================= test session starts ==============================
...
collected X items

test_math_utils.py::test_add PASSED                           [ 33%]
test_math_utils.py::test_subtract PASSED                        [ 66%]
test_math_utils.py::test_multiply PASSED                       [100%]

============================== X passed in X.XXs ===============================

6. 高級功能

pytest 提供了許多高級功能,例如:

  • 夾具(Fixtures):用于設置和清理測試環境。
  • 參數化測試:使用 @pytest.mark.parametrize 裝飾器來運行相同的測試函數,但使用不同的輸入。
  • 插件:擴展 pytest 的功能。

示例:使用夾具

# test_math_utils_with_fixture.py

import pytest
from math_utils import add

@pytest.fixture
def setup_data():
    return 2, 3

def test_add(setup_data):
    a, b = setup_data
    assert add(a, b) == 5

示例:參數化測試

# test_math_utils_parametrized.py

import pytest
from math_utils import add

@pytest.mark.parametrize("a, b, expected", [
    (2, 3, 5),
    (-1, 1, 0),
    (-1, -1, -2),
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

通過這些步驟和示例,你應該能夠開始使用 pytest 編寫和運行單元測試了。更多詳細信息和高級功能,請參考 pytest 官方文檔。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女