Vous êtes sur la page 1sur 44

Groovy Scripting-for SOAPUI

What is Groovy?
• Groovy
• Dictionary Meaning: fashionable and exciting , excellent.
Groovy is a powerful, optionally typed and dynamic language,
with static-typing and static compilation capabilities, for the Java
platform aimed at improving developer productivity thanks to a
concise, familiar and easy to learn syntax.
Variable Declaration
• Groovy is an “optionally” typed language(Java Strongly typed
language).
int i=10
def i=10 //both will do same in groovy
• In groovy, end of statement semicolon is optional
• We can mix both java and groovy statements in groovy script
Groovy Optionals
1. Typing
2. Semicolon at end of each statement
3. public key word is optional by default it is public
4. parentheses
5. return keyword
Data Types –Defaults-Ranges
Java Data Types In Groovy typing is Optional
S.No Type Contains Default Size Range  No need to explicit type declaration of a variable
1 boolean true or false false 1 bit true,false
2 char Unicode Character u0000 16 bits \u0000 to \uFFFF
3 byte Signed Integer 0 8 bits -127 to 128
4 short Signed Integer 0 16 bits -32768 to +32767
5 int Signed Integer 0 32 bits -2147473648 to -2147473647
6 long Signed Integer 0L 64 bits -9223372036854775808 to -9223372036854775807
7 float Floating Number 0.0f 32 bit +/-1.4E-45 to +/-3.40282335E+38
8 double Floating Number 0.od 64 bit +/-4.9E-324 to +/-1.7976931348623157E+308
Conditional Statements
• Simple if
• if-else
• If-else ladder
• Switch-Case statement
Assertion
Assertion
• At the most basic level, testing is about assertions; verifying that what you
get out is what you expect, based on what you put in.. It may be verifying
simple things like “did I connect?” or “is the response in the correct
format?”, or “is the returned data valid?”. But it may deal with more
abstract or involved things. 1 Browsers cannot do assertions. Instead, you
need to provide the correct answer for yourself, quite often by checking
the connection, verifying the format or reviewing the data manually.
• Assertions are used
• to validate functionality by comparing parts of the message (or the entire message)
to some expected value.
• Any number of assertions can be added to a sampler TestStep, each
validating some different aspect or content of the response.
Groovy Truth Shortcut
for null
check
• Non-empty variables/collection are evaluated to true.
• Empty variables/collection are evaluated to false.
def i
assert(i) -here I evaluates as false
If(i){
log.info ”in if block”
}
else{
log.info “in else block”
}
Groovy Truth
• Non-empty Strings is coerced as true
• Non Zero is coerced as true
• Non-empty Collections and arrays are true.
• Non-empty Maps are evaluated to true.
• Non-zero numbers are true.
• Iterators and Enumerations with further elements are coerced to true.
• Non-null object references are coerced to true.
Loops
• classic for loop
• for in loop
• while loop
Groovy Quotes
Java,
 single quotation marks denote a single
• Single Quotes: don’t support interpolation character
 double quotation marks denote a string.
def x = 1
log.info ‘Variable x has a value of ${x}’
• Double Quotes: support interpolation
def x = 1
log.info "Variable x has a value of ${x}"
• Tripple Quotes: Triple single quotes in strings are used to represent
multiline strings.
def aMultilineString = '''line -1
line -2
line-3''‘
Note: Don’t support interpolation
String Handling
• Splitting and Joining
• Splitting String with delimiter
• Joining List with delimiter
Splitting String with delimiter Joining list with delimiter

def myListString = “Apple,Banana,Carrot” def myList = ["Apple", "Banana", "Carrot"]


def listItems = myListString.split(",") def joinResult = myList.join(",") Apple,Banana,Carrot
log.info listItems[0] Apple log.info joinResult
log.info listItems[1] Banana
log.info listItems[2] Carrot Joining List
def myList = ["Apple", "Banana", "Carrot"]
def joinResult = myList.join(",") AppleBananaCarrot
log.info joinResult
GStrings
• Strings in double quote are called Gstrings.
• A special property of it is it evaluates expressions inside it, enclosed in
${}.
For example:
def firstName = ‘rajendra'
def lastName = “prasad"
println '${lastName}, ${firstName}' // output: ${lastName}, ${firstName}
println "${lastName}, ${firstName}" // output: rajendra, prasad
Time Stamp Strings
Printing Date
def d = new Date()
log.info d.format('dd/MM/yyyy') 20/01/2017

Printing Time Stamp in Specific Time Zone


def d = new Date()
def tz = TimeZone.getTimeZone('PST')
log.info d.format('dd/MMM/yyyy ', tz) 20/Jan/2017 09:35:51

Printing Time Stamp String


def d = new Date()
def tz = TimeZone.getTimeZone('PST')
log.info d.format('dd_MM_yyyy_hh_mm_ss', tz) 20_01_2017_09_39_04
Generates Unique String
• def guidVal = "${java.util.UUID.randomUUID()}"
2e7f71c7-b3f1-464d-a332-ae75da6e66b1
Delay

sleep(3000)
Type Conversions
String to Other data Types Other Type to String
.toInteger() .toString()
Why We care?
.toBigDecimal(),
.toBigInteger(),
.toBoolean(),
.toCharacter()
.toDouble(),
.toFloat(),
.toList(),
.toLong().

Note: toInteger() method Deprecated in Groovy


Pattren Matching
• ”=~” - Creates a Matcher out of the String on the left hand side and the
Pattern on the right.
Important Cases:
Full Match
Pattren: Partial Match
Ignore Case
assert 'rajendra' =~ /rajendra/

Partial Match: /(?s).*errors.*/


Undestanding
(?s) :ignores line breaks
.* :for all
Sample:
if ("errors found:\n Aborting now \n" ==~ /(?s).*errors.*/)
Other Cases
• assert 'groovy' =~ /gr.*/ matching string with starts with ‘gr’

• assert 'groovy' =~ /groov?/ matching string with starts with ‘groov’ and with additional any one char
• assert 'groovy' =~ /gr.*ov/ matching string with starts with ‘gr’ and end with ‘ov’

• assert 'grooooovy' =~ /gr.*ov?/


• assert 'greets'=~/gr\w{4}/ matching string with starts with ‘gr followed by 4 characters.

• assert 1234 =~ /\d+/ matching for checking is it number or not


• assert 1234 =~ /\d[0-4]/ digits range matching
• assert 'rajendra' =~ /\w/ matching for checking is it word or not
• assert 'rajendra' =~ /\w{8}/ matching for word type of and size
Logical Operators
• Groovy offers three logical operators for boolean expressions:
1. && : logical "and"
2. || : logical "or"
3. ! : logical "not“

Example
assert !false  true
assert true && true  true
assert true || false  true
assert false  false
assert true && false  false
assert t false || false  false
Closures
• A closure in Groovy is three things:
• a block of code that can access variables in the scope where it is declared.
• a function that can take arguments and always returns a result (may be null)
• an object that has properties and methods with and without side-effects
• A closure has a default implicit parameter called 'it‘
def square = { it * it }
assert square(3) == 9
def isStringLongerThan = { String s, int i -> return s.size() > i }
shortNames.each({ String name -> println name })
G Path
Properties
• Use of Property?
• Types of Properties?
• Custom Properties: Custom Properties as variables
• Object Properties: Object (or Context) Properties as options or settings
• Property Transfer?
• Property Expansion?
Property Expansion
• A common syntax to dynamically insert (“expand”) property values during
processing.
• Allows to insert and reuse property values from other places in tests
• Allows to add placeholders at various places in requests and
assertions, and automatically replaced with real values during the test
execution.
• Property Expansions provide a common syntax to dynamically insert
(“expand”) property values during processing.
Expansion Syntax
Value Scope
#System references a system property. Found in Help>System
• The syntax to access TestSuite, TestCase and TestStep #Global references a global property.
properties is: #Env references an environment variable.
#Project references a project property.
${[scope]#propertyName[#xpath-expression]} #TestSuite references a project property.
Examples: #TestCase references an environment variable.

${#Project#PropertyName}
${#TestSuite#PropertyName}
${#TestCase#PropertyName}
${#Global#PropertyName}
${#System#PropertyName}
Property Expansion to Reading Response
• The syntax to access response of xyz request is:
${<XYZRequestName>#Response}
Example:
def quickSearchResponse = context.expand( '${GetQuickSearch#Response}' )
• The syntax to access response of Data Source row value:
Example:
def campaignName = context.expand( '${GetAllAvailableCampaigns#campaignName}' )
Understanding REST API Request
• Request: Method+Endpoint+[version path]+Resource+Path+Query Parameters
• Request Template

Raw requests
GET https://portal.na4.livevox.com/ConfigMgr_5.0.0/campaign?operation=deactivate&client_id=1001506&rnd=1483450612323
POST https://portal.na4.livevox.com/ConfigMgr_5.0.0/login?operation=login
GET https://portal.na4.livevox.com/ConfigMgr_5.0.0/quicksearch?operation=get&query=QAconfig&_=1484735268217&fullConfigMgrGUI=true
GET https://portal.na4.livevox.com/ConfigMgr_5.0.0/component?operation=get&_=1484735345498&rnd=1484735345499
GET https://portal.na4.livevox.com/ConfigMgr_5.0.0/campaign?operation=get_campaign_detail&fullConfigMgrGUI=false&client_id=1001506&_=1483447088753&rnd=1483429068000&campaign_id=100170606
POST https://acd.na4.livevox.com/VirtualACD_5.0.104/agent/status/ready
JSON Parsing
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}') Formatted JSON Message:
log.info result
{
log.info result.person
"person":{
log.info result.person.pets[1]
"name":"Guillaume",
"age":33,
Out put: "pets":["dog", cat"]
}
{person={pets=[dog, cat], age=33, name=Guillaume}}
}
{pets=[dog, cat], age=33, name=Guillaume}
cat
def test = context.expand( '${TestStep#Response}' )
Sample Response:
<quot:Customers>
<quot:Person>
<quot:CustomerType>PRIMARY</quot:CustomerType>
<quot:Sequence>0</quot:Sequence>
</quot:Person>
<quot:Person>
<quot:CustomerType>ADULT</quot:CustomerType>
<quot:Sequence>1</quot:Sequence>
</quot:Person>
</quot:Customers>

def numPersons =context.expand ('${TestStep#Response #count(//*:Customers/*:Person)}')


XML Parsing
def custRec = context.expand('${GetProductPriceOffer#Request}')
// parse the request
def xml = new XmlSlurper().parseText(custRec)
// find all elements in xml which tag name it's Person and return the list
def persons = xml.depthFirst().findAll { it.name() == 'Person' }
// here you've the number of persons
log.info persons.size()
Flow typing

void flowTyping() {
def o = 'foo'
o = o.toUpperCase()
o = 9d
o = Math.sqrt(o)
}
1. first, o is declared using def and assigned a String
2. the compiler inferred that o is a String, so calling toUpperCase is allowed
3. o is reassigned with a double
4. calling Math.sqrt passes compilation because the compiler knows that at this point, o is a double
Collections in Groovy
Collections
• List
//Declaring empty list Indexed elements
def myList = [] //literal syntax
• Map
• //Declaring empty map
def myList = [:] //literal syntax key value pairs
• Range
• def values=(1..10)
• Iterator it
List
• A list is an ordered collection of objects
List
• Defining an empy list :
def list=[] 5 6 7 8
def arrlist= [] as ArrayList
def list = [5, 6, 7, 8] index 3
0 1 2

• Indexing starts at 0

• Reference: http://docs.groovy-lang.org/docs/latest/html/groovy-jdk/java/util/List.html
Set
• A Set is a Collection that cannot contain duplicate elements.
• It models the mathematical set abstraction
• Set has following methods
• add( )
• clear()
• contains()
• isEmpty( )
• iterator( )
• remove( )
• size( )
Map
• A map contains values on the basis of key i.e. key and value pair.
• Each key and value pair is known as an entry.
• Map contains only unique keys(essentially it is a set).
• Useful Methods of Map
Method Description
Object put(Object key, Object value) It is used to insert an entry in this map.
void putAll(Map map) It is used to insert the specified map in this map.

Object remove(Object key) It is used to delete an entry for the specified


key.
Object get(Object key) It is used to return the value for the specified
key.
HashMap
• Java HashMap class implements the map interface by using a hashtable.
• It inherits AbstractMap class and implements Map interface.
• The important points about Java HashMap class are:
• A HashMap contains values based on the key.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
HashMap
• containsValue(Object value)
• boolean containsKey(Object key)
• void clear()
• boolean isEmpty()
• Object clone()
• Set keySet()
• Object put(Object key, Object value)
• int size()
• Collection values()
TreeMap
• Java TreeMap class implements the Map interface by using a tree. It
provides an efficient means of storing key/value pairs in sorted order.
• It implements the NavigableMap interface and extends AbstractMap
class.
• The important points about Java TreeMap class are:
• A TreeMap contains values based on the key.
• It contains only unique elements.
• It cannot have null key but can have multiple null values.
• It is same as HashMap instead maintains ascending order.
Linked HashMap
• Java LinkedHashMap class is Hash table and Linked list
implementation of the Map interface, with predictable iteration
order.
• It inherits HashMap class and implements the Map interface.
• The important points about Java HashMap class are:
• A LinkedHashMap contains values based on the key.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It is same as HashMap instead maintains insertion order.
Some Important Operations on List
• Joing List
def myList = ["Apple", "Banana", "Carrot"]
def joinResult = myList.join(",") AppleBananaCarrot
log.info joinResult
• Joing list with delimiter
def myList = ["Apple", "Banana", "Carrot"]
def joinResult = myList.join(",") Apple,Banana,Carrot
log.info joinResult
File IO

• http://docs.groovy-lang.org/docs/latest/html/groovy-
jdk/java/io/File.html
Closures in Groovy
References:
• http://groovy-lang.org/semantics.html#
• http://grails.asia/groovy-list-tutorial-and-examples
• http://www.beingjavaguys.com/2013/02/what-is-groovy-java-vs-groovy.html
• https://newcircle.com/bookshelf/java_fundamentals_tutorial/object_oriented#_java_memory
_model

Vous aimerez peut-être aussi