How to add a test step in HP QC from Java - java

I am trying to access and modify test cases in HP QC by JAVA. The code is running successfully but the Step, status, Exec dates are not being updated.
Here is my code
for (Com4jObject obj : testInstances)
{
ITSTest testInstance = obj.queryInterface(ITSTest.class);
ITSTest tstest = obj.queryInterface(ITSTest.class);
IRunFactory runfactory = tstest.runFactory().queryInterface(IRunFactory.class);
IRun run=runfactory.addItem("RunNew").queryInterface(IRun.class);
Com4jObject step = run.stepFactory();
// run.field("Step #", "Step1");
run.status("Passed");
// Com4jObject steps = run.stepFactory();
// System.out.println(run.field("Actual Result"));
// run.field("Actual Result", "As Expected. Please find attachment with TC001");
if(tstest.name().contains("[1]TC001"))
{
try {
String fileName = new File(files.get(i)).getName();
String folderName = new File(files.get(i)).getParent();
System.out.println("FILE: "+fileName);
System.out.println("FOLDER: "+folderName);
IAttachmentFactory attachfac = tstest.attachments().queryInterface(IAttachmentFactory.class);
IAttachment attach = attachfac.addItem(fileName).queryInterface(IAttachment.class);
IExtendedStorage extAttach = attach.attachmentStorage().queryInterface(IExtendedStorage.class);
extAttach.clientPath(folderName);
extAttach.save(fileName, true);
//attach.description(Actual);
attach.post();
attach.refresh();
} catch(Exception e) {
System.out.println("QC Exceptione : "+e.getMessage());
}
}
run.post();
//AppLog.info(" Test Instance: %s", testInstance.name());
System.out.println(("Test Instance: %s"+ testInstance.name()));
}

You need to call post() on each item separately: Test run and each created step.
Example in C# starting from the point where you retrieve the step factory.
// Create test run
var oRunInstance = (QcClient.RunFactory)oTsTest.RunFactory;
var oRun = (QcClient.Run)oRunInstance.AddItem("Performance Test");
oRun.Status = "Passed";
oRun.Post();
oRun.Refresh();
// Create test run steps
var oTest = (QcClient.Test)oTsTest.Test;
var tsDesignStepList = oTest.DesignStepFactory.NewList("");
var oStepFactory = (QcClient.StepFactory)oRun.StepFactory;
foreach (QcClient.DesignStep oDesignStep in tsDesignStepList)
{
var oStep = (QcClient.Step)oStepFactory.AddItem(oDesignStep.StepName);
oStep.Status = "Passed";
oStep.Post();
}

Related

Rally Java: Duplicate test case getting created

I have built a Rally dependency, which auto creates test case, folder in Test Plan. While creating test case it checks first if there any any existing test case with same name, else it creates new test case.
This was working while total test case size was small, while the test case size increased, i am seeing duplicate test cases are created. So I made thread to wait for few seconds (Thread.sleep(8000)) after checking existing scenarios and then creating new scenario. It works by this way.
Is there better way to handle & implement this to handle any size of test case. Please advice.
String tcName = rallyMethods.getTestScenarios(parentFolder, scenarioName);
Thread.sleep(8000);
if (tcName == null) {
rallyMethods.createTestCase(parentFolder, scenarioName);
Thread.sleep(8000);
} else {
rallyMethods.updateTestCase(parentFolder, scenarioName);
Thread.sleep(8000);
}
public String getTestScenarios(String parentFolderName, String ScenarioName) throws Throwable {
String sName = null;
String pFolder;
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setLimit(Integer.MAX_VALUE);
testCaseRequest.setPageSize(Integer.MAX_VALUE);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "Workspace", "Project", "TestFolder"));
testCaseRequest.setQueryFilter(new QueryFilter("Name", "=", ScenarioName));
testCaseRequest.setWorkspace(WORKSPACE_ID);
testCaseRequest.setProject(PROJECT_ID);
QueryResponse testCaseQueryResponse = query(testCaseRequest);
int testCaseCount = testCaseQueryResponse.getTotalResultCount();
// System.out.println("TestCaseCount:" + testCaseCount);
for (int i = 0; i < testCaseCount; i++) {
JsonObject scenarioObj = testCaseQueryResponse.getResults().get(i).getAsJsonObject();
String scenarioName = String.valueOf(scenarioObj.get("Name").getAsString());
JsonElement pFolderObj = scenarioObj.get("TestFolder");
if (!(pFolderObj.isJsonNull())) {
JsonObject tFolderObj = scenarioObj.get("TestFolder").getAsJsonObject();
pFolder = String.valueOf(tFolderObj.get("Name").getAsString());
if (parentFolderName.equalsIgnoreCase(pFolder)) {
sName = scenarioName;
logger.info("Test Scenarios identified in Rally: " + sName);
} else {
logger.info("Scenario, " + ScenarioName + " not found, New Scenario will be created in Rally");
}
}
}
return sName;
}
public void createTestCase(String parentFolderName, String testCaseName) throws Throwable {
String tcName = null;
String userID = readUser();
// Query Child Folders:
QueryRequest testFolderRequest = new QueryRequest("TestFolder");
testFolderRequest.setFetch(new Fetch("Name", "Workspace", "Project"));
testFolderRequest.setQueryFilter(new QueryFilter("Name", "=", parentFolderName));
testFolderRequest.setWorkspace(WORKSPACE_ID);
testFolderRequest.setProject(PROJECT_ID);
QueryResponse testFolderQueryResponse = query(testFolderRequest);
int folderCount = testFolderQueryResponse.getTotalResultCount();
for (int i = 0; i < folderCount; i++) {
String testFolderRef = testFolderQueryResponse.getResults().get(i).getAsJsonObject().get("_ref").getAsString();
JsonObject testFolderObj = testFolderQueryResponse.getResults().get(i).getAsJsonObject();
String pFolder = String.valueOf(testFolderObj.get("Name").getAsString());
if (pFolder.equalsIgnoreCase(parentFolderName)) {
//System.out.println("Creating a test case...");
JsonObject newTC = new JsonObject();
newTC.addProperty("Name", testCaseName);
newTC.addProperty("Workspace", WORKSPACE_ID);
newTC.addProperty("Project", PROJECT_ID);
newTC.addProperty("Description", "Selenium Automated TestCase");
newTC.addProperty("TestFolder", testFolderRef);
newTC.addProperty("Method", "Automated");
newTC.addProperty("Type", "Functional");
if (!(userID == null)) {
newTC.addProperty("Owner", userID);
}
CreateRequest createRequest = new CreateRequest("testcase", newTC);
CreateResponse createResponse = create(createRequest);
if (createResponse.wasSuccessful()) {
JsonObject tcObj = createResponse.getObject();
tcName = String.valueOf(tcObj.get("Name").getAsString());
logger.info("Created test scenario name is: " + tcName);
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
logger.info("Error while creating test scenario below parent folder!");
for (int j = 0; j < createErrors.length; j++) {
System.out.println(createErrors[j]);
logger.info(createErrors[j]);
}
}
}
}
}
Hmmm... I'm not too familiar with the Java REST toolkit, but I can't think of a reason why a larger set of test cases in the workspace would cause the query to fail like that.
Did you try checking testCaseQueryResponse.wasSuccessful()? If it returns false, can you see what the error is? testCaseQueryResponse.getErrors()
My first thoughts are that you should provide a reasonable value for the limit and pageSize parameters, rather than passing Integer.MAX_VALUE. And second, rather than checking if the returned test cases are in the specified parent folder, you should include a query filter to filter the test cases results on TestFolder.Name = parentFolderName. Then you should only be expecting either 1 or 0 results returned (assuming that you're expecting all test cases within a test folder to have unique names).

IF/ELSE conditions on Spark / JAVA

I'm trying to run the following code:
for (java.util.Iterator<Row> iter = dataframe1.toLocalIterator(); iter.hasNext();) {
Row it = (iter.next());
String item = it.get(2).toString();
String rayon = it.get(6).toString();
Double d = Double.parseDouble(rayon)/100000;
String geomType = it.get(14).toString();
Dataset<Row> res_f = null;
if(geomType.equalsIgnoreCase("Polygon")) {
res_f= dataframe2.withColumn("ST_WITHIN",expr("ST_WITHIN(ST_GeomFromText(CONCAT('POINT(',longitude,' ',latitude,')',4326)),ST_GeomFromWKT('"+item+"'))"));
} else {
res_f = dataframe2.withColumn("ST_BUFFERR",expr("ST_Buffer(ST_GeomFromWKT('"+item+"'),"+d+")")).withColumn("ST_WITHIN",expr("ST_WITHIN(ST_GeomFromText(CONCAT('POINT(',longitude,' ',latitude,')',4326)),ST_BUFFERR)"));
}
res_f.show();
}
But res_f returns nothing and is always null.
I'm using Spark with Java.
EDIT
I solved the problem, just change this line from Dataset<Row> res_f = null; to Dataset<Row> res_f;
I need your help .

TFS JAVA SDK - How to run shared query

I have a application which useds TFS JAVA SDK 14.0.3 .
I have a shared query  on my tfs , how can i run the shared query and get the response back using TFS SDK 14.0.3
Also I could see that the query url will expire in every 90 days , so any better way to execute the shared query?
Now I  have a method to run a query , i want method  to  run shared query also.
public void getWorkItem(TFSTeamProjectCollection tpc, Project project){
WorkItemClient workItemClient = project.getWorkItemClient();
// Define the WIQL query.
String wiqlQuery = "Select ID, Title,Assigned from WorkItems where (State = 'Active') order by Title";
// Run the query and get the results.
WorkItemCollection workItems = workItemClient.query(wiqlQuery);
System.out.println("Found " + workItems.size() + " work items.");
System.out.println();
// Write out the heading.
System.out.println("ID\tTitle");
// Output the first 20 results of the query, allowing the TFS SDK to
// page
// in data as required
final int maxToPrint = 5;
for (int i = 0; i < workItems.size(); i++) {
if (i >= maxToPrint) {
System.out.println("[...]");
break;
}
WorkItem workItem = workItems.getWorkItem(i);
System.out.println(workItem.getID() + "\t" + workItem.getTitle());
}
}
Shared query is a query which has been run and saved, so what you need should be getting a a shared query, not run a shared query. You could refer to case Access TFS Team Query from Client Object API:
///Handles nested query folders
private static Guid FindQuery(QueryFolder folder, string queryName)
{
foreach (var item in folder)
{
if (item.Name.Equals(queryName, StringComparison.InvariantCultureIgnoreCase))
{
return item.Id;
}
var itemFolder = item as QueryFolder;
if (itemFolder != null)
{
var result = FindQuery(itemFolder, queryName);
if (!result.Equals(Guid.Empty))
{
return result;
}
}
}
return Guid.Empty;
}
static void Main(string[] args)
{
var collectionUri = new Uri("http://TFS/tfs/DefaultCollection");
var server = new TfsTeamProjectCollection(collectionUri);
var workItemStore = server.GetService<WorkItemStore>();
var teamProject = workItemStore.Projects["TeamProjectName"];
var x = teamProject.QueryHierarchy;
var queryId = FindQuery(x, "QueryNameHere");
var queryDefinition = workItemStore.GetQueryDefinition(queryId);
var variables = new Dictionary<string, string>() {{"project", "TeamProjectName"}};
var result = workItemStore.Query(queryDefinition.QueryText,variables);
}
By the way, you could also check the REST API in the following link:
https://learn.microsoft.com/en-us/rest/api/vsts/wit/queries/get

How to get java class in CF

I want to access the return value from a java method in my coldfusion file. I have loaded all the jar files in coldfusion file and got the java class object successfully. Using the class object, I want to access java class method which returns a Set; but I can't get any return value.
Here is my Java Code:
public Set getSession(String url) {
result+="hello";
try {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", false);
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"E:\\TicketScraper\\phantomjs\\phantomjs.exe"
);
driver = new PhantomJSDriver(caps);
driver.get(url);
driver.findElement(By.id("login:loginName")).sendKeys("XXXX");
driver.findElement(By.id("login:password")).sendKeys("XXXX");
waitForJQueryProcessing(driver, 5);
driver.findElement(By.id("login:j_idt145")).click();
Thread.sleep(10000);
Set<org.openqa.selenium.Cookie> allCookies=driver.manage().getCookies();
for ( org.openqa.selenium.Cookie loadedCookie : allCookies) {
System.out.println(String.format("%s -> %s", loadedCookie.getName(),loadedCookie.getValue()));
}
} catch(Exception e) {
System.out.println(e);
}
return allCookies;
}
The java code runs the Phantom JS driver, logs in to the URL in the above code, and gets all cookies. All cookies are collected in a Set variable and returned from the method. I want to get this set variable in CF code.
But when I have tried to access the java method's Set variable in CF it doesn't return any value. By contrast, when I have commented out all the Phantom JS code and return only a String variable then CF can access the string value.
Here is my CF code:
<cfscript>
paths = arrayNew(1);
paths[1] = expandPath("lib\apache-mime4j-0.6.jar");
paths[2] = expandPath("lib\bsh-1.3.0.jar");
paths[3] = expandPath("lib\cglib-nodep-2.1_3.jar");
paths[4] = expandPath("lib\commons-codec-1.9.jar");
paths[5] = expandPath("lib\commons-collections-3.2.1.jar");
paths[6] = expandPath("lib\commons-exec-1.1.jar");
paths[7] = expandPath("lib\commons-io-2.4.jar");
paths[8] = expandPath("lib\commons-jxpath-1.3.jar");
paths[9] = expandPath("lib\commons-lang3-3.3.2.jar");
paths[10] = expandPath("lib\commons-logging-1.1.3.jar");
paths[11] = expandPath("lib\Counsel_Cookies_Phantom.jar");
paths[12] = expandPath("lib\cssparser-0.9.14.jar");
paths[13] = expandPath("lib\gson-2.3.jar");
paths[14] = expandPath("lib\guava-18.0.jar");
paths[15] = expandPath("lib\hamcrest-core-1.3.jar");
paths[16] = expandPath("lib\hamcrest-library-1.3.jar");
paths[17] = expandPath("lib\htmlunit-2.15.jar");
paths[18] = expandPath("lib\htmlunit-core-js-2.15.jar");
paths[19] = expandPath("lib\httpclient-4.3.4.jar");
paths[20] = expandPath("lib\httpcore-4.3.2.jar");
paths[21] = expandPath("lib\httpmime-4.3.4.jar");
paths[22] = expandPath("lib\ini4j-0.5.2.jar");
paths[23] = expandPath("lib\jcommander-1.29.jar");
paths[24] = expandPath("lib\jetty-websocket-8.1.8.jar");
paths[25] = expandPath("lib\jna-3.4.0.jar");
paths[26] = expandPath("lib\jna-platform-3.4.0.jar");
paths[27] = expandPath("lib\junit-dep-4.11.jar");
paths[28] = expandPath("lib\netty-3.5.7.Final.jar");
paths[29] = expandPath("lib\nekohtml-1.9.21.jar");
paths[30] = expandPath("lib\operadriver-1.5.jar");
paths[31] = expandPath("lib\phantomjsdriver-1.1.0.jar");
paths[32] = expandPath("lib\protobuf-java-2.4.1.jar");
paths[33] = expandPath("lib\sac-1.3.jar");
paths[34] = expandPath("lib\selenium-java-2.44.0.jar");
paths[35] = expandPath("lib\selenium-java-2.44.0-srcs.jar");
paths[36] = expandPath("lib\serializer-2.7.1.jar");
paths[37] = expandPath("lib\testng-6.8.5.jar");
paths[38] = expandPath("lib\xalan-2.7.1.jar");
paths[39] = expandPath("lib\xercesImpl-2.11.0.jar");
paths[40] = expandPath("lib\xml-apis-1.4.01.jar");
paths[41] = expandPath("lib\Selenium_Cookies.jar");
paths[42] = expandPath("lib\selenium-server-2.0b2.jar");
//writeDump(paths);
//create the loader
loader = createObject("component", "javaloader.JavaLoader").init(paths,true);
//writeDump(loader);
excelObject = loader.create("counsel_cookies_phantom.Counsel_Cookies_Phantom");
//writeDump(excelObject);
//abort;
</cfscript>
<cfdump var=#excelObject.getSession("https://pacer.login.uscourts.gov/csologin/login.jsf")#/>
<cfabort>
Please provide your suggestions of how to access the Phantom JS value in CF.
Assuming your Set is a java.util.Set, then calling toArray() would give you an array that's easily accessible in CF.
e.g.
<cfscript>
s = createObject("java", "java.util.HashSet").init();
s.add("foo");
s.add("bar");
s.add("bob");
arr = s.toArray();
writeDump(arr);
</cfscript>
Run this on TryCF.com

how to get path of rule (folder structure) using java

i'm trying to get folder structure of a rule using java TEAMSERVER API .
IlrSessionFactory factory = new IlrRemoteSessionFactory();
try {
factory.connect(login, password, serverUrl, datasource);
IlrSession session = factory.getSession();
IlrRuleProject ruleProject = (IlrRuleProject) IlrSessionHelper.getProjectNamed(session, project);
IlrBaseline currentBaseline = IlrSessionHelper.getCurrentBaseline(session, ruleProject);
session.setWorkingBaseline(currentBaseline);
String query = new String("Find all business rules such that the name of each business rule is \"R105_1_krl\"");
IlrDefaultSearchCriteria criteria = new IlrDefaultSearchCriteria( query.toString());
List summaries = session.findElements(criteria, IlrModelConstants.ELEMENT_SUMMARY);
for (int i = 0; i < summaries.size(); i++) {
IlrElementSummary ruleSummary = (IlrElementSummary) summaries.get(i);
String ruleName = ruleSummary.getName();
System.out.println("\t" + ruleName);
}
If there is as named R105_1_krl rule , I can reach using java and DECİSİON CENTER API. But i need location of this rule. Such as XYZ package / abc folder / def folder
In addition , when i wrote the following two line in loop , i can reach these properties ;
Expiration Date, Effective Date, Created By, Last Changed On ... But, i can not reach folder information of properties of a rule.
IlrActionRule rule = (IlrActionRule) elementDetails;
String lastChangedBy = String.valueOf(rule.getPropertyValue("lastChangedBy"));
Here is the solution.
public static String getHierarchyPath (IlrElementDetails element) {
try {
if (!(element instanceof IlrRule)) return element.getName();
IlrRule rule = (IlrRule)element;
StringBuffer sb = new StringBuffer ();
// Get the rule name
String name = rule.getName();
// Get the rule package
IlrRulePackage current = rule.getRulePackage();
Stack<String> stack = new Stack<String> ();
while (true) {
if (current==null) break;
// Push the package name onto the stack
stack.push("/" + current.getName());
// Next parent ...
current = current.getParent();
}
// Pop the stack and build the path
while (!stack.empty()) {
String folder = (String) stack.pop();
sb.append(folder);
}
// Append the rule name to the path
sb.append("/").append(name);
// Return the built path
return sb.toString();
} catch (Exception e) {
return element.getName();
}
}

Categories

Resources