How to use an array for a method within a loop - java

I am using a list of URLs within a loop for a test in Selenium. For each specific URL I want to define separate strings for a reusable method I'm calling within the test. They all have to be different or else my data will overwrite each other.
public class LogIn extends ReusableMethod {
// here is my lists of URLS
#Test void test()throws Exception {
String[] Urls;
Urls = new String[3];
Urls[0] = "site.com/us/en";
Urls[1] = "site.com/ca/en";
Urls[2] = "site.com/au/en";
for (int i=0; i<Urls.length; i++) {
openbrowser(Urls[i]);
//openbrowser is calling a reusable method to open a browser and go to
each //URL and the test loops through the URLs defined above
//------- sign in from the sign in page--------//
RegisteredSignIn();
CheckTitle();
// My check title method calls
/*
public void CheckTitle () {
String ActualTitle = driver.getTitle();
String[] Title = new String[7];
Title[0] = "My Site Account | Site US";
Title[1] = "My Site Account | Site CA";
Title[2] = "My Site Account | Site AU";
for (int i=0; i<Title.length; i++) {
if(ActualTitle.equals(Title[i])){
System.out.println("Page"+ Title[i] + " is up + Registered Log on
have passed");
}
else {System.err.println( Title[i] + " Page + Registerd Log on have
FAILED");
}
}
}*/
quitbrowser();
}
}
}
I can get the single title of a page and compare it to the expected title.. but how do I change the string used within the method and loop it as well to keep changing with my Test loop?

Just wrap whole method to accept single argument - url - and than in test case iterate over your urls.

I'm not sure I understand your question completely, but it sounds like you need to store your expected titles in a similar way to how you store the URLs you need to test. Here's an example:
public class LogIn {
#Test
void test() throws Exception {
String[] urls = new String[3];
urls[0] = "site.com/us/en";
urls[1] = "site.com/ca/en";
urls[2] = "site.com/au/en";
String[] titles = new String[3];
titles[0] = "Site Title - US";
titles[1] = "Site Title - CA";
titles[2] = "Site Title - AU";
for (int i = 0; i < urls.length; i++) {
checkTitle(urls[i], titles[i]);
}
}
void checkTitle(String url, String expected) {
openbrowser(url);
//------- sign in from the sign in page--------//
RegisteredSignIn();
CheckTitle(expected);
quitbrowser();
}
}

Thank you #ordonezalex I used your solution like soo..
public class LogIn extends ReusableMethod {
Test void test()throws Exception {
String[] Urls;
Urls = new String[3];
Urls[0] = "https://www.nixon.com/us/en";
Urls[1] = "https://www.nixon.com/ca/en";
String[] Titles;
Titles = new String[3];
Titles[0] = "My Nixon Account | Nixon US";
Titles[1] = "My Nixon Account | Nixon CA";
for (int i=0; i<Urls.length; i++) {
System.out.println(Urls.length);
openbrowser(Urls[i]);
RegisteredSignIn();
CheckTitle(Titles[i]); ....

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).

Selenium - Java - how to assert/verify all links on a page are working, get title and verify against expected titles

I am new to test automation and i am currently working on a personal project
I have this method in which it finds all the links for a section on the page, clicks on each link, irritates through each tab and then gets the title of each page
However, i want a way to verify the titles of these links against a list of expected titles
What would be the best approach to modify this in order to do this? would it be better to store in an array and then assert/verify each title separately?
I have tried a few ways to assert by changes return type to String and also to List but with no luck
public void linksAreWorkingDashBoardLeftPanal() throws Exception {
List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
for(int i = 0; i < li_All.size(); i++){
String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
Thread.sleep(5000);
}
//Opens all the tabs
Set<String> getTitleinWindow = driver.getWindowHandles();
Iterator<String> it = getTitleinWindow.iterator();
while(it.hasNext())
{
driver.switchTo().window(it.next());
System.out.println(driver.getTitle());
}
Modify the while loop as follows;
List<String> expectedTitleList = new ArrayList<>();
// Get the expected titles in a list.
// You have to initiate and add expected titles to this list, before running the while loop.
List<String> actualTitleList = new ArrayList<>();
while(it.hasNext())
{
driver.switchTo().window(it.next());
actualTitleList.add(driver.getTitle());
}
// Create copies of each list;
Set<String> expectedSet = new HashSet<>(expectedTitleList);
Set<String> actualSet = new HashSet<>(actualTitleList);
Set<String> expectedOnlySet = new HashSet<>(expectedSet);
Set<String> actualOnlySet = new HashSet<>(actualSet);
expectedOnlySet.removeAll(actualSet);
actualOnlySet.removeAll(expectedSet);
// Check if expectedOnlySet and actualOnlySet are empty
// If both of them are empty then all titles are received as expected.
boolean isEmpty = (expectedOnlySet.size() == 0 && actualOnlySet.size() == 0);
if (expectedOnlySet.size() > 0 || actualOnlySet.size() > 0) {
// If expectedOnlySet contain any title; it means those titles are not opened in the browser.
// If actualOnlySet contain any title; it means those titles are not expected titles.
StringBuilder message = new StringBuilder();
for (String x: expectedOnlySet) {
message.append("Did not receive: ");
message.append(x).append(", ");
}
for (String y: actualOnlySet) {
message.append("Not expected but received: ");
message.append(y).append(", ");
}
Assert.assertTrue(false, message,toString());
}else {
Assert.assertTrue(true);
}
Here you can use removeAll() method in Collections. Check the documentation
We have to check both scenarios;
Whether all expected titles are received
All received titles are expected
Thanks! I took what i needed from your code and it worked perfectly.
this work and i added my own assertion
List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
for(int i = 0; i < li_All.size(); i++){
String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
}//Opens all the tabs
Set<String> getTitleinWindow = driver.getWindowHandles();
Iterator<String> it = getTitleinWindow.iterator();
// Get the expected titles in a list.
// You have to initiate and add expected titles to this list, before running the while loop.
List<String> expectedTitleList = new ArrayList<>();
expectedTitleList.add("Page 1 title");
expectedTitleList.add("Page 2 title");
expectedTitleList.add("Page 3 title");
expectedTitleList.add("Page 4 title");
expectedTitleList.add("Page 5 title");
expectedTitleList.add("Page 6 title");
expectedTitleList.add("Page 7 title");
List<String> actualTitleList = new ArrayList<>();
while(it.hasNext())
{
driver.switchTo().window(it.next());
actualTitleList.add(driver.getTitle());
}
//System.out.println(expectedTitleList);
// System.out.println(actualTitleList);
if(actualTitleList.equals(expectedTitleList)).....

error when get value from marketdataincremental refresh

I got an error in my quickfixj Application. First, I got an error like this:
Out of order repeating group members
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
But now I got another error in my application:
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:38)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInThread$1(SingleThreadedEventHandlingStrategy.java:145)
at quickfix.mina.SingleThreadedEventHandlingStrategy$ThreadAdapter$RunnableWrapper.run(SingleThreadedEventHandlingStrategy.java:267)
at java.lang.Thread.run(Thread.java:748)
My code for get value of symbols is :
public void fromApp(quickfix.Message message, SessionID sessionID)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
try {
String symbol = message.getString(Symbol.FIELD);
System.out.println(" FromApp " + message);
message.getString(TransactTime.FIELD);
// String seqNo = message.getString(MsgSeqNum.FIELD);
double bid = message.getDouble(MDEntryPx.FIELD);
double ask = message.getDouble(MDEntryPx.FIELD);
// System.out.println(seqNo + " " + message);
} catch (FieldNotFound fieldNotFound) {
fieldNotFound.printStackTrace();
}
}
I have also using this code
public void onMessage (MarketDataIncrementalRefresh message, SessionID sessionID) throws FieldNotFound{
try
{
MDReqID mdreqid = new MDReqID();
SendingTime sendingtime = new SendingTime();
NoMDEntries nomdentries = new NoMDEntries();
quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries group
= new quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries();
MDUpdateAction mdupdateaction = new MDUpdateAction();
DeleteReason deletereason = new DeleteReason();
MDEntryType mdentrytype = new MDEntryType();
MDEntryID mdentryid = new MDEntryID();
Symbol symbol = new Symbol();
MDEntryOriginator mdentryoriginator = new MDEntryOriginator();
MDEntryPx mdentrypx = new MDEntryPx();
Currency currency = new Currency();
MDEntrySize mdentrysize = new MDEntrySize();
ExpireDate expiredate = new ExpireDate();
ExpireTime expiretime = new ExpireTime();
NumberOfOrders numberoforders = new NumberOfOrders();
MDEntryPositionNo mdentrypositionno = new MDEntryPositionNo();
message.getField(nomdentries);
message.getField(sendingtime);
message.getGroup(1, group);
int list = nomdentries.getValue();
for (int i = 0; i < list; i++)
{
message.getGroup(i + 1, group);
group.get(mdupdateaction);
if (mdupdateaction.getValue() == '2')
System.out.println("Enter");
group.get(deletereason);
group.get(mdentrytype);
group.get(mdentryid);
group.get(symbol);
group.get(mdentryoriginator);
if (mdupdateaction.getValue() == '0')
group.get(mdentrypx);
group.get(currency);
if (mdupdateaction.getValue() == '0')
group.get(mdentrysize);
}
System.out.printf("Got Symbol {0} Price {1}",
symbol.getValue(), mdentrypx.getValue());
}catch (Exception ex)
{
System.out.println("error" + ex);
}
but i also get error like this
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:39)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInpacket_write_wait: Connection to 3.13.235.241 port 22: Broken pipe
and here the value i check in my message.log
8=FIX.4.2^A9=0217^A35=X^A34=7291^A49=Fastmatch1^A52=20200401-10:47:59.833^A56=MDValueTrade2UAT1^A262=VT_020^A268=02^A279=2^A55=GBP/CHF^A269=0^A278=1140851192^A270=1.19503^A271=02000000^A279=0^A55=GBP/CHF^A269=0^A278=1140851194^A270=1.19502^A271=06000000^A10=114^A
my broker have send to me the price and etc
My question is: how to fix my problem from this code ?
First, I got an error like this:
Out of order repeating group members
Your data dictionary doesn't match your counterparty's. Fix that and this will go away.
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
This did not fix anything -- it HIDES your actual problem and has you looking at a new fake problem.
What you need to do:
Your configuration has this, right?
UseDataDictionary=Y
DataDictionary=path/to/FIXnn.xml
# or if FIX5:
AppDataDictionary=path/to/FIX5n.xml
TransportDataDictionary=path/to/FIXT.xml
Find your counterparty's documentation, and make sure your xml file's messages and fields match what they say they're going to send you. Make sure all repeating groups have the same fields in the same order.
Here is some documentation about how the Data Dictionary xml file is structured. It's pretty easy.

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();
}
}

Query TestSet Json returns wrong list of test cases in Rally Rest API

When I request "TestSet" query to fetch TestCases in a specific test set.
But, the fetched TestCases contains the full list of test cases in the project not in the specific test set.
QueryRequest queryTestSet = new QueryRequest("TestSet");
queryTestSet.setFetch(new Fetch("Name", "Project", "TestCases"));
queryTestSet.setQueryFilter(new QueryFilter("name", "=", "TestSet_Name"));
QueryResponse responseTestSet = RallyRestAPI.getAPI().query(queryTestSet);
JsonArray testcasesJson = responseTestSet.getResults().get(0).getAsJsonObject().getAsJsonArray("TestCases");
For example, there are total 500 test cases in the project
I added test cases and results of "Automated" test cases in a TestSet (300 test cases)
Then, I request the query above, the size of "testcasesJson" returns 500 and it includes full list of test cases.
How can I read the test cases that only added in a TestSet?
Rally Rest JAR Version: rally-rest-api-1.0.7.jar
This code example that uses 2.0.4 jar returned only test cases associated with a test set:
public class GetTCofTS {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String applicationName = "RESTExampleFindTestCasesOfTestSet";
String workspaceRef = "/workspace/1111";
String projectRef = "/project/2222";
String wsapiVersion = "1.43";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
QueryRequest testSetRequest = new QueryRequest("TestSet");
testSetRequest.setWorkspace(workspaceRef);
restApi.setWsapiVersion(wsapiVersion);
testSetRequest.setFetch(new Fetch(new String[] {"Name", "TestCases", "FormattedID"}));
testSetRequest.setQueryFilter(new QueryFilter("Name", "=", "someTS"));
QueryResponse testSetQueryResponse = restApi.query(testSetRequest);
System.out.println("Successful: " + testSetQueryResponse.wasSuccessful());
System.out.println("Size: " + testSetQueryResponse.getTotalResultCount());
for (int i=0; i<testSetQueryResponse.getResults().size();i++){
JsonObject testSetJsonObject = testSetQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + testSetJsonObject.get("Name") + " ref: " + testSetJsonObject.get("_ref").getAsString() + " Test Cases: " + testSetJsonObject.get("TestCases"));
int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size();
System.out.println(numberOfTestCases);
if(numberOfTestCases>0){
for (int j=0;j<numberOfTestCases;j++){
System.out.println(testSetJsonObject.get("TestCases").getAsJsonArray().get(j).getAsJsonObject().get("FormattedID"));
}
}
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}

Categories

Resources