I was going to use Groovy's inspect() methods for quick and dirty object persistence but it didn't work as I expected. More specifically if I inspect() a list then list items are not inspect()ed but rather are toString()ed instead. Consider the following script:
class Foo {
String inspect() { 'new Foo()' }
}
assert new Foo().inspect() == 'new Foo()' // passes as expected
assert [new Foo()].inspect() == '[new Foo()]' // fails
Running this script produces the following output:
Assertion failed:
assert [new Foo()].inspect() == '[new Foo()]'
| | |
| | false
| [Foo#3d52315f]
Foo#3d52315f
at test.run(test.groovy:6)
meaning that inspect() on my Foo instance is never called. Is this a Groovy bug? I'm testing with Groovy 2.4.1.
Try in the following way:
class Foo {
String inspect() { 'new Foo()' }
}
assert new Foo().inspect() == 'new Foo()' // passes as expected
assert [new Foo()]*.inspect().toString() == '[new Foo()]'
You need to call inspect on every element of the list provided and then make to list inspectable itself. But indeed the behavior seems strange when it comes to the docs.
It seems that this is a bug. From DefaultGroovyMethods call to inspect() is redirected to InvokerHelper. Since you pass a collection (list) formatList method will be invoked. This method iterates over the list passed and calls format in the same class. Since formatdoesn't know about Foo it will call toString to the object passed (line 629).
The following example shows how it works:
class Foo {
String inspect() { 'new Foo()' }
String toString() { 'new Foo()' }
}
assert new Foo().inspect() == 'new Foo()'
assert [new Foo()].inspect() == '[new Foo()]'
Related
I would like to write a wrapper method for a webservice, the service accepts 2 mandatory and 3 optional parameters.
To have a shorter example, I would like to get the following code working
def myMethod(pParm1='1', pParm2='2') {
println "${pParm1}${pParm2}"
}
myMethod();
myMethod('a')
myMethod(pParm2:'a') // doesn't work as expected
myMethod('b','c')
The output is:
12
a2
[pParm2:a]2
a2
bc
What I would like to achieve is to give one parameter and get 1a as the result.
Is this possible (in the laziest way)?
Can't be done as it stands... The code
def myMethod(pParm1='1', pParm2='2'){
println "${pParm1}${pParm2}"
}
Basically makes groovy create the following methods:
Object myMethod( pParm1, pParm2 ) {
println "$pParm1$pParm2"
}
Object myMethod( pParm1 ) {
this.myMethod( pParm1, '2' )
}
Object myMethod() {
this.myMethod( '1', '2' )
}
One alternative would be to have an optional Map as the first param:
def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}
myMethod( 'a', 'b' ) // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd') // prints 'a b 1 2nd'
Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:
def someMethod(def args) {
println "MANDATORY1=${args.mandatory1}"
println "MANDATORY2=${args.mandatory2}"
println "OPTIONAL1=${args?.optional1}"
println "OPTIONAL2=${args?.optional2}"
}
someMethod mandatory1:1, mandatory2:2, optional1:3
with the output:
MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null
This looks nicer and the advantage of this is that you can change the order of the parameters as you like.
We can Deal with Optional parameters in 2 ways
Creating the method parameter with null values:
def generateReview(def id, def createDate=null) {
return new Review(id, createDate ?: new Date()) // ?: short hand of ternary operator
}
generateReview(id) // createDate is not passed
generateReview(id, createDate) // createDate is passed
Using Java Optional.of()
def generateReview(def id, Optional<Date> createDate) {
return new Review(id, createDate.isPresent() ? createDate.get() : new Date())
}
generateReview(id, Optional.empty()) // createDate is not passed
generateReview(id, Optional.of(createDate)) // createDate is passed
I created some mixin methods. Code and example below:
URL.metaClass.withCreds = { u, p ->
delegate.openConnection().tap {
setRequestProperty('Authorization', "Basic ${(u + ':' + p).bytes.encodeBase64()}")
}
}
URLConnection.metaClass.fetchJson = {
delegate.setRequestProperty('Accept', 'application/json')
delegate.connect()
def code = delegate.responseCode
def result = new JsonSlurper().parse(code >= 400 ? delegate.errorStream : delegate.inputStream as InputStream)
[
ok : code in (200..299),
body: result,
code: code
]
}
example usage:
new URL("$baseUrl/projects/$name").withCreds(u, p).fetchJson().find {
it.ok
}?.tap{
it.repos = getRepos(it.key).collectEntries { [(it.slug): it] }
}
}
When I dont use find(), my object is, as expected, a map with those 3 elements. When I use find it is a Map.Entry with key ok and value true
which produces this error:
groovy.lang.MissingPropertyException: No such property: ok for class: java.util.LinkedHashMap$Entry
Possible solutions: key
It occured to me when I wrote this post that it was treated the map as an iterable and thus looking at every entry which I have subsequently verified. How do I find on the whole map? I want it.ok because if it's true, I need to carry it forward
There is no such method in Groovy SDK. Map.find() runs over an entry set of the map you call method on. Based on expectation you have defined I'm guessing you are looking for a function that tests map with a given predicate and returns the map if it matches the predicate. You may add a function that does to through Map.metaClass (since you already add methods to URL and URLConnection classes). Consider following example:
Map.metaClass.continueIf = { Closure<Boolean> predicate ->
predicate(delegate) ? delegate : null
}
def map = [
ok : true,
body: '{"message": "ok"}',
code: 200
]
map.continueIf { it.ok }?.tap {
it.repos = "something"
}
println map
In this example we introduced a new method Map.continueIf(predicate) that tests if map matches given predicate and returns a null otherwise. Running above example produces following output:
[ok:true, body:{"message": "ok"}, code:200, repos:something]
If predicate is not met, map does not get modified.
Alternatively, for more strict design, you could make fetchJson() method returning an object with corresponding onSuccess() and onError() methods so you can express more clearly that you add repos when you get a successful response and optionally you create an error response otherwise.
I hope it helps.
How come I cannot declare an array of People in Groovy as shown.
Maybe I'm lacking the deeper understanding of classes
class People {
Integer id
}
class Job {
def func() {
People[] p = new People[10]
}
}
I get an error of People[] cannot be applied to app.People[]
The code sample you have shown does not reproduce the error you mentioned in the question above. It's broken actually and does not compile - method func() is missing its body. If you correct the code to e.g.
class People {
Integer id
}
class Job {
def func() {
People[] p = new People[10]
assert p.size() == 10
println p
}
}
new Job().func()
you will see it produces the expected result - check it out in the Groovy web console here. When you run it you will see following output to the console:
[null, null, null, null, null, null, null, null, null, null]
The difference between Groovy and Java
When it comes to array initialization there is one significant difference between Groovy and Java. In Java you can initialize an array of People[] like this:
People[] p = new People[] { new People(), new People(), /* ... */ new People() };
It wont work in Groovy, because Groovy reserves {} for closures. In Groovy you can initialize such array as:
People[] p = [new People(), new People(), new People()] as People[]
While Szymon Stepniak's answer is correct for Groovy 2.5 and below, Java-style array initialization are part of the enhancements of Groovy 3.0 and 2.6 made possible by the new parrot parser.
Example from the release notes:
def primes = new int[] {2, 3, 5, 7, 11}
assert primes.size() == 5 && primes.sum() == 28
assert primes.class.name == '[I'
def pets = new String[] {'cat', 'dog'}
assert pets.size() == 2 && pets.sum() == 'catdog'
assert pets.class.name == '[Ljava.lang.String;'
// traditional Groovy alternative still supported
String[] groovyBooks = [ 'Groovy in Action', 'Making Java Groovy' ]
assert groovyBooks.every{ it.contains('Groovy') }
Szymon Stepniak's answer is correct. I'll point another example of a real case in some unit test that I've worked (general Object type):
Object[] o = [YourModel] as Object[]
This is sufficient to mock a general Object with your model properties.
I would like to write a system groovy script which inspects the queued jobs in Jenkins, and extracts the build parameters (and build cause as a bonus) supplied as the job was scheduled. Ideas?
Specifically:
def q = Jenkins.instance.queue
q.items.each { println it.task.name }
retrieves the queued items. I can't for the life of me figure out where the build parameters live.
The closest I am getting is this:
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
it.task.properties.each { key, val ->
println(" ${key}=${val}")
}
}
This gets me this:
4.1.next-build-launcher:
com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty$ScannerJobPropertyDescriptor#b299407=com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty#5e04bfd7
com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty$DescriptorImpl#40d04eaa=com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty#16b308db
hudson.model.ParametersDefinitionProperty$DescriptorImpl#b744c43=hudson.mod el.ParametersDefinitionProperty#440a6d81
...
The params property of the queue element itself contains a string with the parameters in a property file format -- key=value with multiple parameters separated by newlines.
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
println("Parameters: ${it.params}")
}
yields:
dbacher params:
Parameters:
MyParameter=Hello world
BoolParameter=true
I'm no Groovy expert, but when exploring the Jenkins scripting interface, I've found the following functions to be very helpful:
def showProps(inst, prefix="Properties:") {
println prefix
for (prop in inst.properties) {
def pc = ""
if (prop.value != null) {
pc = prop.value.class
}
println(" $prop.key : $prop.value ($pc)")
}
}
def showMethods(inst, prefix="Methods:") {
println prefix
inst.metaClass.methods.name.unique().each {
println " $it"
}
}
The showProps function reveals that the queue element has another property named causes that you'll need to do some more decoding on:
causes : [hudson.model.Cause$UserIdCause#56af8f1c] (class java.util.Collections$UnmodifiableRandomAccessList)
In my work, I have methods to return closures as inputs for markup builders. So, for testing purposes, can we make an expected closure and assert the expected one equal to the one returned by one method? I tried the following code, but the assert failed.
a = {
foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
}
b = {
foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
}
assert a == b
I do not think it will be feasible to assert the closures even after calling them.
//Since you have Markup elements in closure
//it would not even execute the below assertion.
//Would fail with error on foo()
assert a() != b()
Using ConfigSlurper will give the error about input() since the closure does not represent a config script (because it is a Markup)
One way you can assert the behavior is by asserting the payload (since you have mentioned MarkupBuilder). That can be easily done by using XmlUnit as below(mainly Diff).
#Grab('xmlunit:xmlunit:1.4')
import groovy.xml.MarkupBuilder
import org.custommonkey.xmlunit.*
//Stub out XML in test case
def expected = new StringWriter()
def mkp = new MarkupBuilder(expected)
mkp.foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
/**The below setup will not be required because the application will
* be returning an XML as below. Used here only to showcase the feature.
* <foo>
* <bar>
* <input type='float' name='dum'>Another hello world</input>
* </bar>
* </foo>
**/
def real = new StringWriter()
def mkp1 = new MarkupBuilder(real)
mkp1.foo {
bar {
input( type : 'float', name : 'dum', 'Another hello world' )
}
}
//Use XmlUnit API to compare xmls
def xmlDiff = new Diff(expected.toString(), real.toString())
assert !xmlDiff.identical()
assert !xmlDiff.similar()
Above looks like a functional test, but I would go with this test unless otherwise there is an appropriate unit test to assert two markup closures.