Académique Documents
Professionnel Documents
Culture Documents
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
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().
• 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’
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>
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.
• 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