讀取excel測試資料

2021-08-28 12:22:44 字數 2099 閱讀 9368

unittest 的 test***() 本身是不推薦使用函式引數的,然而實際使用時,是不太可能將資料寫死,每條用例資料都寫乙個 test***() 方法,所以需要借助配置檔案例如excel,然而,又是如何將同乙個方法,進行多次測試,並且用到不同的資料,還生成測試報告呢?

如下,提供一種解決方案

1、用xlrd讀取excel資料

import xlrd

def readexcel(sheetname,rownum,colnum):

excel = xlrd.open_workbook('c:\\users\admin\\desktop\\testdata.xlsx')

sheet = excel.sheet_by_name(sheetname)

data = sheet.cell_value(rownum-1,colnum-1)

return data

2、用 @classmethod 裝飾 setup(),使 self.n 遞增

3、注意要點:

(0)excel資料至少包含用例資料、預期結果

(1)在 testcase 子類之外,定義乙個返回值為 true、false的函式 func(…)

(2)在 testcase 子類中,定義的測試方法,用 assert func(…) 來處理

(3)for迴圈用同乙個方法構建測試集

for i in range(5): 

suite.addtest(unittest.makesuite(類名,"方法開頭字串"))

def mycal(a,b,c,result):		# 這個函式不能寫在下邊的類裡邊

mul = a*b

r = mul + c

print a,'*',b,'+',c ,'==',result

return r == result

#coding=utf-8

import unittest

from unittest import testsuite

from htmltestrunner import htmltestrunner

import xlrd

class getexceldata(unittest.testcase):

@classmethod

def setupclass(self):

self.n = 1

@classmethod # 一般setup()不需要,這裡是為了self.n遞增

def setup(self):

self.n = self.n + 1

print "n = ",self.n

def aaa(self):

a = readexcel("testone",self.n,2)

b = readexcel("testone",self.n,3)

c = readexcel("testone",self.n,4)

result = readexcel("testone",self.n,5)

assert mycal(a,b,c,result)

if __name__ == "__main__":

suite = testsuite()

for i in range(5):

print 'i = ',i

suite.addtest(unittest.makesuite(getexceldata,'aaa'))

runner = unittest.texttestrunner(verbosity=2)

runner.run(suite)

fp = file("./excelresult.html",'wb')

runner = htmltestrunner(fp,title="calculation result")

runner.run(suite)

fp.close()

Python讀取測試資料檔案

在日常測試過程中,經常遇到需要讀取測試資料檔案,這邊就涉及到乙個檔案讀取的方法。這篇文章主要以python讀取檔案的基礎方法為本,包括讀取excel檔案 yaml檔案 csv檔案。下面是具體實現方式 import openpyxl import yaml import csv from conf.c...

構造測試資料 對比測試資料

正確 include using namespace std typedef long long ll const int max n 1e6 10 intmain return0 author max n date 2019 10 04 15.03.21 description 正確 錯誤 inc...

python讀取測試資料的多種方式

目錄 1 建立乙個config.ini或者.conf檔案,這種方法就是ini檔案的讀取,如下 api url www.taobao.com method get mysql db hello port 3306 2 使用python的configparser庫讀取,如下 from configpar...