Replace a String

Use the following code replacing a version number in a message as an example of string replacement using CloudTest > Scripts. This script example represents the output of a recorded clip for HTTP traffic. These messages have strings in them that contain the CloudTest build version number. In order to make the clips portable across versions, it is necessary to either replace the version with a generic version string ("version") or the real new version number.

Note: Use the following links to download and import the XML for the entire Replace Version Number Composition or just the Replace Version Number Script. XML can be imported using the CloudTest > Repository toolbar > Import icon or copy and paste only the script code from here.

Refer to Script to learn how to add a script to a test clip and test composition.

How to

  1. Specify the last build number as versionToReplace . var versionToReplace = "version20";
  2. Set a variable, version , with its value as "version". var version= "version";
  3. Create an array, clipElements , and populate it with the children of the currentClip. Cycle through all the elements.
    • Line 4 returns the var (clearly an array) which points to the children. Line 5 creates the "for" loop to cycle through those array elements.
    var clipElements = $context.currentClip.children; for (var i=0; i<clipElements.length; ++i)
  4. Get the next item in the clip. var clipElement = clipElements[i]; if (clipElement.type == "Message")
  5. For each clip element whose type is "Message", its version is updated to the new version.

What you should see

Note: origMessage is the original message body and newMessage is the newly constructed replacement message body (with the build number replaced), which is then put back into the message.

If there was something in the message text that was replaced (causing origMessage to not equal newMessage ), then use setMessage to put the changed message back into the message. The remaining lines of code post text stating that the replacement has been done.

var = clipElement.getMessage(clipElement.MESSAGE_HTTP_BODY); var newMessage = origMessage.replace( versionToReplace ,version); if (origMessage != newMessage) { clipElement.setMessage(newMessage, clipElement.MESSAGE_HTTP_BODY); $context.result.postMessage($context.result.LEVEL_INFO, "Replaced version string in Message.", "Original Message: " + origMessage + "\n\nNew Message: " + newMessage); } } }