executeUpdate() not updating on grails spock-integration testing - grails

hi i am new to grails testing. Willing to do integration test as below but
problem is that executeUpdate() seems not updating the value
How to do integration testing for
executeUpdate('update query goes here') ??
Please help suggest me
Sample code is given for problem demo.
Thanks in advance.
def "for given merchantTier Id update merchantTier value"(){
setup:
def merchantTier = new MerchantTier(
value:1.11).save(flush: true) //it saves merchantTier
when:"when update with setProperty"
testData = editWithSetProperty(merchantTier.id) //id is passed
then:"it updates data and test is success"
merchantTier.value == 2.22
when:"executeUpdate query is used instead"
testData = editWithExecuteUpdate(merchantTier.id)// id is passed
then:"it does not update the data and test is failed"
merchantTier.value == 3.33
}
def editWithSetProperty(id) {
def merchantTier = MerchantTier.get(id.toLong())
merchantTier.setValue(2.22.toDouble())
}
def editWithExecuteUpdate(id) {
MerchantTier.executeUpdate('update MerchantTier mt set mt.value=:mrValue where mt.id=:mtId', [mrValue: 3.33.toDouble(), mtId: id.toLong()])
}
How to do integration testing for
executeUpdate('update query goes here') ??

as you are updating through executeUpdate you again need to fetch the object from database so try returning the fresh object fetched from database in editWithExecuteUpdate
def editWithExecuteUpdate(id) {
MerchantTier.executeUpdate('update MerchantTier mt set mt.value=:mrValue where mt.id=:mtId', [mrValue: 3.33.toDouble(), mtId: id.toLong()])
merchantTier = MerchantTier.get(id)
}
once done then you will have testData containing merchantTier object in when: clause
so in then: clause have
testData.value == 3.33
hope this make sense. Thanks
Edit - Additional Way
def editWithExecuteUpdate(id) {
def updatedRecords = MerchantTier.executeUpdate('update MerchantTier mt set mt.value=:mrValue where mt.id=:mtId', [mrValue: 3.33.toDouble(), mtId: id.toLong()])
return updatedRecords
}
so in then: clause have as due to executeUpdate only one row should be updated based on unique id and also fetch fresh object again and check the persisted value
testData == 1
def freshMerchantTier = MerchantTier.get(merchantTier.id)
freshMerchantTier.value == 3.33
Try this way once, please. Thanks

Related

Getting a second parameter based on the first parameter in Jenkins

I have a task where my Jenkins job needs two parameters for build. The first specifies the application name and can be either QA, Dev, Prod etc and the second is a server which is dependent on the first one.
Example: If I chose the app name as QA, the second parameter should display values like QAServer1, QAServer2, QAServer3.
I'm using Active Choices Plugin (https://wiki.jenkins.io/display/JENKINS/Active+Choices+Plugin) to get this done but facing an problem in fetching the second parameter contents.
Snapshots:
For obtaining the second parameter, I've written a Groovy code which reads the respective files of the selected first parameter and gets the details.
code:
#!/usr/bin/env groovy
import hudson.model.*
def Appliname = System.getenv("APPNAME")
//println Appliname
def list1 = []
def directoryName = "C:/Users/Dev/Desktop/JSONSTest"
def fileSubStr = Appliname
def filePattern = ~/${fileSubStr}/
def directory = new File(directoryName)
def findFilenameClosure =
{
if (filePattern.matcher(it.name).find())
{
def jsoname = it.name
def jsoname1 = jsoname.reverse().take(9).reverse()
list1.add(jsoname1.substring(1,4))
String listAsString = "[\'${list1.join("', '")}\']"
println "return"+listAsString
}
}
directory.eachFileRecurse(findFilenameClosure)
The above code will print the output as return['QAServer1', 'QAServer2'] which i want to use it as input for the second parameter.
Snapshot of Second parameter:
Somehow the Groovy script is not being executed and second parameter value remains empty. How can i get this done dynamically. Am i following the right away to it. Kindly help me figure out. TIA
Would you like to try below change
From:
def findFilenameClosure =
{
if (filePattern.matcher(it.name).find())
{
def jsoname = it.name
def jsoname1 = jsoname.reverse().take(9).reverse()
list1.add(jsoname1.substring(1,4))
String listAsString = "[\'${list1.join("', '")}\']"
println "return"+listAsString
}
}
directory.eachFileRecurse(findFilenameClosure)
To:
directory.eachFileRecurse {
if (filePattern.matcher(it.name).find()) {
def jsoname = it.name
def jsoname1 = jsoname.reverse().take(9).reverse()
list1.add(jsoname1.substring(1,4))
}
}
return list1

Grails 3 Cookie Plugin - return Null

i am trying to use cookie in grails 3.
i tried this plugin but i don't know why its not work at all..
cookieService.setCookie('username', customer?.email)
and i use this code for call it from gsp
<g:cookie name="username"/>
i also tried this way..
def cokusername = cookieService.setCookie('username', customer?.email)
println "cookieService.getCookie('username') = "+cookieService.getCookie('username')
redirect(controller: "toko",cokusername: cokusername)
and this is in my tokoController.groovy index :
def index={
def toko = CifLogo.executeQuery("from CifLogo order by rand()",[max: 10])
// def itemRandom = Item.executeQuery("from Item where cif = :cif order by rand()",[max:12,cif:cif])
def awdf = cookieService.getCookie('username')
println "awdf = "+awdf
println "cokusername = "+params.cokusername
[tokoList:toko,cokusername:awdf]
}
i have no idea to retrieve my cookie. :(
update
def index(){
def toko = CifLogo.executeQuery("from CifLogo order by rand()",[max: 10])
// def itemRandom = Item.executeQuery("from Item where cif = :cif order by rand()",[max:12,cif:cif])
def awdf = cookieService.getCookie('username')
println "awdf = "+awdf
println "cokusername = "+params.cokusername
[tokoList:toko,cokusername:awdf]
}
i tried to print cookie like this..
def awdf = request.getCookie('username')
println "awdf = "+awdf
println "cokusername = "+params.cokusername
request.cookies.each { println "${it.name} == ${it.value}" }
and this is what the result
From what I can see this line:
redirect(controller: "toko",cokusername: cokusername)
Should be:
redirect(controller: "toko",params:[cokusername: cokusername])
Also actions using closures in grails 3 will have undesired results. You should change to methods. Hence this line:
def index={
SHould be:
def index(){
Apart from this it seems the cookieService code should work fine, so I can only assume its being caused my the closure index that should be a method.
Another thing could be the fact that you are doing a redirect, which will clear the request and not persist any cookies that were set before the redirect
I don't know why, but maybe it's a bug.
i use this code to setCookie
cookieService.setCookie(name:"username", value: customer?.email, maxAge: 24*60*60, path: "/")
after read this code.
and i cannot deleteCookie with this code.
cookieService.deleteCookie(cookieService.findCookie("username"))
because when i print cookieService.findCookie("username") it returns javax.servlet.http.Cookie#78cbf320
and method deleteCookie(Cookie cookie) from this link
so i think it mustbe deleted.
but still availlable.
so i can answer this question about setCookie not deleteCookie
i also tried this way to delete cookie..but still failed.
CookieService.setCookie(name:"username", value: "", maxAge: 0, path: "/")

executeUpdate query not working on grails spock test

Now willing to do integration test as below but problem is that
MerchantTier.executeUpdate('update MerchantTier..........'),
here update does not working
but if I make update with
def merchant = MerchantTier.get(params.id.toLong())
merchant.setValue(merchantTierVal)
instead of execute update it works
Is there is any prolem with executeUpdate Query?
def merchantTier
def setup() {
merchantTier = new MerchantTier(
startTier: tier,
endTier: tier,
value: 2.02).save(flush: true)
}
void "for given merchantTierId update merchantTier"(){
setup:
params = [id:merchantTier.id,tierVal:2]
when:
testData = updateIndividualSuperResellerTier(params)
then:"return data"
merchantTier.value==params.tierVal
}
def updateIndividualSuperResellerTier(params) {
def merchantTierVal = 0
if (params.tierVal) {
merchantTierVal = params.tierVal.toDouble()
}
def merchantTier = MerchantTier.get(params.id.toLong())
def updateMerchantTier = MerchantTier.executeUpdate('update MerchantTier mt set mt.value=:mrValue where mt.id=:mtId', [mrValue: merchantTierVal, mtId: params.id.toLong()])
}
There seems to be no problem with executeUpdate, the problem here could be, that executeUpdate did not return an object, it just return the number of rows updated so updateMerchantTier doesnot contain updatedObject.
Also you should again fetch the object as it is updated by executeUpdate in your void "for given merchantTierId update merchantTier"() then: statement
then:"return data"
merchantTier.value==params.tierVal
here merchantTier is still an old object hence will not be having value equal to params.tierVal
in your other case you are using setter explicitly to set the property and hence it passed your Integration test.
def merchant = MerchantTier.get(params.id.toLong())
merchant.setValue(merchantTierVal)
hope this helps. Thanks

Remove current model instance from AR:Relation

I am creating an instance method on a model which returns instances of the same model. How can I ensure that the instance of the model that the method is being called upon is not part of the output?
My code is like this at the moment:
def other_versions(include_current = true)
if include_current
Coaster.where(order_ridden: order_ridden)
else
#coaster.other_version_count // Need this to exclude the current instance.
end
end
I'm not sure I understood, but would this help?
def other_versions(include_current = true)
query = Coaster.where(order_ridden: order_ridden)
query = query.where("id != ?", id) unless include_current
query
end

Checking if a collection is null or empty in Groovy

I need to perform a null or empty check on a collection; I think that !members?.empty is incorrect. Is there a groovier way to write the following?
if (members && !members.empty) {
// Some Work
}
There is indeed a Groovier Way.
if (members) {
//Some work
}
does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)
FYI this kind of code works (you can find it ugly, it is your right :) ) :
def list = null
list.each { println it }
soSomething()
In other words, this code has null/empty checks both useless:
if (members && !members.empty) {
members.each { doAnotherThing it }
}
def doAnotherThing(def member) {
// Some work
}
!members.find()
I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:
def lst1 = []
assert !lst1.find()
def lst2 = [null]
assert !lst2.find()
def lst3 = [null,2,null]
assert lst3.find()
def lst4 = [null,null,null]
assert !lst4.find()
def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42
def lst6 = null;
assert !lst6.find()

Resources