Как получить определенные c значения из 2 CSV в groovy - PullRequest
0 голосов
/ 03 августа 2020

Помогите разобрать CSV до JSON из 2 файлов в groovy. У меня есть 1-й такой CSV (номера строк каждый раз могут быть разными):

testKey,status

Name001,PASS

Name002,PASS

Name003,FAIL

CSV2 (список всех тестовых ключей, но с разными именами ключей:

Kt,Pd 
PT-01,Name007

PT-02,Name001

PT-03,Name003

PT-05,Name002

PT-06,Name004

PT-07,Name006

Мне нужно совпадение в результате точно таких же значений для testKey (testKey.CSV1 = Kt = CSV2)

Примерно так:

{
    "testExecutionKey": "DEMO-303",
    "info": {
        "user": "admin"
    },
    "tests": [
        {
            "testKey": "PT-02",
             "status": "PASS"
        },
        {
            "testKey": "PT-05",
             "status": "PASS"
        },
        {
            "testKey": "PT-03",
             "status": "FAIL"
        }
    ]
}

Этот код анализирует только одно и то же значение, но без точного соответствия testKey:

File csv1 = new File( 'one.csv')
File csv2 = new File( 'two.csv')

def lines1 = csv1.readLines()
def lines2 = csv2.readLines()

assert lines1.size() <= lines2.size()
fieldSep = /,[ ]*/

def fieldNames1 = lines1[0].split( fieldSep )
def fieldNames2 = lines1[0].split( fieldSep )
def testList = []

lines1[1..-1].eachWithIndex { csv1Line, lineNo ->
  def mappedLine = [:]

  def fieldsCsv1 = csv1Line.split( fieldSep )
  fieldsCsv1[1..-1].eachWithIndex { value, fldNo -> 
    String name = fieldNames1[ fldNo + 1 ]
    mappedLine[ name ] = value
  }

  def fieldsCsv2 = lines2[lineNo + 1].split( fieldSep )
  fieldsCsv2[0..-2].eachWithIndex { value, fldNo -> 
    String name = fieldNames2[ fldNo ]
    mappedLine[ name ] = value
  }

  testList << mappedLine
}
def builder = new JsonBuilder()
def root = builder {
  testExecutionKey 'DEMO-303'
  info user: 'admin'
  tests testList
}

println builder.toPrettyString()

1 Ответ

1 голос
/ 03 августа 2020

Вам нужно привязать CSV2 к карте, а затем использовать его для замены значений из CSV1, например:

import groovy.json.*    

def csv1 = '''
testKey,status
Name001,PASS
Name002,PASS
Name003,FAIL
Name999,FAIL
'''.trim()

def csv2 = '''
Kt,Pd
PT-01,Name007
PT-02,Name001
PT-03,Name003
PT-05,Name002
PT-06,Name004
PT-07,Name006
'''.trim()

boolean skip1st = false

def testMap2 = [:]
//parse and bind 1st CSV to Map
csv2.splitEachLine( /\s*,\s*/ ){
  skip1st ? ( testMap2[ it[ 1 ] ] = it[ 0 ] ) : ( skip1st = true )
}

def keys
def testList = []
csv1.splitEachLine( /\s*,\s*/ ){ parts ->
  if( !keys )
    keys = parts*.trim()
  else{
    def test = [:]
    parts.eachWithIndex{ val, ix -> test[ keys[ ix ] ] = val }
    //check if testKey present in csv2
    if( testMap2[ test.testKey ] ){
      test.testKey = testMap2[ test.testKey ] // replace values from CSV2
      testList << test
    }
  }
}  

def builder = new JsonBuilder()
def root = builder {
    testExecutionKey 'DEMO-303'
    info user: 'admin'
    tests testList
 }

builder.toPrettyString()

дает:

{
    "testExecutionKey": "DEMO-303",
    "info": {
        "user": "admin"
    },
    "tests": [
        {
            "testKey": "PT-02",
            "status": "PASS"
        },
        {
            "testKey": "PT-05",
            "status": "PASS"
        },
        {
            "testKey": "PT-03",
            "status": "FAIL"
        }
    ]
}
...