Selenium assertText for all text in a table? - java

I need to assert that each row in table contains a certain text string, either through selenium IDE or a Java test case. What's the best way to do this? Here's my current test:
Command assertText
Target //table[#id='myTable']//tbody//tr[not(#style)]/td[1]
Value myValue
I need to test the first column of every row, but this only tests the first row. Is there an easy way to test every row?

I haven't used selenium IDE, only the java API, so here how I'd do it in java (or the basic idea at least)
int numRows = selenium.getXpathCount("table[#id='myTable']//tbody//" +
"tr[not(#style)]/td[1]").intValue();
String[] values = new String[numRows];
for (int i = 0; i < numRows; i++) {
values[i] = selenium.getText("table[#id='myTable']//tbody//" +
"tr[not(#style)][" + i + "]/td[1]");
}

Related

Expand the range of numbers

I was trying a solve a issue which is bothering me for a while. I created a small parser that reads an .ini file and then stores the data in an ArrayList. However, I got stuck with the following snippet:
while (!(sCurrentLine.equals("[End]"))) {
formats.add(sCurrentLine);
for (int i = 0; formats.size() > 0; i++) {
}
sCurrentLine = br.readLine();
}
Now this is the place where I have to add values into formats, which is of type ArrayList.
The values that will be added like this:
0900.013-017=LABEL
0900.018-029=LABEL
Now the range is in between and I also have to make sure that '0900' and '=label' repeats themselves along with the expansion of numbers, for example:
0900.013=LABEL
0900.014=LABEL
0900.015=LABEL
0900.016=LABEL and so on...
and store it back in the ArrayList.
I don't want to depend upon third-party libraries. Please help me out with this.
Use a regular expression to parse the range, then loop over the parsed values. There is some fine tuning to be done but I think this should get you started.
Pattern rangePattern = Pattern.compile("([0-9]+)\\.([0-9]+)-([0-9]+)=(.*)$");
Matcher rangeMatcher = rangePattern.matcher("0900.13-17=First label");
if (rangeMatcher.matches()) {
String prefix = rangeMatcher.group(1);
int start = Integer.parseInt(rangeMatcher.group(2));
int end = Integer.parseInt(rangeMatcher.group(3));
String label = rangeMatcher.group(4);
for (int r = start; r < end; r++) {
System.out.println(prefix + "." + r + "=" + label);
}
}
Create the pattern once and then just get new matchers each time through your loop.
The results:
0900.13=First label
0900.14=First label
0900.15=First label
0900.16=First label

Java Mysql table data output formatting

Here is my MySql table:
I want to show the output of the query in commandline as below:
I have written the code below to loop but I am getting only the first row, What i have to modify ??
ResultSet rs2 = stmt.executeQuery(table_retrive);
String[] cols = new String[itemList.size()];
int[] rec =new int[itemList.size()];
for (int i = 0; i < itemList.size(); i++) {
while (rs2.next()) {
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.println(rec[i]+" ");
}
}
Your two loops are wrong. Start at i=0 and then iterate once over the whole ResultSet, filling yor first array position. When this is done, i is incremented and you try to iterate the ResultSet a second time but the cursor is at the end of the ResultSet, so rs2.next() returns false and the code will not be executed.
So you have two Solutions:
Handle the loops correctly. Unfortunately I do not know, what you are trying to do anyways because this is some C-like code without OOP, which doesn't show semantics and then you have this itemList which seems to hold preset values and you read out of this list, which column to take for the i-th position. This seems odd. Maybe switching the loops does the desired: Start with the while and nest the for.
Reset the cursor of the ResultSet after the while with rs2.beforeFirst(). WARNING: This could throw a SQLFeatureNotSupportedException. Not all Databases can move the cursor backwards. This is of course a very ugly solution, since you should first parse the whole row a once.
Try to use printf() Or format() method. It is same as printf method in c lang. you can pass parameters and difference. Look at link1
And link 2
Example : System.out.printf("%d%5s%10d", 5,"|",10);
output : 5 | 10
Using this the I got all the values but in one row :
while (rs2.next()) {
for (int i = 0; i < itemList.size(); i++) {
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.print(rec[i]+" ");
}
}
But I need to divide like the rows.
Usage of the inner loop is your problem.
You can enhance your code to remove the usage of the second loop in your code, it basically does nothing. You can loop over your result set and in the same loop using the incremented variable to persist the values accordingly.
The code shown half implemented in your question, hence it will be difficult to give you exactly what need to be done. Nevertheless, here's an attempt to resolve the problem for you:
while (rs2.next()) {
System.out.println(rs2.getInt(1) + "\t |" + rs2.getString(2) + "\t |" + rs2.getString(3));
}
Based on the column names from the table in the question, assuming that column2 and column3 are String's.
You can add the necessary details to this code to complete it according to your usecase, but I've just taken the example of showing a record in one line.
EDIT:
OP has his own way of programming, but to satisfy his question in the comment - this is how you can do it.
while (rs2.next()) {
for (int i = 0; i < itemList.size(); i++)
{
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.print(rec[i]+"\t |");
}
System.out.println();
}

Dynamic addition & use of variable outside for loop- Selenium

Below is the scenario i am trying to automate:
Put all numerical values of the links in a Selenium Weblist & perform an addition and later to verify if the sum of count matches a fixed number.
The issue is that the numerical links returns a number engulfed in braces example:(20)(35)(16)(15)
I need to first trim these brackets & fetch only the numbers & then perform the addition i.e: 20+35+16+15
Later i need to assert the total against the number i.e: Assert.assertequals(sum,'86')
List<WebElement> lists=driver.findElements(By.cssSelector("span.ndocs"));
for (int i=0; i<lists.size(); ){
String trimmed_value=lists.get(i).getText();
trimmed_value=lists.get(i).getText().trim().substring(trimmed_value.indexOf("(") + 1);
trimmed_value=lists.get(i).getText().trim().substring(0, trimmed_value.indexOf(")"));
System.out.println(trimmed_value);
int numerical_value = Integer.parseInt(trimmed_value);
i++;
}
Till now i am able to get the elements, iterate them & able to remove the braces & get the numbers, I am stuck upon how to perform the addition operation & then do an Assert for the count.
Any help will be much appreciated here.
Try using below code.
Initialize a variable outside the method and add every trimmed_value to it as explained below.
import assertEquals(import static org.junit.Assert.assertEquals;)
int expected_value=86;
int numerical_value=0;
List<WebElement> lists = driver.findElements(By.cssSelector("span.ndocs"));
for (int i = 0; i < lists.size(); ) {
String trimmed_value = lists.get(i).getText();
trimmed_value = lists.get(i).getText().trim().substring(trimmed_value.indexOf("(") + 1);
trimmed_value = lists.get(i).getText().trim().substring(0, trimmed_value.indexOf(")"));
System.out.println(trimmed_value);
numerical_value =numerical_value+Integer.parseInt(trimmed_value);
i++;
}
assertEquals(expected_value, numerical_value);

Use Selenium to press tab and then write with java

I want selenium to press "TAB" for me and then write something in the focused field, now I know that I can use
sendKeys(Keys.TAB)
But as I understand it That require a locator behind it, I want to test the tab order of my page and to do so, I want to be able to focus on my first element only, then tab my way through the page like this:
--THE ELEMENTS IN THE TAB ORDER THEY ARE SUPOSED TO BE--
String[] elementArray = {"firstname","lastname", "phone", "email"};
for(int x = 0; x < 4; x = x+1)
{
WebElement theElement = driver.findElement(By.id(elementArray[x]));
if (x == 0) {driver.theElement.sendKeys(x)}
else{driver.(TheCurrentlyFocusedElement).sendKeys(x)}
String elementval = theElement.getAttribute("value");
assertEquals(x, elementval);
(TheCurrentlyFocusedElement).sendKeys(Keys.TAB);
}
So the question is, is there a method I can use that allows me to use the currently focused element as a locator? i.e.:
driver.focusedElement().sendKeys(Keys.TAB); ?
This is what you are looking for -
driver.switchTo().activeElement();
I have just had to do something similar but found that sending tab didn't actually change focus (it did when manual testing, just not via Selenium).
I wanted to prove the order of input fields on screen (positioning was more important then tabbing in this case), so had to do something like the following;
String[] elementArray = {"firstname","lastname", "phone", "email"};
List<WebElement> inputFields = driver.findElements(By.cssSelector("input"));
for(int x = 0; x < 4; x++)
{
assertEquals(elementArray[x], inputFields.get[x]);
}
I would probably create a list rather than an array, and compare those, but you should get the gist.
Yes, I know that this is quite a simplified approach and that this doesn't actually prove that fields are definitely in that order once rendered, but it gives you some security for regression.

How can Selenium RC process dynamic rows?

I have a table similar to the following:
Part #
Price
Status
1st Part #
$1.00
OK
2nd Part #
$2.00
Discontinued
Nth Part #
$N.00
Reordered
My java code will be looking for the status of "Nth Part #" where I have no idea how big the table is, how many columns it has, and no idea what N is (until run time). In Ruby/WATIR, I would have used the table's id to grab it's HTML, and then used Ruby to iterate over the rows until the part # matched, and then check that row's corresponding status in the Status column (whichever column that might be, but it's set in the hd header's row).
Selenium's standard table lookup function selenium.getTable("table.1.2") only works for static tables that contain the same contents for each test. The overkill selenium.get_html_source is a waste since selenium knows how to find the table already, plus then I have to parse the entire web page.
Any ideas on how I can grab the html of the table, and what would be the best way to iterate over the rows and/or columns?
Thanks in advance.
The easiest thing to do would be to use getTable like this
selenium.getTable("table." + (1 + n) + ".3")
to get the "Status" cell for the nth row if you know what n will be at runtime.
If you are trying to iterate over all of the rows in the table, you could do something like this
try {
for(int n = 1; true; n++) {
String cellContents = selenium.getTable("table." + n + ".3");
//do something with n
}
}
catch {
//handle end of table
}
or, alternatively
final int rowCount = (int)selenium.getXPathCount("id('table')/tbody/tr");
for(int n = 1; n < rowCount; n++) {
String cellContents = selenium.getTable("table." + n + ".3");
}
Remember that in getTable(locator.row.column), row and column start at 1.
Not exactly what you're asking for, but I solved a similar problem by assigning the unique id (part number it sounds like in your case) to be the html id of the tr. Then I used the Selenium xpath locators to get the row and columns I needed for my test.

Categories

Resources