iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
Python

利用Python完成自動化測試專案系列 第 15

D15 pytest 介紹

  • 分享至 

  • xImage
  •  

經過 15 天,終於來到此次主題的重點 - pytest ,使用它後我們才從「自動化」走向「自動化測試」。

什麼是 pytest

如同其名,它是基於 python 上的測試框架,可以與 selenium 合用實現網頁自動化測試,它有以下幾個優點

  • 免費且開源, import 到專案即可使用
  • 有活躍的社群
  • 使用簡單好上手
  • 支援精美的測試報表(後面文章會提到)
  • 支援許多插件
  • fixture 功能

實際使用

我們可以寫一個簡單的平方函數實際測試 pytest 功能,並用多個方法實作重複執行測試。

首先用 pip 把 pytest 下載到我們的專案

pip install pytest

再來新增一檔案 test_square.py 實際撰寫函式,使用 random 隨機生成數字

import random

# 平方函數
def square(x):
    return x * x

# 平方測試函數
def test_square():
    x = random.randint(1, 100)
    assert square(x) == x * x

然後在終端輸入

pytest

就會開始測試

PS C:\Users\user\Documents\Project\pytest_project> pytest
===================================================================== test session starts ======================================================================
platform win32 -- Python 3.12.6, pytest-8.3.3, pluggy-1.5.0
rootdir: C:\Users\user\Documents\Project\pytest_project
collected 1 item                                                                                                                                                 

test_square.py .  

pytest 除了可以執行特定的測試檔外,若沒有特別指定檔案, pytest 會自動找所有檔案名稱開頭有 test_ 的檔案執行測試。

若想要重複執行測試,有幾種方法

repeat-scope

首先要安裝插件

pip install pytest-repeat

再終端輸入的地方輸入

pytest -s --count=3 --repeat-scope=session

count 是設定次數, repeat-scope 是設定參數範圍,有 funcion, class, module, sesssion 可以選擇,預設為 function。

pytest.mark.parametrize

首先要 import pytest

import pytest

再來在函數的開頭加入 @pytest.mark.parametrize

import pytest

def square(x):
    return x * x

@pytest.mark.parametrize("x", [1, 2, 3, 4, 5])
def test_square(x):
    assert square(x) == x * x

這個方法除了能重複執行測試外還可以自己設定測試的值,大大增加測試的靈活性。

今天講到的只是 pytest 的皮毛而已,下一篇預計會再更深入的解釋 pytest 的各項功能。


上一篇
D14 Github 介紹
下一篇
D16 pytest.ini
系列文
利用Python完成自動化測試專案23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言