I have a flag of type boolean "worklogMatch". I need to assert this flag for 'true'. If this is not true, I would need to print the ERROR value. Here is my code,
List<WebElement> worklogObj = driver().findElements(By.xpath("//div[#class='ng-scope']");
boolean worklogMatch = false;
ArrayList<String> worklogDescriptions = new ArrayList<String>();
for(int i=0; i<worklogObj.size(); i++) {
worklogDescriptions.add(worklogObj.get(i).getText());
log.info("Text of the worklogs: "+worklogObj.get(i).getText());
if (worklogObj.get(i).getText().equals(worklogDescription)){
worklogMatch = true;
break;
}
}
assertTrue(worklogMatch == true, "worklog Description "+worklogDescription + " is not saved. List of "+ "worklog description found for the incident " +incidentNumber +" is" + worklogDescriptions);
When I assert this, the boolean variable worklogMatch is set as false as the String that I'm looking for is not present in the ArrayList. The test case fails as expected. However, the message is not dispalyed in the console. My questions,
Is my way of assertion valid? I'm asserting a boolean variable with 'true'
Why is my message not being printed when the assertion fails?
Yes, way of assertion is correct, one thing that i've changed is not compare worklogMatch to true in assertion
According to the doc, message should be written as first arg
now assert will look like:
assertTrue("worklog Description "+worklogDescription + " is not saved. List of "+ "worklog description found for the incident " +incidentNumber +" is" + worklogDescriptions, worklogMatch);
Related
Can’t convert String into json, and it seems that it will be superfluous for the entire string.
Was thinking maybe json might have helped me out here, but it doesn't seem to give me what I want or I don't know how it will be work.
How I can check the string?
I need to check:
METHOD: GET and URL: http://google.com/
also to check the BODY contains the fields userId, replId and view (no values, only keys)
I was trying to find a way to check that:
if (msg.contains("METHOD: GET") && msg.contains("URL: http://google.com/") && msg.contains("BODY: etc...")) {
System.out.println("ok");
}
It doesn't work. Some values from BODY that are dynamic and that's why for BODY the check won't pass if it’s so hardcoded String. And I guess there're any better ways to do that.
I'd like to have something like:
Assert.assertEquals(
msg,
the expected value for METHOD, which contains GET); // same here for URL: http://google.com/
Assert.assertEquals(
msg,
the expected value for BODY that has userId, replId, and view fields); // or make this assertion for each field separately, such as there is an assertion for the userId field, the same assertions for replId and view
And here's the String:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
I can't think of any way to check that. Any ideas?
You can use the java.util.List Interface (of type String) and place the string contents into that list. Then you can use the List#contains() method, for example:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
// Split contents of msg into list.
java.util.List<String> list = Arrays.asList(msg.split("\n"));
if (list.contains("METHOD: GET")) {
System.out.println("YUP! Got: --> 'METHOD: GET'");
}
else {
System.out.println("NOPE! Don't have: --> 'METHOD: GET'");
}
I've tried to use Assert:
String[] arr1 = msg.split("\n");
Map<String, String> allFieldsMessage = new HashMap<>();
for (String s : arr1) {
String key = s.trim().split(": ")[0];
String value = s.trim().split(": ")[1];
allFieldsMessage.put(key, value);
}
Assert.assertEquals(
allFieldsMessage.get("METHOD"),
"GET"
);
And the same for URL. But my problem is in BODY part. I thought maybe try to parse this particular part of String into json and then only check the necessary keys.
i'm trying to compare some texts with this code bellow:
driver.get("https://www.hotel.de/");
boolean status = false;
String searchText = "Hannover, Niedersachsen";
WebElement inputBox = driver.findElement(By.xpath("//div[#class='LocationAutoSuggest__container--2Hli_']//input"));
Now i send String "Hannover" to Searchbox:
Actions actions = new Actions(driver);
actions.moveToElement(inputBox).click().sendKeys("Hannover").build().perform();
Thread.sleep(3000);
List<WebElement> listsearch = driver.findElements(By.id("react-autowhatever-1"));
And compare the found text with searchText :
for(WebElement listElem : listsearch) {
System.out.println(listElem.getText());
System.out.println(searchText.equals(listElem.getText()));
if(searchText.equals(listElem.getText())) {
System.out.println("hooho");
status = true;
break;
} else {
status = false;
}
}
System.out.println(status);
==> Could you tell me: why i become FALSE instead of TRUE? (How can i see the logs, to know what was actually compared?). Many thanks.
Check the size of your List if it zero than directly false will be printed.
If size is not greater than zero check your locator.
When the code is ran the nested loop causes it to create occasional duplicate entries to the system, i have spent a while looking through this but still cant find what is causing this, would greatly appreciate any help?
for(int i = 0; i < subWorkItemElement.getChildNodes().getLength(); i++) {
Boolean test = false;
WorkItemCommon existingChild = null;
String summary = null;
if(subWorkItemElement.getChildNodes().item(i).getNodeName().equals("workitem")) {
// We know it's a work item - but is it in the existing list?
Element childWorkItem = (Element) subWorkItemElement.getChildNodes().item(i);
for(int j = 0; j < subWorkItemElement.getChildNodes().getLength(); j++) {
if(childWorkItem.getChildNodes().item(j) instanceof Element) {
if(((Element)childWorkItem.getChildNodes().item(j)).getNodeName().equals("details")) {
summary = ((Element) childWorkItem.getChildNodes().item(j)).getElementsByTagName("summary")
.item(0).getTextContent();
for(String k : userInfoHashMap.keySet()) {
summary = summary.replace("${" + k + "}", userInfoHashMap.get(k));
}
if(childHashTable.containsKey(summary)) {
test = true;
existingChild = childHashTable.get(summary);
IWorkItem workItem = existingChild.getWorkItem();
System.out.println("INFO: The task with summary \"" + summary + "\" already exists. Skipping creation.");
System.out.println("this task is work item: " + workItem.getId());
//either check the tasks in the xml for updated details and then modify the existing workitem
//or just modify the work item without checking for updates
makeChildTask(childWorkItem, existingChild, childHashTable, userInfoHashMap, workItemHashMap, rtc, false);
break;
}
}
}
}
if(!test) {
System.out.println("INFO: The task with summary " + summary + " does not currently exist. Creating.");
makeChildTask(childWorkItem, thisItem, childHashTable, userInfoHashMap, workItemHashMap, rtc, true);
} else makeFromExistingChildTask(childWorkItem, existingChild, userInfoHashMap, workItemHashMap, rtc);
}
}
You are possibly (not sure what makeChildTask() does) changing an XML structure while iterating through the children list. While not necessarily incorrect, this can mean you get entries inserted while you process the list. Since you call the subWorkItemElement.getChildNodes().getLength() each time instead of cache'ing it, this might result in the length changing in between the loop iterations.
The below code is getting into an infinite search when running via TestNG, otherwise giving correct results when executed directly in Main method via Java Application.
Boolean iselementpresent = driver.findElements(By.linkText("Foreign exchange1")).size()!= 0;
Infinite search-->
public boolean checkLinkPresence(String linkName){
Boolean iselementpresent = driver.findElements(By.linkText("Foreign exchange1")).size()!= 0;
if (iselementpresent == true)
return true;
else{
System.out.print("Element " + linkName + " not Present");
APP_LOGS.debug("Element " + linkName + " not Present");
return false;
}
}
You should not be using main method in TestNG as everything works with annotations. However make sure your implicit wait time is short so that the command findElements timeouts after that. If you have not given an implicit wait, try giving one and then try running your method. Here's an example -
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //set this before you get the url using driver.get()
Once your implicit wait time is set, try running your method.
public boolean checkLinkPresence(String linkName){
List elements = driver.findElements(By.linkText("Foreign exchange1"));
if (elements.size() != 0)
return true;
else{
System.out.print("Element " + linkName + " not Present");
APP_LOGS.debug("Element " + linkName + " not Present");
return false;
}
}
Hope it helps.
This is how I would write this function...
public boolean checkLinkPresence(String linkName)
{
if (driver.findElements(By.linkText(linkName)).isEmpty())
{
System.out.print("Element " + linkName + " not Present");
APP_LOGS.debug("Element " + linkName + " not Present");
return false;
}
return true;
}
Your locator had a hard coded string in it By.linkText("Foreign exchange1"), so no matter what string you passed the function, it was always looking for that one string.
I received a table and was able to get and validate the data (whether the email is ACTUALLY an email and so forth). We want to validate the data that is displayed on the front end with the backend. There was a table (I had seen the table- the first column was name and then email , phone number, company , country and the date).
Now, the person on the front-end, switched up the columns. I had seen the table before and therefore I knew the order I would receive my information. I will have to change the code everytime a small change is made on the front end. FYI, the table headers are defined with "data-name" so I will be able to use it if your solution involves something w/ table headers. My code is posted below:
public static void getTableContents(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//TODO Replace this w. until it find command
e.printStackTrace();
}
log("TABLE CONTENTS VERIFICATION");
//Get the table contents
WebElement table_element = driver.findElement(By.className(TABLE_RESPONSE));
//Click on a button to switch into the desired column
WebElement switchColumn = driver.findElement(By.cssSelector(".switchColumn img.pull-right"));
switchColumn.click();
// We do not want the first two contents as they represent default or error case.
List<WebElement> tr_collection=table_element.findElements(By.xpath("//tbody//tr[position()>2]"));
int i=1;
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
int j=1;
for(WebElement tdElement : td_collection)
{
String check = tdElement.getText();
if(j==1) {
if(isValidName(check))
passed("Name Test : " );
else{
log(check + " is not a valid name");
}
}
if(j==2) {
if(isValidEmail(check))
{ passed("Email address Test : ");
}
else
log(check + " is not a valid email");
}
if(j==3) {
if(isValidNumber(check))
passed("Valid Number test : ");
else
log(check + " is not a valid number");
}
if(j==6){
if(isValidIccid(check))
passed("Valid Iccid test : ");
else
log(check+ " is not a valid Iccid");
}
if(j==4){
//Blank (for a while)
}
if(j==5){
if(isValidCountry(check))
passed("Valid country test : ");
else
log(check+ " is not a valid country");
}
j++;
}
System.out.println();
i++;
}
}
Is there any quick way of changing this code to my requirements? I can't keep changing the numbers (1,2,3,4,5,6) all the times. I am just looking for clever ways to UPDATE my code rather than CHANGE my code completely.
Any help/tip is greatly appreciated.EDIT: Also, I will be changing my if/else statements to switch cases so it is easier to understand. But as of now, I got a great problem cause I might have to change my entire code so please do not mind.
If your table has the table headers with classes like:
data-Name
data-Email
then you can use this in the code as follows:
// We do not want the first two contents as they represent default or error case.
List<WebElement> tr_collection=table_element.findElements(By.xpath("//tbody//tr[position()>2]"));
int i=1;
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
int j=1;
for(WebElement tdElement : td_collection)
{
String check = tdElement.getText();
String header = driver.findElement(By.xpath("//tbody//tr/th[" + j + "]")).getAttribute("class");
if(header.equals("data-Name")) {
if(isValidName(check))
passed("Name Test : " );
else{
log(check + " is not a valid name");
}
}
if(header.equals("data-Email")) {
if(isValidEmail(check))
{ passed("Email address Test : ");
}
else
log(check + " is not a valid email");
}
//... and so on
}
}
You might need to change this line to reflect the correct way for you to identify the table headers:
String header = driver.findElement(By.xpath("//tbody//tr/th[" + j + "]")).getAttribute("class");
but the point is to use the "j" counter to track the column that you are on and check the class name of the header for that column. The order of the columns should no longer matter if you identify them this way.