selenium webdriver sendkeys intermittent issue - selenium

I have a web automation framework set up that works pretty well. I have a constant issue though that when using SendKeys to write to textboxes, quite often a letter gets missed out. So for example, if my dataset is "TestUserName", something like "TestUerName" gets sent example with a missing letter.
This is a big issue for me, as after the web tests concludes successfully I further check if the database was updated properly. So in the above example I would go to the UserName column and expect to find TestUserName, but the test would fail because TestUerName is found instead.
Any ideas please? I am using selenium 2.53.0.
My code below.
public void inputValue (Object [][] valuesFromExcel)
{
for (int rowNow = 0; rowNow < (valuesFromExcel.length); rowNow++)
{
String newValue = valuesFromExcel[rowNow][0].toString();
if (!newValue.equals(""))
{
WebElement currentElement = driver.findElement(By.id(valuesFromExcel[rowNow][1].toString()));
if (currentElement.getTagName().equals("input"))
{
currentElement.sendKeys(newValue);
}
else if (currentElement.getTagName().equals("select"))
{
new Select(currentElement).selectByVisibleText(newValue);
}
}
}
}
Thanks.

Instead of sending as a string, send it as char...
Convert the string to char and send each char one by one to the text box. Yes there will be a performance issue, but it works fine. It will not skip any of the letters

Related

If condition inside Concrete5 Job not working

I don't even have a clue why this is happening. The if condition in my job is not working properly. I triple checked the $flag variable and it is true. Still the code always goes to the else condition.
$flag = file_exists($csvFile);
if($flag){
//A big chunk of code
} else {
return 'Whatever you do I will always go here XD';
}
I hard coded true inside if, it works properly. Then another if inside that chunk of code also always goes to else. Again double checked Express. Express object exists and object is returned properly. And is_object returns true.
$flag = file_exists($csvFile);
if(true){
//Some code here
$entity = Express::getObjectByHandle('user');
if(is_object($entity)){
// Another chunk of code
} else {
return 'You cant escape from me that easily... XD';
}
//some code here
} else {
return "Now I'm a good boy";
}
Tried a bunch of things. The code works without any problems in single page controllers. What ever I do it's just not working. I'm running PHP 5.6.10 on MAMP. Conceret5 8.1.0
The only time I've seen something like this is with a buggy older version of PHP.
You could try moving some code around like so:
if($flag = file_exists($csvFile)) {
// code to handle file
} else {
// no file
}
A followup post would help...
Well. Looks like I found the fix. It looks like a simple matter but don't know for sure. I was running the job from dashboard, I didn't knew I could run the same job from the url as well (Automate job option URL). It worked fine when I ran it from URL and Magically it started working inside the Dashboard as well. I will look into it in detail when I get the time.

Cannot Instantiate class error - Selenium WebDriver using testng

I want to pass an integer variable to web element using Sendkey function and i'm getting that integer vaiable from another class and passing through a method and calling in sendkey funciton but getting type casting error.
I'm very new to selenium. Please help me to improve my selenium knowledge wider. Attached screen shot for your better understand.
public static WebElement setQuantityPage(WebDriver driver,int **individual_units**,int noOFCaseUnit, int noOfBox)
{
Select packType = new Select(driver.findElement(By.xpath(".//*[#id='fba-core-view-meta-data-pkg-type']/**strong text**dl/dd[1]")));
packType.selectByVisibleText("Individual products");
String type=packType.toString();
if(type.equalsIgnoreCase("Individual products"))
{
driver.findElement(By.xpath(".//*[#id='batch-update-number-cases']")).sendKeys(**individual_units**);
}
I'm asking for above bold letters.
else
{
}
return element;
}
Sendkeys methods takes only CharSequence as it's parameter. But your are passing an integer as an argument. That's why you are getting a type casting error. Replacing
driver.findElement(By.xpath(".//[#id='batch-update-number-cases']")).sendKeys(individual_units);
with
driver.findElement(By.xpath(".//[#id='batch-update-number-cases']")).sendKeys(individual_units+"");
or
driver.findElement(By.xpath(".//[#id='batch-update-number-cases']")).sendKeys(String.valueOf(individual_units));
will resolve your problem.

How to write a string in textfield which contains underscore in it using TestFX?

I am writing a simple login form in JavaFX for which I am writing a test program in TestFX. My TestFX script automatically types the credentials in the textfields and clicks the login button and it works fine further.
But when I want the script to type credentials which contain underscore, it doesn't type the underscore and types until the underscore comes. I have used backslash before underscore but it didn't help me.
Below is a screenshot of my login page.
Below is my test script which works fine when I give string without an underscore.
#Test
public void invalidCredentialsShouldNotLogin()
{
controller.click("#username").type("invalid");
controller.click("#password").type("invalid");
controller.click("#button");
verifyThat("#welcome", hasText("Login failed"));
}
And this is the script which tries to type a string which contains underscore in it and does not work as intended, and gives exception as invalid key code.
#Test
public void invalidCredentialsShouldNotLogin()
{
controller.click("#username").type("user_name");
controller.click("#password").type("invalid");
controller.click("#button");
verifyThat("#welcome", hasText("Login failed"));
}
This is the output of the above code.
The same thing happens when I use colon in place of underscore.
Please help me fix this. If you require any more information, please tell me. Thanks
I have got the answer of this question. Actually every special character like underscore or colon has a keycode associated with it. We have to use that keycode to type in the TextField using TestFX script.
In the question above, I wanted to type underscore. Usually when we type underscore, we press two keys together i.e. shift and hyphen (-). Same way we will use the keycodes of these two keys to type underscore using TestFX script.
Below is the code that worked for me and typed underscore in the TextField.
#Test
public void enterCredentialsWithUnderscore()
{
TextField usernameField = (TextField)GuiTest.find("#username");
if(username.indexOf("_") != -1)
{
String[] tokens = username.split("_");
for(int i=0; i<tokens.length; i++)
{
if (i == 0)
controller.click(usernameField).type(tokens[i]);
else
controller.push(KeyCode.SHIFT, KeyCode.MINUS).type(tokens[i]);
}
}
}
KeyCode.MINUS is keycode for hyphen key. And push(KeyCode.SHIFT, KeyCode.MINUS) method pushes the both buttons together thus typing underscore.
Below is a screenshot of the output I received.
Thanks to all.

Best way to find out if jqGrid is loaded and ready with Selenium

How are you finding out if jqGrid is loaded and ready to be used, via selenium.
Some details :
Im using C# driver
I have a method : new WebDriverWait(driver, new TimeSpan(0, 0, 0, 30)).Until(x => loadingdissapearedcondition) which im using to wait until Loading.. element is gone.
I also sometimes use this script :
private const string script = #"return ($('#{0}').jqGrid('getGridParam', 'reccount') !=x undefined) && ($('#{0}').jqGrid('getGridParam', 'reccount') != 0) && (!$('#load_{0}').is(':visible')) && (!$('#busyIcon').is(':visible'))";
private readonly string waitScript;
waitScript = string.Format(script, jqGridId);
public void WaitUntilLoadIconDissappears()
{
driver.WaitUntil(MAXWAIT, Wait);
}
public bool Wait()
{
var executeScript = ((IJavaScriptExecutor) driver).ExecuteScript(waitScript);
bool result;
bool tryParse = bool.TryParse(executeScript.SafeToString(), out result);
return tryParse && result;
}
to find if jqGrid has records and loading done.
I require something better - as even the above two does not make driver wait until load finishes, if we are using local data for jqGrid. Im also curious what is the best way, or at the minimum, how others are dealing with this problem.
I never used Selenium before, so I'm not sure that I understood your problem correctly. jqGrid will be first initialized and then (optionally) the data can be loaded from the server. During the initializing stage the original <table id="grid"></table> element will be converted to relatively complex HTML fragment which is the grid. At the end of the initialization the DOM element of the table (the $("#grid")[0]) will get the expando grid.
So you can use the test like
if ($("#grid")[0].grid) {
// grid is initialized
}
to determine that the grid is already initialized. jqGrid uses the same test internally (see here for example).
Here is solution for Java and jqgrid.
If grid data is not loaded yet then right pager has no value, so simply check its length. Methods such as isElementPresent, isDisplayed etc. seems not to work for grid right pager object. It's always present in page code while ajax, but text value is set when dynamic data is loaded.
public void waitForGridPagerRight(String gridName) throws Exception {
for (int second = 0;; second++) {
if (second >= 15) {
fail("Timeout.");
}
try {
if (driver
.findElement(By.id("pager_" + gridName + "_right"))
.getText().length() > 2)
break;
} catch (Exception e) {
}
Thread.sleep(1000);
}
}
Not sure why #Oleg's answer didn't work for me. It seemed like grid was being populated even before the ajax call was being made. It appears there's some change in newer versions maybe. It look like the last thing to happen in the ajax call is that the "loading" block is hidden, so instead I find that element and check it's display attribute a la:
def wait_for_jqgrid(self, t=20):
def check_jqgrid(driver):
#the last thing jqgrid does after the ajax call is to turn off the loading div
#so we find it and check to see if its display attribute is no longer set to 'none'
script = 'pid = $.jgrid.jqID($(".ui-jqgrid-btable").get(0).p.id); return $("#load_"+pid).get(0).style.display == "none";'
return driver.execute_script(script)
WebDriverWait(self.driver, t).until(check_jqgrid)
When the loading div is hidden, we are done. This is python but the same javascript bit should work in Java or whatever.

sprintf() and WriteFile() affecting string Buffer

I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:
1) read a byte from the serial port
2) store each char into tagBuffer as they are read
3) run a query using tagBuffer to see what type of tag it is (book or shelf tag)
4) depending on the type of tag, output a series of bytes corresponding to the type of tag
Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.
The lines are the two lines at the very bottom:
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().
I thought sprintf and WriteFile are I/O functions and would have no effect on variables.
I'm stuck and I need help to fix this.
//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// resets tagBuffer in case tagBuffer is out of sync
time_t t_time = time(0);
char buf[50];
if (HasOverlappedIoCompleted(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if( strlen(tagBuffer) >= PACKET_LENGTH )
{
i = 0;
}
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
sprintf(query,"select type from rfid where rfidnum=\"");
strcat(query, tagBuffer);
strcat(query, "\"");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&mysql);
while(row = mysql_fetch_row(res))
{
printf("result of query is %s\n",row[0]);
string str = "";
str = string(row[0]);
if( str == "book" )
{
WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else if ( str == "shelf" )
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&ovWrite);
}
}
mysql_free_result(res);
// Display a response to input
//printf("query is %s!\n", query);
//printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer));
//without these, tagBuffer only holds the last character
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
}
}
With those two lines, my output looks like this:
s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001
Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.
Any help at all will be greatly appreciated. Thanks.
Where are you allocating tagbuffer, how large is it?
It's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.
It seems unlikely that those two lines would have that effect on a correct program - maybe you haven't allocated sufficient space in buf for the whole length of the string in tagBuffer? This might cause a buffer overrun that is disguising the real problem?
The first thing I'd say is a piece of general advice: bugs aren't always where you think they are. If you've got something going on that doesn't seem to make sense, it often means that your assumptions somewhere else are wrong.
Here, it does seem very unlikely that an sprintf() and a WriteFile() will change the state of the "buf" array variable. However, those two lines of test code do write to "hSerial", while your main loop also reads from "hSerial". That sounds like a recipie for changing the behaviour of your program.
Suggestion: Change your lines of debugging output to store the output somewhere else: to a dialog box, or to a log file, or similar. Debugging output should generally not go to files used in the core logic, as that's too likely to change how the core logic behaves.
In my opinion, the real problem here is that you're trying to read and write the serial port from a single thread, and this is making the code more complex than it needs to be. I suggest that you read the following articles and reconsider your design:
Serial Port I/O from Joseph Newcomer's website.
Serial Communications in Win32 from MSDN.
In a multithreaded implementation, whenever the reader thread reads a message from the serial port you would then post it to your application's main thread. The main thread would then parse the message and query the database, and then queue an appropriate response to the writer thread.
This may sound more complex than your current design, but really it isn't, as Newcomer explains.
I hope this helps!