1. 程式人生 > >RobotFramework環境配置二十一:資料驅動(總結)

RobotFramework環境配置二十一:資料驅動(總結)

資料驅動(總結)

RIDE提供的庫:

自定義庫:DataCenter.py

一、資料驅動測試
注重於測試軟體的功能性需求,也即資料驅動測試執行程式所有功能需求的輸入條件

二、總結:根據資料來源,靈活地實現KISS。

  • 資料較少

資料比較少的時候,可以使用 Create List, Get File & Import Variables。
建立 List 最快捷、最簡單,但是處理多維列表就比較麻煩。如何建立多維列表,請檢視齊道長的部落格。

這裡寫圖片描述

從 File 獲取資料需要自己封裝關鍵字,把原始資料處理並存儲為列表。可以處理稍微複雜的資料,不過 File 儲存的資料本身格式並不直觀。

這裡寫圖片描述

Import Variables 和 Create List 類似。相比 Create List,Import Variables 較靈活。因為 Import Variables 可以直接建立多維列表。

list1 = [[['grade1'], [5, 2, 3, 4], [6, 1, 7, 8]], [['grade2'], [1, 2, 3, 4], [5, 6, 7, 8]]]

如果資料較少,比 Get Sheet Values From Excel 跟靈活。例如,在 Get Sheet Values From Excel 方法中的例項就需要把三維列表轉換為二維列表。三維列表是從網頁上獲取並存儲的資料。

    def Reorgnize_List(self, alsit):
        newList = []
        for element in alsit:
            if isinstance(element, list):
                for el in element:
                    newList.append(natsort.natsorted(el))
        OrderedData = natsort.natsorted(newList)
        return OrderedData

if
__name__ == '__main__': obj = main() list1 = [[['grade1'], [5, 2, 3, 4], [6, 1, 7, 8]], [['grade2'], [1, 2, 3, 4], [5, 6, 7, 8]]] list2 = obj.Reorgnize_List(list1) print list2

測試新的二維列表與 Excel 中讀取的資料保持一致。

list1 = [['grade1'], [5, 2, 3, 4], [6, 1, 7, 8]], ['grade2'], [1, 2, 3, 4], [5, 6, 7, 8]]
  • 資料較多

模板 Template,實現資料驅動簡單。

這裡寫圖片描述

但是,缺乏靈活度。比如,Read Column From Excel 方法中實現的選卡並測試每張卡所包含的課程,資料需要在關鍵字之間互動傳遞。如果寫在一個關鍵字中,這個關鍵字將會過於複雜,不易管理維護。

RIDE 提供的 ExcelLibrary 功能較齊全。缺點較明顯,即所有資料加上了行列值,處理起來比較麻煩。

這裡寫圖片描述

如果不願意修改原始碼也可使用,不過在使用的時候需要小心謹慎。

最後,就是根據自身需求開發自定義關鍵字實現資料驅動。大家可以靈活運用,不用過於教條。

三、data_center.py 原始碼

# -*- encoding = cp936 -*-
# Author: Allan
# Version: 2.0
# Data: 2017-3-20

import os, sys
import csv
import xdrlib
import xlrd
import json
import natsort

class data_center:

    def __init__(self):
        #Default File Path:
        self.data_dir = os.getenv('G_DATACENTER', 'F:\\Robotframework\\common\\resource')
        #print self.data_dir

        #Current Log Path:
        self.curr_dir = os.getenv('G_CURRENTLOG', 'f:\\robotframework\\logs')
        #print self.curr_dir

    def Read_Data_From_Excel(self, filename, path=None, includeEmptyCells=True):
        """
        Returns the values from the file name specified. Returned values is separated and each sublist is one column.

        Arguments:
                |  filename (string)  | The selected Excel file that the cell values will be returned from. |
                |  path               | Default dirctory is G_DATACENTER |
        Example:

        | *Keywords*           |  *Parameters*                                      |
        | ${data}    |  Read_Data_From_Excel           |  ExcelRobotTest.xls  |     %{G_DATACENTER}      |  includeEmptyCells=True |

        """
        if path == None:
            file = os.path.join(self.data_dir, filename) # Default File Path
        else:
            file = os.path.join(path, filename)
        try:
            data = xlrd.open_workbook(file)
            table = data.sheets()[0]

            nrows = table.nrows
            nclos = table.ncols

            listAll=[]
            for row in range(2,nrows):
                alist=[]
                for col in range(1,nclos):
                    val = table.cell(row,col).value
                    # Solve issue that get integer data from Excel file would be auto-changed to float type.
                    alist.append(self.keep_integer_type_from_excel(val))
                listAll.append(alist)
            #print listAll
            listAll = self.unic(listAll)
        except Exception, e:
            print str(e)

        if includeEmptyCells is True:
            return listAll
        else:
            newList = []
            for element in listAll:
                while "" in element:
                    element.remove("")
                newList.append(natsort.natsorted(element))
            OrderedData = natsort.natsorted(newList)
            return OrderedData

    def Read_Excel_File(self, filename, path=None, includeEmptyCells=True):
        """
        Returns the values from the file name specified. Returned values is separated and each sublist is one column.

        Arguments:
                |  filename (string)  | The selected Excel file that the cell values will be returned from. |
                |  path               | Default dirctory is G_DATACENTER |
        Example:

        | *Keywords*           |  *Parameters*                                      |
        | ${data}    |  Read_Excel_File           |  ExcelRobotTest.xls  |     %{G_DATACENTER}      |   includeEmptyCells=True   |

        """
        if path == None:
            file = os.path.join(self.data_dir, filename) # Default File Path
        else:
            file = os.path.join(path, filename)
        try:
            data = xlrd.open_workbook(file)
            table = data.sheets()[0]

            nrows = table.nrows
            nclos = table.ncols

            listAll=[]
            for row in range(2,nrows):
                for col in range(1,nclos):
                    val = table.cell(row,col).value
                    # Solve issue that get integer data from Excel file would be auto-changed to float type.
                    value = self.keep_integer_type_from_excel(val)
                    # print value, type(value)
                    listAll.append(value)
            #print listAll
            listAll = self.unic(listAll)
        except Exception, e:
            print str(e)

        if includeEmptyCells is True:
            return listAll
        else:
            # Delete all empty data
            while '' in listAll:
                listAll.remove('')
            return listAll

    def Read_CSV_File(self, filename, path=None):
        """
        Returns the values from the sheet name specified.

        Arguments:
                |  filename (string)  | The selected CSV file that the cell values will be returned from. |
                |  path               | Default dirctory is G_DATACENTER |
        Example:

        | *Keywords*           |  *Parameters*                                                    |
        | ${data}    |  Read_CSV_File           |  ExcelRobotTest.csv  |     %{G_DATACENTER}      |  

        """
        if path == None:
            file = os.path.join(self.data_dir, filename) # Default File Path
        else:
            file = os.path.join(path, filename)
        data = []

        with open(file, 'rb') as csvfile:
            data = [each for each in csv.DictReader(csvfile)]
            # reader =csv.reader(csvfile)
            # for col in reader:
            #   data.append(col)
            return self.unic(data)

    def is_number(self, val):
        # Check if value is number not str.
        try:
            float(val)
            return True
        except ValueError:
            pass

        try:
            import unicodedata
            unicodedata.numeric(val)
            return True
        except (TypeError, ValueError):
            pass

    def keep_integer_type_from_excel(self, value):
        # Keep integer number as integer type. When reading from excel it has been changed to float type.
        if self.is_number(value) and type(value) != unicode and value%1 == 0:
            return str(int(value))
        else:
            return value

    def unic(self, item):
        # Resolved Chinese mess code.
        try:
            item = json.dumps(item, ensure_ascii=False, encoding='cp936')
        except UnicodeDecodeError:
            try:
                item = json.dumps(item, ensure_ascii=False, encoding='cp936')
            except:
                pass
        except:
            pass

        item = json.loads(item, encoding='cp936') # Convert json data string back
        return item

    def Read_Column_From_Excel(self, filename, column, path=None, includeEmptyCells=True):
        reload(sys)
        sys.setdefaultencoding('cp936') 
        alist = []
        if path == None:
            file = os.path.join(self.data_dir, filename) #Default Data Directory
        else:
            file = os.path.join(path, filename)

        try:
            excel_data = xlrd.open_workbook(file)
            table = excel_data.sheets()[0]

            for row_index in range(2, table.nrows):
                value = table.cell(row_index, int(column)).value
                print value
                alist.append(self.keep_integer_type_from_excel(value))
            #print alist
            listAll = self.unic(alist)
        except Exception, e:
            print str(e)

        if includeEmptyCells is True:
            return listAll
        else:
            # Delete all empty data
            while '' in listAll:
                listAll.remove('')
            return listAll

    def Get_Sheet_Values_From_Excel(self, filename, sheetname, path=None, includeEmptyCells=True):
        """
        Returns the values from the sheet name specified.

        Arguments:
                |  Sheet Name (string)                 | The selected sheet that the cell values will be returned from.                                                              |
                |  Include Empty Cells (default=True)  | The empty cells will be included by default. To deactivate and only return cells with values, pass 'False' in the variable. |
        Example:

        | *Keywords*           |  *Parameters*                                      |
        | Get Sheet Values           |  ExcelRobotTest.csv  | TestSheet1     |     %{G_DATACENTER}         |   includeEmptyCells=True     |

        """
        if path == None:
            file = os.path.join(self.data_dir, filename) #Default Data Directory
        else:
            file = os.path.join(path, filename)

        try:
            excel_data = xlrd.open_workbook(file)
            sheetNames = self.get_sheet_names(excel_data)
            my_sheet_index = sheetNames.index(sheetname)
            #print my_sheet_index
            table = excel_data.sheet_by_index(my_sheet_index)

            nrows = table.nrows
            nclos = table.ncols

            listAll=[]
            for row in range(2,nrows):
                alist=[]
                for col in range(1,nclos):
                    val = table.cell(row,col).value
                    # Solve issue that get integer data from Excel file would be auto-changed to float type.
                    alist.append(self.keep_integer_type_from_excel(val))
                listAll.append(alist)
            #print listAll
            listAll = self.unic(listAll)
        except Exception, e:
            print str(e)

        if includeEmptyCells is True:
            return listAll
        else:
            newList = []
            for element in listAll:
                while "" in element:
                    element.remove("")
                newList.append(natsort.natsorted(element))
            OrderedData = natsort.natsorted(newList)
            return OrderedData

    def get_sheet_names(self, wb):
        """
        Returns the names of all the worksheets in the current workbook.

        Example:

        | *Keywords*              |  *Parameters*                                      |
        | ${sheetNames}           |  Get Sheets Names                                  |

        """
        sheetNames = wb.sheet_names()
        return sheetNames

相關推薦

RobotFramework環境配置資料驅動總結

資料驅動(總結) RIDE提供的庫: 自定義庫:DataCenter.py 一、資料驅動測試 注重於測試軟體的功能性需求,也即資料驅動測試執行程式所有功能需求的輸入條件。 二、總結:根據資料來源,靈活地實現KISS。 資料較少 資料比較

執行緒基礎()-併發容器-ArrayBlockingQueue

本文作者:王一飛,叩丁狼高階講師。原創文章,轉載請註明出處。 在正式講解ArrayBlockingQueue類前,先來科普一下執行緒中各類鎖,只有瞭解這些鎖之後,理解ArrayBlockingQueue那就更輕鬆了。 可重入鎖 一種遞迴無阻塞的同步機制,也叫做遞迴鎖。簡單講

Qt總結記憶體洩漏彙總

一、簡介        Qt記憶體管理機制:Qt 在內部能夠維護物件的層次結構。對於可視元素,這種層次結構就是子元件與父元件的關係;對於非可視元素,則是一個物件與另一個物件的從屬關係。在 Qt 中,在 Qt 中,刪除父物

Esper學習之EPL語法

轉載請註明出處:http://blog.csdn.net/luonanqin        元宵過後回公司上班,換了個部門,換了個領導,做的事也換了,不過Esper還是會繼續搞,所以部落格也會慢慢寫的,大家別急。^_^        上一篇說到了EPL如何訪問關係型資料

算法系列之實驗資料與曲線擬合

12.1 曲線擬合12.1.1 曲線擬合的定義        曲線擬合(Curve Fitting)的數學定義是指用連續曲線近似地刻畫或比擬平面上一組離散點所表示的座標之間的函式關係,是一種用解析表示式逼近離散資料的方法。曲線擬合通俗的說法就是“拉曲線”,也就是將現有資料透過

性能測試性能測試環境之mysql

files 使用 mysql目錄 con 過程 版本 i686 shutdown 服務 在正常工作中,mysql應該部署到 一臺獨立的服務器上,不與tomcat共用服務器,由於成本原因,現部署到一起 為避免出錯引起麻煩,先備份: 一:環境清理:先卸載系統自帶的mysql

效能測試效能測試環境之mysql

在正常工作中,mysql應該部署到 一臺獨立的伺服器上,不與tomcat共用伺服器,由於成本原因,現部署到一起 為避免出錯引起麻煩,先備份: 一:環境清理:先解除安裝系統自帶的mysql 停止mysql:service mysql stop 1、查詢以前是否裝有mysql:命令:rpm -qa|g

Tensorflow深度學習之LeNet的實現CIFAR-10資料

一、LeNet的簡介 LeNet是一個用來識別手寫數字的最經典的卷積神經網路,是Yann LeCun在1998年設計並提出的。Lenet的網路結構規模較小,但包含了卷積層、池化層、全連線層,他們都構成了現代CNN的基本元件。 LeNet包含輸入層在內共有

Nginx詳解Nginx深度學習篇之配置蘋果要求的openssl後臺HTTPS服務

9.png 升級 ssl 版本升級 org tex 技術 就是 加密 配置蘋果要求的證書: 1、服務器所有的連接使用TLS1.2以上的版本(openssl 1.0.2) 2、HTTPS證書必須使用SHA256以上哈希算法簽名 3、HTTPS證書必須使用RSA20

【Java並發編程】之並發新特性—阻塞隊列和阻塞棧含代碼

err 退出 link rac gb2312 com void throws pbo 轉載請註明出處:http://blog.csdn.net/ns_code/article/details/17511147 阻塞隊列 阻塞隊列是Java 5並發新特性中的內容

Java並發編程原理與實戰線程通信wait&notify&join

ola run 原理 ons spa sta pro join() cto wait和notify wait和notify可以實現線程之間的通信,當一個線程執行不滿足條件時可以調用wait方法將線程置為等待狀態,當另一個線程執行到等待線程可以執行的條件時,調用notify

Redis()Redis效能問題排查解決手冊

效能相關的資料指標 通過Redis-cli命令列介面訪問到Redis伺服器,然後使用info命令獲取所有與Redis服務相關的資訊。通過這些資訊來分析文章後面提到的一些效能指標。 info命令輸出的資料可分為10個類別,分別是: server clients memory persis

Redis()Redis性能問題排查解決手冊

毫秒 直接 不包含 特定 命令 不用 超出 pip 過去 性能相關的數據指標 通過Redis-cli命令行界面訪問到Redis服務器,然後使用info命令獲取所有與Redis服務相關的信息。通過這些信息來分析文章後面提到的一些性能指標。 info命令輸出的數據可分為10個類

SpringBoot專案開發()Gzip壓縮

為了減少資料在網路中的傳輸量,從而減少傳輸時長,增加使用者體驗,瀏覽器大都是支援Gzip壓縮技術的,http的請求頭 Accept-Encoding:gzip, deflate 就表示這次請求可以接受Gzip壓縮後的資料,圖片不要進行壓縮,因為圖片完全可以在專案開發中使用壓縮後的圖片。壓

步步走>> 設計模式Visitor-訪問者

package com.test.DPs.XingWei.Visitor; /** * 行為型:Visitor-訪問者 外觀:作用面為 物件 * * 用途:表示一個作用於某物件結構中的各元素的操作。 * 它是你可以在不改變各元素的類的前提下定義作用於這些元素的新操作。 *

【原創】《矩陣的史詩級玩法》連載用矩陣計算直線和次貝塞爾曲線的交點

搞了這麼多理論,現在是時候展現一下矩陣的魅力了。看看經過矩陣變換後的曲線求交是何等的方便! 上篇說過,矩陣簡化的效果立竿見影,如同連載二的直線橢圓相交判斷一樣。 按我的套路,我是會先給出傳統的做法,然後再用矩陣的史詩級玩法將其擊敗,不過這次為了不讓大家看暈,我選擇把順序調

Swift 學習之?和 !詳解

新更新的內容請移步閱讀: Swift語言使用var定義變數,但和別的語言不同,Swift裡不會自動給變數賦初始值, 也就是說變數不會有預設值,所以要求使用變數之前必須要對其初始化 。如果在使用變數之前不進行初始化就會報錯: var stringValue : Stri

Maven 學習筆記Maven倉庫(快照版本)

 Maven倉庫(快照版本) ---------- 在Maven的世界中,任何一個專案或者構件都必須有自己的版本。版本的值可能是1.0.0,1.3-alpha-4,2.0,2.1-SNAPSHOT或者2.1-20091214.221414-13。其中,1.0、1.3-a

《Nodejs開發加密貨幣》之交易

題外話:這篇文章,耗費了我大量精力,用UML表達javascript類及流程本來就不是什麼容易的事情,用來描述加密貨幣交易這種驗證邏輯非常多的程式碼更難,加之Nodejs的回撥在這些程式碼裡巢狀很深,所以如何把非同步呼叫變成人類容易理解的順序呼叫,也做了一番取捨

Android實戰技巧之Android原型設計工具探索

移動開發者、移動產品經理和互動設計師在有了產品的想法後會做出一系列的草圖,然後反覆推敲改進,直到自己滿意。這個草圖就是原型設計,是產品設計初期很重要的工作,它是產品的雛形,之後會以此為原型進行開發。 當移動網際網路熱度增加後,一些主打移動原型設計的工具如雨後春