Karate check if xml request contains specific value

安稳与你 提交于 2021-01-28 18:40:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/59728792/karate-check-if-xml-request-contains-specific-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!