Friday, May 25, 2012

Groovy : Read & Write values from csv file


//groovy script to store values in properties 

def testDataSet = []
def failureList = []
def fileName = "d:\\SOAPUI\\planets.CSV"

// Opens file, iterates through each line, splits the line on the commas into an array, and adds
// the array to testDataSet. (So testDataSet is an array of arrays).
new File(fileName).eachLine { line -> testDataSet.add( line.split(",") ) }

log.info( "Read " + testDataSet.size() + " test values from " + fileName )

// If any iteration fails, it will add an entry to the failure list, and they will all be printed at the end
context.setProperty( "failureList", failureList )

// Store the test data in a property called "testData"
context.setProperty( "testDataSet", testDataSet )


// This indicates which line of the file we will start reading from (0 = first line, 1 = second line, etc.)
// We are starting at the second line because the CSV contains a header row at the top that explains what
//   each column means
context.setProperty( "index", 1 )

//groovy script to read values from properties

def testDataSet = context.getProperty("testDataSet") // Retrieve the test data from the testData property
def index = context.getProperty("index") // Track which line of the test input file we're on
def testDataLine = testDataSet[index] // Select the current test data line

def props = testRunner.testCase.getTestStepByName( "Properties" )
props.setPropertyValue("AccountName", testDataLine[0])
props.setPropertyValue("AccountCode", testDataLine[1])
props.setPropertyValue("mars", testDataLine[2])

3 comments:

  1. Great post, keep up with good job!

    For complete solution I miss 2 things:
    - yielding index values for iteration
    - reseting index upon testDataSet exhaustion

    ReplyDelete
    Replies
    1. You may try below.The number of columns in the file will hopefully be predefined. Iterate through the number of testcases (no. of lines in the file) and assign column values to variables and use as desired to set to any properties.

      log.info( "Read " + testDataSet[0].size() + " test values from " + fileName )

      def w = testDataSet[0].size()
      def l = testDataSet.size()

      for (int i = 0; i < w; i ++ )
      {
      (testDataSet[0][i].toString())
      log.info (testDataSet[1][i].toString())
      log.info (testDataSet[2][i].toString())
      log.info (testDataSet[3][i].toString())
      }

      Delete
  2. I like this. This is working.

    ReplyDelete