Search code examples
groovyjmeterjsr223

Jmeter how to construct payload with same size from csv file by iteration


I had a csv file that contains 10 user ids and the requirement is to construct a payload for every 5 users in the csv. Below is my code:

def start    = (vars.get('__jm__Thread Group__idx') as int)
def offset   = 5
def payload  = [:]
def data     = []

def file     = 'C:/path/dataset.csv'
start.upto(offset, { index ->
    def lineFromCsv = new File(file).readLines().get(index)
    data.add(['userId': lineFromCsv.split(',')[0], 'groupId': lineFromCsv.split(',')[1]])
})

payload.put('data', data)
log.info("%%%The Payload is%%%:" + payload)
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())

My 1st question is why there were 6 items in the first payload (1st iteration), where I was expecting 5. And there were 5 items in the 2nd payload (2nd iteration) as expected. Every payload was supposed to have the same # of items in it.
My 2nd question is that how do I make the 2nd payload start parsing from where the 1st payload left off. The 2nd payload was supposed to contain the next 5 users in the csv? There should not have any overlap items between each payloads.
Below is the payload:
1st payload:

POST data:
{
    "data": [
        {
            "userId": "fakeUser3k0000002",
            "groupId": "1"
        },
        {
            "userId": "fakeUser3k0000003",
            "groupId": "2"
        },
        {
            "userId": "fakeUser3k0000004",
            "groupId": "2"
        },
        {
            "userId": "fakeUser3k0000005",
            "groupId": "3"
        },
        {
            "userId": "fakeUser3k0000006",
            "groupId": "4"
        },
        {
            "userId": "fakeUser3k0000007",
            "groupId": "5"
        }
    ]
}

2nd payload:

POST data:
{
    "data": [
        {
            "userId": "fakeUser3k0000003",
            "groupId": "2"
        },
        {
            "userId": "fakeUser3k0000004",
            "groupId": "2"
        },
        {
            "userId": "fakeUser3k0000005",
            "groupId": "3"
        },
        {
            "userId": "fakeUser3k0000006",
            "groupId": "4"
        },
        {
            "userId": "fakeUser3k0000007",
            "groupId": "5"
        }
    ]
}

Solution

  • def start    = (vars.get('__jm__Thread Group__idx') as int)
    def offset   = 5
    

    i guess Thread Group is your jmeter loop name.

    you have to build loop like this

    (start*offset).step((start+1)*offset,1){ index->
        println it
    }
    

    so for start=5 you'll have index 25 to 29