spock test for a service in grails - grails

I have a service in my application which return a list of tracks, here is the code for that
List<Track> getTrackListTracks(String listName, int max) {
def tracks = getTrackListTracks(listName)
if(tracks?.size() > max) {
tracks = tracks[0 ..< max]
}
return tracks
}
List<Track> getTrackListTracks(String listName) {
def tl = TrackList.findByName(listName)
if(tl?.tracks) {
return tl?.tracks?.collect { Track.read(it.trackId) }
}
}
i have to write the unit test for this but I am not able to write. Can anyone help me in this.
Thanks Already

Hopefully you've progressed beyond this, but for those coming after, the grails-spock-examples project # google code (https://github.com/pschneider-manzell/grails-spock-examples) has a wide range of examples.
More specifically, for a service (as you've asked), check out Testing Services.
Caution, though - there are a few differences between that and what is required for Grails 2. For example, if testing controllers, 'redirectArgs' is no longer valid. Make sure to also consult the Grails Documentation for differences.

Related

accessing transition history via JIRA REST API

I found another person apparently having this issue but I thought I'd re-ask the question to see if I could make it more explicit.
I'm using the JIRA 6 REST web API and successfully pulling lots of data that matches our web cloud UI.
Now I'd like to see the transitions a given issue has been thru, preferably with info about who performed the transition.
I can see this transition history in our JIRA web UI but I haven't figured out how to access programmatically yet.
There's a promising sounding API:
http://example.com:8080/jira/rest/api/2/issue/{issueIdOrKey}/transitions [GET, POST]
And this is the API the previous asker seemed to have been using. From what I can tell it only returns the valid transitions you can ask for on the issue at a given point in time.
I would like a history of transitions, such as when the issue went to code review, QA, closed, etc.
I have done a expand=changelog but the change log does not correlate with the transitions that I can see.
Any tips would be appreciated. Thanks.
When you use expand=changelog, then all changes that have been done in issue are there. Exactly same info as in All tab in Activity section when viewing in web browser.
When I send:
http://jira.my.server.se/rest/api/2/issue/KEYF-42346?expand=changelog
Under changelogkey I find list of histories. Each historyhas list of items. Those items are changes performed on the certain field, with to and from values.
To find all status changes you need to do something like this:
for history in issue.changelog.histories:
for item in history.items:
if item.field == "status":
print item.toString # new value
print item.fromString # old value
Or use GET /rest/api/3/issue/{issueIdOrKey}/changelog like explained in the "get changelog" docs
You can try using the jql parameter for the REST API call.
So your call for,
JQL = project=XYZ and status was resolved
fields = key
will look like this,
http://example.com/rest/api/2/search?jql=project%3DXYZ%20and%20status%20was%20resolved&fields=key
where key will return only relevant information and not excessive for each issue.
public void changeStatus(IssueRestClient iRestClient,
List<Statuses> JiraStatuses, String key) {
String status = "To Do";
for (Statuses statuses : vOneToJiraStatuses) {
if (1 == statuses.compareTo(status)) {
try {
String _transition = statuses.getTransition();
Issue issue = iRestClient.getIssue(key).get();
Transition transition = getTransition(iRestClient, issue,
_transition);
if (!(isBlankOrNull(transition))) {
if (!(issue.getStatus().getName()
.equalsIgnoreCase(_transition)))
transition(transition, issue, null, iRestClient,
status);
}
} catch (Exception e) {
Constants.ERROR.info(Level.INFO, e);
}
break;
}
}
}
List is a pojo implementation where statuses and transitions defined in xml are injected through setter/constructor.
private void transition(Transition transition, Issue issue,
FieldInput fieldInput, IssueRestClient issueRestClient,
String status) throws Exception {
if (isBlankOrNull(fieldInput)) {
TransitionInput transitionInput = new TransitionInput(
transition.getId());
issueRestClient.transition(issue, transitionInput).claim();
Constants.REPORT.info("Status Updated for : " + issue.getKey());
} else {
TransitionInput transitionInput = new TransitionInput(
transition.getId());
issueRestClient.transition(issue, transitionInput).claim();
Constants.REPORT.info("Status Updated for : " + issue.getKey());
}
}
public Transition getTransition(IssueRestClient issueRestClient,
Issue issue, String _transition) {
Promise<Iterable<Transition>> ptransitions = issueRestClient
.getTransitions(issue);
Iterable<Transition> transitions = ptransitions.claim();
for (Transition transition : transitions) {
if (transition.getName().equalsIgnoreCase(_transition)) {
return transition;
}
}
return null;
}
In Short using Transition API of JIRA we can fetch all the transitions to set statuses

BatchInserters.batchDatabase fails - sometimes - silently to persist node properties

I use BatchInserters.batchDatabase to create an embedded Neo4j 2.1.5 data base. When I only put a small amount of data in it, everything works fine.
But if I increase the size of data put in, Neo4j fails to persist the latest properties set with setProperty. I can read back those properties with getProperty before I call shutdown. When I load the data base again with new GraphDatabaseFactory().newEmbeddedDatabase those properies are lost.
The strange thing about this is that Neo4j doesn't report any error or throw an exception. So I have no clue what's going wrong or where. Java should have enough memory to handle both the small data base (Database 2.66 MiB, 3,000 nodes, 3,000 relationships) and the big one (Database 26.32 MiB, 197,267 nodes, 390,659 relationships)
It's hard for me to extract a running example to show you the problem, but I can do if this helps. Here the main steps I do though:
def createDataBase(rules: AllRules) {
// empty the data base folder
deleteFileOrDirectory(new File(mainProjectPathNeo4j))
// Create an index on some properties
db = new GraphDatabaseFactory().newEmbeddedDatabase(mainProjectPathNeo4j)
engine = new ExecutionEngine(db)
createIndex()
db.shutdown()
// Fill the data base
db = BatchInserters.batchDatabase(mainProjectPathNeo4j)
//createBatchIndex
try {
// Every function loads some data
loadAllModulesBatch(rules)
loadAllLinkModulesBatch(rules)
loadFormalModulesBatch(rules)
loadInLinksBatch()
loadHILBatch()
createStandardLinkModules(rules)
createStandardLinkSets(rules)
// validateModel shows the problem
validateModel(rules)
} catch {
// I want to see if my environment (BIRT) is catching any exceptions
case _ => val a = 7
} finally {
db.shutdown()
}
}
validateModel is updating some properties of already created nodes
def validateModule(srcM: GenericModule) {
srcM.node.setProperty("isValidated", true)
assert(srcM.node == Neo4jScalaDataSource.testNode)
assert(srcM.node eq Neo4jScalaDataSource.testNode)
assert(srcM.node.getProperty("isValidated").asInstanceOf[Boolean])
When I finally use Cypher to get some data back
the properties set by validateModel are missing
class Neo4jScalaDataSet extends ScriptedDataSetEventAdapter {
override def beforeOpen(...) {
result = Neo4jScalaDataSource.engine.profile(
"""
MATCH (fm:FormalModule {isValidated: true}) RETURN fm.fullName as fullName, fm.uid as uid
""");
iter = result.iterator()
}
override def fetch(...) = {
if (iter.hasNext()) {
for (e <- iter.next().entrySet()) {
row.setColumnValue(e.getKey(), e.getValue())
}
count += 1;
row.setColumnValue("count", count)
return true
} else {
logger.log(Level.INFO, result.executionPlanDescription().toString())
return super.fetch(dataSet, row)
}
}
batchDatabase indeed causes this problem.
I have switched to BatchInserters.inserter and now everything works just fine.

Dart HttpRequest polling

I have a web app that have a Timer that fires a poll to get data every 3 seconds. It works fine for about 2.5 minutes then Chromium crashes.
My request Dart looks like this
HttpRequest.getString('data/get_load_history_recent.json')
.then((e) => _recentHistoryResponse(e))
.catchError((e) => _recentHistoryError(e));
Can you think of any reasons why this would happen? I assume it's a memory leak...
Edit:
Here is my _recentHistoryResponse()
void _recentHistoryResponse(String data)
{
Map obj = JSON.decode(data);
if(obj['status'] == 'success')
{
List processes = obj['data']['processes'];
List newItems = new List();
List oldIdsArray = new List();
int length = appDataDic.load_history_list.length;
for(HistoryDataVO oldVO in appDataDic.load_history_list)
{
oldIdsArray.add(oldVO.loadID);
}
for(Map process in processes)
{
HistoryDataVO dataVO = new HistoryDataVO();
dataVO.loadID = process['loadID'];
dataVO.time = process['time'];
dataVO.loadType = process['loadType'];
dataVO.fileName = process['fileName'];
dataVO.label = process['label'];
dataVO.description = process['description'];
dataVO.count = process['count'];
dataVO.progress = process['progress'];
dataVO.loadTask = process['loadTask'];
// Check if the item is currently in the list
if(length >= 1)
{
if(!LoadHistoryHelper.exists(oldIdsArray, dataVO.loadID))
{
dataVO.isNew = true;
}
}
newItems.add(dataVO);
}
appDataDic.load_history_list.clear();
appDataDic.load_history_list.addAll(newItems);
}
}
I have commented out the exists check !LoadHistoryHelper.exists(oldIdsArray, dataVO.loadID)) (because this seemed like the obvious place) but it the VM still crashes.
Also, I have taken this same code and put it into an isolated app with the only real difference in the poll check is appDataDic.load_history_list is just an #observable List, not an ObservableList.
Edit 2 :
Ok, so I have discovered that Map obj = JSON.decode(data); causes the crash. I was reading in a Javascript forum that timeouts cause the memory to not be released (I had never thought of this but it makes sense), is this true? Can any one think of a better way to do this? Can I directly call the garbage collection? I'm running out of ideas.
There's another question here, suggesting a memory leak in HttpRequest; however I'm not able to find anything in the Dart issue tracker. If you think this might be a real memory leak, it might be worth raising a bug.

neo4j 2.0 findNodesByLabelAndProperty not working

I'm currently trying the Neo4j 2.0.0 M3 and see some strange behaviour. In my unit tests, everything works as expected (using an newImpermanentDatabase) but in the real thing, I do not get results from the graphDatabaseService.findNodesByLabelAndProperty.
Here is the code in question:
ResourceIterator<Node> iterator = graphDB
.findNodesByLabelAndProperty(Labels.User, "EMAIL_ADDRESS", emailAddress)
.iterator();
try {
if (iterator.hasNext()) { // => returns false**
return iterator.next();
}
} finally {
iterator.close();
}
return null;
This returns no results. However, when running the following code, I see my node is there (The MATCH!!!!!!!!! is printed) and I also have an index setup via the schema (although that if I read the API, this seems not necessary but is important for performance):
ResourceIterator<Node> iterator1 = GlobalGraphOperations.at(graphDB).getAllNodesWithLabel(Labels.User).iterator();
while (iterator1.hasNext()) {
Node result = iterator1.next();
UserDao.printoutNode(emailAddress, result);
}
And UserDao.printoutNode
public static void printoutNode(String emailAddress, Node next) {
System.out.print(next);
ResourceIterator<Label> iterator1 = next.getLabels().iterator();
System.out.print("(");
while (iterator1.hasNext()) {
System.out.print(iterator1.next().name());
}
System.out.print("): ");
for(String key : next.getPropertyKeys()) {
System.out.print(key + ": " + next.getProperty(key).toString() + "; ");
if(emailAddress.equals( next.getProperty(key).toString())) {
System.out.print("MATCH!!!!!!!!!");
}
}
System.out.println();
}
I already debugged through the code and what I already found out is that I pass via the InternalAbstractGraphDatabase.map2Nodes to a DelegatingIndexProxy.getDelegate and end up in IndexReader.Empty class which returns the IteratorUtil.EMPTY_ITERATOR thus getting false for iterator.hasNext()
Any idea's what I am doing wrong?
Found it:
I only included neo4j-kernel:2.0.0-M03 in the classpath. The moment I added neo4j-cypher:2.0.0-M03 all was working well.
Hope this answer helps save some time for other users.
#Neo4j: would be nice if an exception would be thrown instead of just returning nothing.
#Ricardo: I wanted to but I was not allowed yet as my reputation wasn't good enough as a new SO user.

Block JS with Firefox Addon

im developing a little firefox addon with the addon-sdk provided by mozilla. The addon should work on only one specific website and it needs to block a js-file from this website. I'm searching for hours on how to block such a request.
Hopefully someone knows the answer
Yeah, you'd have to do this mostly by hand. The SDK isn't going to help you much at all here but it is somewhat possible.
This is along the lines of what you'd need to do. Note that this isn't tested and won't work out of the box but just to give you an idea of what components are involved and where to find more resources.
const { Cc, Ci, Cm, components } = require("chrome");
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
const CategoryManager = Cc["#mozilla.org/categorymanager;1"]
.getService(Ci.nsICategoryManager);
function PolicyComponent() { }
PolicyComponent.prototype = {
desc: "My nsIContentPolicy XPCOM Component",
classID: components.ID("{3ffd2f60-3784-11e1-b86c-0800200c9a66}"),
contractID: "#abc.def.com/policycomp;1",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPolicy]),
shouldLoad: function(contentType, contentLocation, requestOrigin, aContext, mimeTypeGuess, extra) {
if (contentLocation.spec != BLOCKED_JS) { return return Ci.nsIContentPolicy.ACCEPT; }
else { return Ci.nsIContentPolicy.REJECT_REQUEST; }
},
shouldProcess: function() {
return CI.nsIContentPolicy.ACCEPT;
}
}
var pc = new PolicyComponent()
// Register the Interface
Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory(pc.uuid, pc.desc, pc.contractID, pc);
// Add the content policy
CategoryManager.addCategoryEntry("content-policy",pc.className,pc.contractID, true, true); // not sure you should replace (last true statement)
See this post for more:
What is missing in my nsIContentPolicy Firefox/IceWeasel extension XPCOMponent implementation for the shouldLoad to be called?
Also take a look at these docs: https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads#Content_Policy

Resources