API Masterminds - How do you use event handlers?
Hi everyone!
Most probably, many of you know about the event handlers functionality in ReadyAPI. It lets you execute a custom Groovy script when an event occurs. For example, if you want to pre-process a request before it’s sent to the server, you would use the RequestFilter.filterRequest event handler, and if you would like to pre-process a response before it’s displayed in the Response Editor and before it’s verified with assertions, you would use the RequestFilter.afterRequest event.
I’ve got a couple of nice examples of the RequestFilter.afterRequest usage.
-
An XML response payload contains a CDATA section. Within this section, you have content that is known to be a well-formed XML and you’d like to apply XML-specific assertions to it. What you can do is to unwrap CDATA with the following code snippet:
def response = context.httpResponse.responseContent; response = response.replaceAll("<!\\[CDATA\\[","").replaceAll("]]>",""); context.httpResponse.responseContent = response;
- A JSON response payload contains a string value that is known to be an escaped JSON string.
For this response
{ "applicationResponse" : "{\"header\":{\"status\":\"OK\"},\"response\":{\"id\": 1,\"date\":\"03-26-2020\"}}" }
the code to unescape the value of the "applicationResponse" property can be as follows:
import groovy.json.JsonSlurper import groovy.json.JsonOutput def response = context.httpResponse.responseContent try{ def jsonSlurper = new JsonSlurper() def responseObj = jsonSlurper.parseText(response) def applicationResponseVal = responseObj.applicationResponse def applicationResponseValUnescaped = applicationResponseVal.replaceAll("\\\\", ""); responseObj.applicationResponse = jsonSlurper.parseText(applicationResponseValUnescaped) log.info(JsonOutput.toJson(responseObj)) context.httpResponse.responseContent = JsonOutput.toJson(responseObj) } catch (e){ log.info("The response was not modified " + e) }
In the above examples, ReadyAPI will try to pre-process every response in your project. If this is not what you need, you can limit the scope of the handler by specifying a target for it. Refer to this KB article for more examples of filters.
Questions:
Do you use event handlers?
Do you use filtering by target?
What are the most common scenarios for your testing process?