In Robot Framework, how to perform data-driven testing by creating a separate test case for each line of data in a text file?

前端 未结 3 1436
温柔的废话
温柔的废话 2021-01-13 15:46

In Robot Framework, we can use Test Template to perform data-driven testing. However, in this method, the number of test cases are fixed. We are not able to add new test cas

3条回答
  •  余生分开走
    2021-01-13 16:37

    I feel below one is the better approach.

    Create two libraries one for reading the csv data and another for getting the number of lines like below.

    csvLibrary.py

     1 import csv
     2 class csvLibrary(object):
     3
     4     def read_csv_file(self, filename):
     5         '''This creates a keyword named "Read CSV File"
     6
     7         This keyword takes one argument, which is a path to a .csv file. It
     8         returns a list of rows, with each row being a list of the data in
     9         each column.
     10         '''
     11         data = []
     12         with open(filename, 'rb') as csvfile:
     13             reader = csv.reader(csvfile)
     14             for row in reader:
     15                 data.append(row)
     16         return data
    

    csvLibraryNoOfRows.py

    1 import csv
    2 class csvLibraryNoOfRows(object):
    3
    4     def csv_length(self, filename):
    5         '''This creates a keyword named "CSV Length"
    6
    7         This keyword takes one argument, which is a path to a .csv file. It
    8         returns a list of rows, with each row being a list of the data in
    9         each column.
    10         '''
    11         length=0
    12         with open(filename, 'rb') as csvfile:
    13             reader = csv.reader(csvfile)
    14             for row in reader:
    15                 length+=1
    16         return length
    

    Include these two libraries in your test files. Using length, lets say "N" you can get the row data/cell data with the help of :FOR ${index} IN RANGE ${csvlength}

    Example code is below.

    Library        csvLibrary.py
    Library        csvLibraryNoOfRows.py
    
    *** Test Cases ***
    
    Reading a csv file
    ${csvdata}=    read csv file   sample.csv
    ${csvlength}=   csv length  sample.csv
    :FOR    ${index}    IN RANGE    ${csvlength}
        \   log ${csvdata[${index}]}
    

提交回复
热议问题