2

I have a strange problem for which I already have a solution for but it's VERY ugly. I am wondering if there is a better way to do it through Karate or JS. I am new at both so please bear with me.

I am sending a POST call with a rather large request body (total of 19 fields). I have to purposefully send malformed requests for EACH field where instead of inputting a legitimate value for a key, I am putting garbage values (or removing the value altogether) and making sure I get a 400 back as expected.

For example the request body is as follows (shortened for illustration purposes):

{
    "Age": 20
    "School": "UIC"
    "Sex": "Female"
}

I am sending requests like:

* def payload = {"Age":'#(age)',"School":'#(schoolName)', "Sex":'#(gender)'}
* copy payload1 = payload
* copy payload2 = payload
* copy payload3 = payload
* remove payload1.Age
* remove payload2.School
* remove payload3.Sex
* table callTable
    |payload  |status|
    |payload1 | 400  |
    |payload2 | 400  |
    |payload3 | 400  |
* call read (call to the actual POST API here)

Now on surface the above may not look ugly but imagine doing that for 19 fields and instead of remove, there is about FIVE different requests PER field (instead of just one "remove" above).

I have contemplated using JS and a loop function but I don't know enough and my attempts failed spectacularly.

Please advise if there is a way better to do it in Karate and/or JS.

Thank you in advance for reading and for your time!

hungryhippos
  • 405
  • 2
  • 8

1 Answers1

1

You can use a loop to build JSON. For example:

* def keys = ['foo', 'bar', 'baz']
* def body = {}
* keys.forEach(k => body[k] = 'blah')
* match body == { foo: 'blah', bar: 'blah', baz: 'blah' }

See also https://stackoverflow.com/a/69149219/143475

And the main documentation for JSON transforms: https://github.com/intuit/karate#json-transforms

Peter Thomas
  • 47,282
  • 14
  • 68
  • 196