Could not mock return value of service - grails

i have a problem with an controller test. I try to mock a return value of a service method, but it do not return a specific object and call the service method anyway.
The Test-Method:
def "shouldReturnStatus"() {
given:
controller.repairService.getRepair('123465') >> repair;
when:
controller.status();
then:
response.text == '{"currentStatus":"Repair was found.","repairFound":true}'
}
The repair mock is declared in the setup method.
The Controller-Method:
def status() {
String repairCode = params.repairCode;
if(repairCode == null || repairCode.isEmpty()) {
log.info("REPARATURSTATUSABFRAGE: Reparaturcode wurde nicht angegeben")
renderEmptyRepairCode();
} else if(repairService.getRepair(repairCode)) {
Repair repair = repairService.getRepair(repairCode);
if(repair) {
log.info("REPARATURSTATUSABFRAGE: Reparaturstatus mit Code " + repairCode + " erfolgreich ausgegeben.")
Customer customer = repair.getCustomer();
renderRepairStatus(repair, customer);
}
} else {
log.info("REPARATURSTATUSABFRAGE: Reparatur mit Code " + repairCode + " nicht gefunden.")
renderRepairNotFound(repairCode);
}
}
The repairService-Method:
def getRepair(String repairCode) {
Repair repair = Repair.findByRepairCode(repairCode);
if(repair == null) {
String upperCaseRepairCode = repairCode.toUpperCase();
repair = Repair.findByRepairCode(upperCaseRepairCode);
}
return repair;
}
I've mocked the repairService in the setup-Method
repairService = Mock(RepairService);
I think the code of the service method don't really matters, because I mocked the return value of this method. Or did i understand something wrong?

You need to modify your test:
def "shouldReturnStatus"() {
given:
controller.repairService = Mock(RepairService)
controller.repairService.getRepair('123465') >> repair
when:
controller.status();
then:
response.text == '{"currentStatus":"Repair was found.","repairFound":true}'
}
If I interpret your question right, you have created an instance variable inside your Spec, of type Mock(RepairService). That does not mean that your controller will use this mocked service. You need to actually assign it to the controller.

Related

Is there a way, in a list of jobs, to change a job's parameter to required?

I am using the script console of hudson and jenkins.
And I need make a parameter called "NAME" become required at the jobs where that parameter already exists. But I do not know any method that can help me.
def instance = hudson.model.Hudson.instance;
def allJobs = instance.getView("All");
allJobs.items.each {
if (it.containsParameter('NAME')){ /// this exists?
println(it.getName());
it.set??? /// what can I do?
}
}
I need that way for when someone excute the job the parameter "NAME" do not be empty or null.
you can get the desired result with below code:
def instance = hudson.model.Hudson.instance;
def allJobs = instance.getView("All");
allJobs.items.each {
prop = it.getProperty(ParametersDefinitionProperty.class)
if(prop != null) {
for(param in prop.getParameterDefinitions()) {
try {
if(param.name.equals('NAME')){
println(it.name + ":" + param.name + " " + param.defaultValue)
if(!param.defaultValue.trim()){
println("default value is blank")
}
}
}
catch(Exception e) {
println e
}
}
}
}

Redirect to external site does not terminate current execution flow

I'm using grails 1.3.7.
I have the following filter setup:
class MyFilters {
def userService
def springSecurityService
def filters = {
all(controller: '*', action: '*') {
before = {
String userAgent = request.getHeader('User-Agent')
int buildVersion = 0
// Match "app-/{version}" where {version} is the build number
def matcher = userAgent =~ "(?i)app(?:-\\w+)?\\/(\\d+)"
if (matcher.getCount() > 0)
{
buildVersion = Integer.parseInt(matcher[0][1])
log.info("User agent is from a mobile with build version = " + buildVersion)
log.info("User agent = " + userAgent)
String redirectUrl = "https://anotherdomain.com"
if (buildVersion > 12)
{
if (request.queryString != null)
{
log.info("Redirecting request to anotherdomain with query string")
redirect(url:"${redirectUrl}${request.forwardURI}?${request.queryString}",params:params)
}
return
}
}
}
after = { model ->
if (model) {
model['currentUser'] = userService.currentUser
}
}
afterView = {
}
}
}
}
A problem occurs in that the redirect does not happen at the point I would have thought.
I want all execution to stop and redirect to the exaact url I have given it at this point.
When i debug to the "redirect" line, it continues past this line exectuting other lines and jumping to another controller.
In order to prevent the normal processing flow from continuing, you need to return false from your before filter:
if (buildVersion > 12)
{
if (request.queryString != null)
{
log.info("Redirecting request to anotherdomain with query string")
redirect(url:"${redirectUrl}${request.forwardURI}?${request.queryString}",params:params)
return false
}
}
This is mentioned in passing at the very end of section 6.6.2 of the user guide, but it isn't particularly prominent:
Note how returning false ensure that the action itself is not executed.

Grails save() failure; can't figure out why

I am having a problem saving a Domain object. Below is my Controller code:
def onContactRequest = {
if(request.method == 'POST') {
if(User.findByUserTelephone(params.userTelephone)) {
User thisUser = User.findByUserTelephone(params.userTelephone)
Contact thisContact = new Contact()
thisContact.setContact(thisUser)
println("This Contact: " + thisContact.getContact());
thisContact.setBelongsTo(request.user)
println("This User: " + request.user)
if(thisContact.save(flush: true)) {
render(thisContact.belongsTo.userName + " just requested " + thisContact.getContact().userName )
} else {
render("There was a problem saving the Contact.")
if( !thisContact.save() ) {
thisContact.errors.each {
println it
}
}
}
} else {
User thisUser = new User()
thisUser.setUserName("Not Set")
thisUser.setUserTelephone(params.userTelephone)
thisUser.save()
Contact thisContact = new Contact()
thisContact.setContact(thisUser)
thisContact.setBelongsTo(request.user)
if(thisContact.save(flush: true)) {
render(thisContact.belongsTo.userName + " just requested " + thisContact.getContact().userName )
} else {
render("There was a problem saving the Contact.")
if( !thisContact.save() ) {
thisContact.errors.each {
println it + "\n"
}
}
}
}
} else {
}
The error message is printed with the following code; hence it's very ugly:
if( !thisContact.save() ) {
thisContact.errors.each {
println it + "\n"
}
}
From what I can tell, it's complaining that either the Contact or User instance is null; however that can't be true (look below)
This Contact: org.icc.callrz.User.User : 2
This User: org.icc.callrz.User.User : 1
Field 'user' in org.icc.callrz.Contact.Contact is:
static belongsTo = [
user: User
]
Error detail below:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'org.icc.callrz.Contact.Contact' on field 'user': rejected value [null]; codes [org.icc.callrz.Contact.Contact.user.nullable.error.org.icc.callrz.Contact.Contact.user,org.icc.callrz.Contact.Contact.user.nullable.error.user,org.icc.callrz.Contact.Contact.user.nullable.error.org.icc.callrz.User.User,org.icc.callrz.Contact.Contact.user.nullable.error,contact.user.nullable.error.org.icc.callrz.Contact.Contact.user,contact.user.nullable.error.user,contact.user.nullable.error.org.icc.callrz.User.User,contact.user.nullable.error,org.icc.callrz.Contact.Contact.user.nullable.org.icc.callrz.Contact.Contact.user,org.icc.callrz.Contact.Contact.user.nullable.user,org.icc.callrz.Contact.Contact.user.nullable.org.icc.callrz.User.User,org.icc.callrz.Contact.Contact.user.nullable,contact.user.nullable.org.icc.callrz.Contact.Contact.user,contact.user.nullable.user,contact.user.nullable.org.icc.callrz.User.User,contact.user.nullable,nullable.org.icc.callrz.Contact.Contact.user,nullable.user,nullable.org.icc.callrz.User.User,nullable]; arguments [user,class org.icc.callrz.Contact.Contact]; default message [Property [{0}] of class [{1}] cannot be null]
Edit: I have no problem creating Contact domain objects using the 'generate-all' code.
SOLUTION: I had a look at the code in the view, and it looked like to create the ID was used, so I changed the code to:
thisContact.user.id = request.user.id
However, then I got an error: java.lang.NullPointerException: Cannot set property 'id' on null object but the output of println request.user was not blank so I wasn't sure why that was appearing.
I then changed the offending line to:
thisContact.user = request.user
Now everything is working. :)
Try replacing:
thisContact.setBelongsTo(request.user)
With:
thisContact.user = thisUser
The syntax you are using is wrong as far as I know, not to mention that you construct thisUser and then go on to use request.user instead.

return not working in service

I am getting a wierd problem and i am stuck on it for atleast 4 hours now. Actually i had written my code in a controller for testing but when i have moved the code to service i am getting a strange behaviour that the methods in service are not returning or may be methods that are calling them in the service only are not receiving .
class FacebookService implements InitializingBean, GroovyInterceptable {
def getUserLikes(def at){
List<String> listOfUrls = []
String basicFbUrl = "https://graph.facebook.com/"
String likeUrl = basicFbUrl + "me/likes?access_token=${at}"
URL url = new URL(likeUrl)
String jsonResponse = getResponseFromUrl(url)
println "JSON RESPONSE IS ${jsonResponse}" // this is showing null
}
String getResponseFromUrl() {
String something
String resp = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
int respCode = conn.responseCode
if (respCode == 400) {
log.error("COULD NOT MAKE CONNECTION")
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
def jsonResp = JSON.parse(br.text)
} else {
resp = conn.getInputStream().getText()
}
} finally {
conn.disconnect()
}
println("RETURNIG RESPONSE ${resp}") // This returns me a map as expected
return resp;
}
Dont know where does resp goes ?? any suggestions please ??
OK i know the culprit , i am posting the code of invokeMethod
def invokeMethod(String name, args){
System.out.println("IN INVOKE METHOD NAME ${name}")
if(facebookPalsCache==null)
facebookPalsCache = new FacebookPalsCache(1000)
System.out.println("time before ${name} called: ${new Date()}")
//Get the method that was originally called.
def calledMethod = metaClass.getMetaMethod(name, args)
System.out.println("CALLED METHOD IS ${calledMethod}")
//The "?" operator first checks to see that the "calledMethod" is not
//null (i.e. it exists).
if(name.equals("getFriends")){
println "getFriends..."
def session = RequestContextHolder.currentRequestAttributes().getSession()
def friends = facebookPalsCache.get(session.facebook.uid)
if(!friends){
def getFriends = facebookGraphService.invokeMethod (name, args)
println "Saving FBFRIENDS in CACHE"
facebookPalsCache.put(session.facebook.uid, getFriends)
return getFriends
}
else return friends
}
else {
if(calledMethod){
System.out.println("IN IF AND INVOKING METHOD ${calledMethod}")
calledMethod.invoke(this, args)
}
else {
return facebookGraphService.invokeMethod(name, args)
}
}
System.out.println "RETURNING FROM INVOKE METHOD FOR NAME ${name}"
System.out.println("time after ${name} called: ${new Date()}\n")
}
OK SOMETHING IS WRONG ABOVE I DONT KNOW WHAT CAN ANYONE PLEASE HELP ??
The code for invokeMethod and the service don't seem to be the same unless there's a separate FacebookGraphService. Assuming that's the case, then the resp is being caught in the part of your invokeMethod that's inside the if (calledMethod) { block, but since it's not the last line of the method it's not being returned from the call to invokeMethod and therefore is being gobbled up.
Try adding a return to calledMethod.invoke(this, args):
if(calledMethod){
System.out.println("IN IF AND INVOKING METHOD ${calledMethod}")
return calledMethod.invoke(this, args)
}

removeFrom* not working and with no errors

I have what I think is a simple problem but have been unable to solve...
For some reason I have a controller that uses removeFrom*.save() which throws no errors but does not do anything.
Running
Grails 1.2
Linux/Ubuntu
The following application is stripped down to reproduce the problem...
I have two domain objects via create-domain-class
- Job (which has many notes)
- Note (which belongs to Job)
I have 3 controllers via create-controller
- JobController (running scaffold)
- NoteController (running scaffold)
- JSONNoteController
JSONNoteController has one primary method deleteItem which aims to remove/delete a note.
It does the following
some request validation
removes the note from the job - jobInstance.removeFromNotes(noteInstance).save()
deletes the note - noteInstance.delete()
return a status and remaining data set as a json response.
When I run this request - I get no errors but it appears that jobInstance.removeFromNotes(noteInstance).save() does nothing and does not throw any exception etc.
How can I track down why??
I've attached a sample application that adds some data via BootStrap.groovy.
Just run it - you can view the data via the default scaffold views.
If you run linux, from a command line you can run the following
GET "http://localhost:8080/gespm/JSONNote/deleteItem?job.id=1&note.id=2"
You can run it over and over again and nothing different happens. You could also paste the URL into your webbrowser if you're running windows.
Please help - I'm stuck!!!
Code is here link text
Note Domain
package beachit
class Note
{
Date dateCreated
Date lastUpdated
String note
static belongsTo = Job
static constraints =
{
}
String toString()
{
return note
}
}
Job Domain
package beachit
class Job
{
Date dateCreated
Date lastUpdated
Date createDate
Date startDate
Date completionDate
List notes
static hasMany = [notes : Note]
static constraints =
{
}
String toString()
{
return createDate.toString() + " " + startDate.toString();
}
}
JSONNoteController
package beachit
import grails.converters.*
import java.text.*
class JSONNoteController
{
def test = { render "foobar test" }
def index = { redirect(action:listAll,params:params) }
// the delete, save and update actions only accept POST requests
//static allowedMethods = [delete:'POST', save:'POST', update:'POST']
def getListService =
{
def message
def status
def all = Note.list()
return all
}
def getListByJobService(jobId)
{
def message
def status
def jobInstance = Job.get(jobId)
def all
if(jobInstance)
{
all = jobInstance.notes
}
else
{
log.debug("getListByJobService job not found for jobId " + jobId)
}
return all
}
def listAll =
{
def message
def status
def listView
listView = getListService()
message = "Done"
status = 0
def response = ['message': message, 'status':status, 'list': listView]
render response as JSON
}
def deleteItem =
{
def jobInstance
def noteInstance
def message
def status
def jobId = 0
def noteId = 0
def instance
def listView
def response
try
{
jobId = Integer.parseInt(params.job?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in jobId " + params.job?.id)
log.debug(ex.getMessage())
}
if (jobId && jobId > 0 )
{
jobInstance = Job.get(jobId)
if(jobInstance)
{
if (jobInstance.notes)
{
try
{
noteId = Integer.parseInt(params.note?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in noteId " + params.note?.id)
log.debug(ex.getMessage())
}
log.debug("note id =" + params.note.id)
if (noteId && noteId > 0 )
{
noteInstance = Note.get(noteId)
if (noteInstance)
{
try
{
jobInstance.removeFromNotes(noteInstance).save()
noteInstance.delete()
message = "note ${noteId} deleted"
status = 0
}
catch(org.springframework.dao.DataIntegrityViolationException e)
{
message = "Note ${noteId} could not be deleted - references to it exist"
status = 1
}
/*
catch(Exception e)
{
message = "Some New Error!!!"
status = 10
}
*/
}
else
{
message = "Note not found with id ${noteId}"
status = 2
}
}
else
{
message = "Couldn't recognise Note id : ${params.note?.id}"
status = 3
}
}
else
{
message = "No Notes found for Job : ${jobId}"
status = 4
}
}
else
{
message = "Job not found with id ${jobId}"
status = 5
}
listView = getListByJobService(jobId)
} // if (jobId)
else
{
message = "Couldn't recognise Job id : ${params.job?.id}"
status = 6
}
response = ['message': message, 'status':status, 'list' : listView]
render response as JSON
} // deleteNote
}
I got it working... though I cannot explain why.
I replaced the following line in deleteItem
noteInstance = Note.get(noteId)
with the following
noteInstance = jobInstance.notes.find { it.id == noteId }
For some reason the jobInstance.removeFromNotes works with the object returned by that method instead of .get
What makes it stranger is that all other gorm functions (not sure about the dynamic ones actually) work against the noteInstance.get(noteId) method.
At least it's working though!!
See this thread: http://grails.1312388.n4.nabble.com/GORM-doesn-t-inject-hashCode-and-equals-td1370512.html
I would recommend using a base class for your domain objects like this:
abstract class BaseDomain {
#Override
boolean equals(o) {
if(this.is(o)) return true
if(o == null) return false
// hibernate creates dynamic subclasses, so
// checking o.class == class would fail most of the time
if(!o.getClass().isAssignableFrom(getClass()) &&
!getClass().isAssignableFrom(o.getClass())) return false
if(ident() != null) {
ident() == o.ident()
} else {
false
}
}
#Override
int hashCode() {
ident()?.hashCode() ?: 0
}
}
That way, any two objects with the same non-null database id will be considered equal.
I just had this same issue come up. The removeFrom function succeeded, the save succeeded but the physical record in the database wasn't deleted. Here's what worked for me:
class BasicProfile {
static hasMany = [
post:Post
]
}
class Post {
static belongsTo = [basicProfile:BasicProfile]
}
class BasicProfileController {
...
def someFunction
...
BasicProfile profile = BasicProfile.findByUser(user)
Post post = profile.post?.find{it.postType == command.postType && it.postStatus == command.postStatus}
if (post) {
profile.removeFromPost(post)
post.delete()
}
profile.save()
}
So it was the combination of the removeFrom, followed by a delete on the associated domain, and then a save on the domain object.

Resources