Home > Encoding, Groovy > Groovy – a cool problem

Groovy – a cool problem


So I got a small groovy script to maintain. This script is executed as part of a SoapUI project.
The target of the script was simple – iterate 5 times and execute a test-case.
Here was the script:

for( i in 1..5)
{
 log.info("Running Authentication - iteration <" + i + ">.")
 def step = testRunner.testCase.getTestStepByName( "authentication-fail" );
 step.run(testRunner, context);
}

The output was very simple:

Running Authentication - iteration <1>
Running Authentication - iteration <2>
Running Authentication - iteration <3>
Running Authentication - iteration <4>
Running Authentication - iteration <5>

But then I was asked to make ‘5‘ configurable, so I defined it as a parameter and made the following change to the code:

def maxCallsBeforeLock = testRunner.testCase.getPropertyValue("MaxCallsBeforeLock")
for( i in 1..maxCallsBeforeLock)
{
 log.info("Running Authentication - iteration <" + i + ">.")
 def step = testRunner.testCase.getTestStepByName( "authentication-fail" );
 step.run(testRunner, context);
}

Unfortunately, the result was not as I expected:

Running Authentication - iteration <1>
Running Authentication - iteration <2>
...
Running Authentication - iteration <52>
Running Authentication - iteration <53>

Since I’m familiar with the ASCII Code I immediately recognized that 53 is the ASCII code of ‘5‘ and the solution became apparent that I need to convert my fake integer to a real integer. So the revision to the code was simply to replace this:

def maxCallsBeforeLock = testRunner.testCase.getPropertyValue("MaxCallsBeforeLock")

With this:

def maxCallsBeforeLock = testRunner.testCase.getPropertyValue("MaxCallsBeforeLock").toInteger()

Which solved the problem.

Now I had just one thing left to do – to understand why this happened.
53 is the ASCII code of the character ‘5‘. It is also the hashCode of the string “5“.
After some investigation and the help of friends on Stack Overflow I got the answer that Strings with the length of 1 are converted to a single character. So when trying to use them in a range, the numerical value of the corresponding character is used.

Advertisements
Categories: Encoding, Groovy Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: