天天看點

軟體測試/測試開發丨Pytest結合資料驅動-Excel

作者:霍格沃茲測試開發學社

點此擷取更多相關資料> 「連結」

本文為霍格沃茲測試開發學社學員學習筆記分享

原文連結:pytest結合資料驅動-excel L3 - 學習筆記 - 測試人社群

Pytest 結合資料驅動 Excel

讀取 Excel 檔案

  • 第三方庫
    • xlrd
    • xlwings
    • pandas
  • openpyxl
    • 官方文檔: https://openpyxl.readthedocs.io/en/stable/

openpyxl 庫的安裝

  • 安裝:pip install openpyxl
  • 導入:import openpyxl

openpyxl 庫的操作

  • 讀取工作簿
  • 讀取工作表
  • 讀取單元格
import openpyxl

# 擷取工作簿
book = openpyxl.load_workbook('../data/params.xlsx')

# 讀取工作表
sheet = book.active

# 讀取單個單元格
cell_a1 = sheet['A1']
cell_a3 = sheet.cell(column=1, row=3)  # A3

# 讀取多個連續單元格
cells = sheet["A1":"C3"]

# 擷取單元格的值
cell_a1.value           
軟體測試/測試開發丨Pytest結合資料驅動-Excel

工程目錄結構

  • data 目錄:存放 excel 資料檔案
  • func 目錄:存放被測函數檔案
  • testcase 目錄:存放測試用例檔案
# 工程目錄結構
.
├── data
│   └── params.excel
├── func
│   ├── __init__.py
│   └── operation.py
└── testcase
    ├── __init__.py
    └── test_add.py           

測試準備

  • 被測對象:operation.py
  • 測試用例:test_add.py
# operation.py 檔案内容
def my_add(x, y):
    result = x + y
    return result

# test_add.py 檔案内容
class TestWithEXCEL:
    @pytest.mark.parametrize('x,y,expected', get_excel())
    def test_add(self, x, y, expected):
        assert my_add(int(x), int(y)) == int(expected)           

測試準備

  • 測試資料:params.xlsx
軟體測試/測試開發丨Pytest結合資料驅動-Excel

Pytest 資料驅動結合 Excel 檔案

# 讀取Excel檔案
import openpyxl
import pytest

def get_excel():
    # 擷取工作簿
    book = openpyxl.load_workbook('../data/params.xlsx')

    # 擷取活動行(非空白的)
    sheet = book.active

    # 提取資料,格式:[[1, 2, 3], [3, 6, 9], [100, 200, 300]]
    values = []
    for row in sheet:
        line = []
        for cell in row:
            line.append(cell.value)
        values.append(line)
    return values           
軟體測試/測試開發丨Pytest結合資料驅動-Excel

點此擷取更多相關資料>「連結」