Newbie
Newbie

Reputation: 1714

Karate check if xml request contains specific value

My Karate mock server will accept request in XML form, below is the example of the request:

<methodCall>
<methodName>MyMethod</methodName>
<params>
    <param>
        <value>
            <struct>
                <member>
                    <name>a</name>
                    <value>abc</value>
                </member>
                <member>
                    <name>b</name>
                    <value><i4>2</i4></value>
                </member>
            </struct>
        </value>
    </param>
</params>

Within the <struct>, it might have multiple <member> tag. How can I check if within the request <member>, there is specific <name> is presented with specific <value>?

I can define a Scenario like below:

Scenario: pathMatches('/test') && methodIs('post') && bodyPath('/methodCall/methodName') == 'MyMethod'

to handle the request based on methodName, but I would like to do different handling depends on what <member> it contains. For example: If request contains a member with <name>color</name> with value <value>blue</value> then I will do the job accordingly.

Upvotes: 1

Views: 1447

Answers (2)

Eric L.
Eric L.

Reputation: 11

Below is a little snippet from the karate documentation https://github.com/intuit/karate#xml

Given def cat = <cat><name>Billie</name><scores><score>2</score><score>5</score></scores></cat>
# **sadly, xpath list indexes start from 1**
Then match cat/cat/scores/score[2] == '5'
# but karate allows you to traverse xml like json !!
Then match cat.cat.scores.score[1] == 5

You should be able to do something like this paying attention to how you reference the index for xpath:

Scenario: pathMatches('/test') && methodIs('post') && bodyPath('/methodCall/params/param/value/struct/member[1]/value') == 'abc'

Upvotes: 1

Peter Thomas
Peter Thomas

Reputation: 58058

Maybe you are over-thinking this and what you have may be sufficient. All you need to do is return a response conditionally. One tip is that Karate can auto-covert XML into JSON which is convenient because it is easier to write JSON-path queries or filter operations:

Here is some example code that can give you some ideas:

* def structs = get[0] request..member
* def fun = function(x){ return x.name == 'a' && x.value == 'abc' }
* def test = karate.filter(structs, fun)
* if (test.length) karate.set('response', '<some>response</some>')

I guess the point is you are trying to do non-trivial conditional handling, so the code will be more complex than usual.

You can use JSON-path instead of the karate.filter() hack, but the query expression may get harder to read IMO. Note that you can define a function such as getStructType() in the Background - put all the logic you want in it - and then use it in the Scenario HTTP path "route" expression.

Upvotes: 2

Related Questions