Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Thursday, November 7, 2013

C#: Avoiding the WebDriverException: No response from server for url


When it comes to automated testing, there’s not much worse than intermittent failures, especially when they stem from the driver itself. The current version of the C# WebDriver bindings has such a failure, but I worked out a reasonable way to avoid it happening. Basically it involves creating a WebDriver extension method that I use instead of Driver.FindElement, which tries a number of times to find the element, ignoring the exception that is intermittently raised.

I hope you find this useful if you’re consuming WebDriver in C#.
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace Extensions
{
    public static class WebDriverExtensions
    {
        public static SelectElement GetSelectElement(this IWebDriver driver, By by)
        {
            return new SelectElement(driver.GetElement(by));
        }
        public static IWebElement GetElement(this IWebDriver driver, By by)
        {
            for (int i = 1; i <= 5; i++ )
            {
                try
                {
                    return driver.FindElement(by);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception was raised on locating element: " + e.Message);
                }
            }
            throw new ElementNotVisibleException(by.ToString());
        }
    }
}


=====================
I think this is what the WebDriverWait class in the WebDriver.Support library is for, isn’t it? We have an extension method that wraps this:
public static T WaitUntil(this IWebDriver browser, Func condition,
string failMessage, int timeoutSeconds = 15)
{
// helper for inserting browser name in failure messages
failMessage = failMessage.Replace(“@Browser”, string.Format(“{0} browser”, browser.GetName()));
try
{
// if the condition does not become true within timeoutSeconds, an exception will be thrown.
return new WebDriverWait(browser, new TimeSpan(0, 0, 0, timeoutSeconds, 0))
.Until(condition);
}
catch (Exception ex)
{
// if an exception was thrown, fail the test and return
Assert.Fail(string.Format(“{0} ({1})”, failMessage, ex.Message));
}
return default(T);
}
Usage:
// this example returns an IWebElement, but you can also do conditions that evaluate
// to true/false. If condition does not become true within timeoutSeconds, test fails
var webElement = driver.WaitUntil(d => d.FindElement(By.CssSelector("h1:first")), "error message to display on fail", 5);
However, we do get intermittent no response from session during Click, SendKeys, Clear, etc, at times. For these we have taken similar approach — just keep trying and catching WebDriverException until the session responds.
 public static void ClickWebElement(this IWebElement webElement)
{
if (webElement == null)
throw new ArgumentNullException(“webElement”);

bool exceptionCaught;
do
{
exceptionCaught = false;
try
{
webElement.Click();
}
catch (WebDriverException)
{
exceptionCaught = true;
}

} while (exceptionCaught);
}
Taken from here : http://watirmelon.com/2011/10/04/c-avoiding-the-webdriverexception-no-response-from-server-for-url/

Sunday, October 27, 2013

Selenium Tips: CSS Selectors in Selenium Demystified


Following my previous TOTW about improving your locators, this blog post will show you some advanced CSS rules and pseudo-classes that will help you move your XPATH locators to CSS, a native approach on all browsers.

Next sibling

Our first example is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username.
 
<form>
<input class="username"></input>
<input class="alias"></input>
</form>
Let’s write a css selector that will choose the input field after "username". This will select the "alias" input, or will select a different element if the form is reordered. css=form input.username + input

Attribute values

If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form without adding a class.
 
<form>
<input name="username"></input>
<input name="password"></input>
<input name="continue" type="button"></input>
<input name="cancel" type="button"></input>
</form>
We can easily select the username element without adding a class or an id to the element.
 
css=form input[name='username']
We can even chain filters to be more specific with our selections.
 
css=input[name='continue'][type='button']
Here Selenium will act on the input field with name="continue" and type="button"

Choosing a specific match

CSS selectors in Selenium allow us to navigate lists with more finess that the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type.
<ul id="recordlist">
<p>Heading</p>
 
    <li>Cat</li>
    <li>Dog</li>
    <li>Car</li>
    <li>Goat</li>
 
</ul>
If we want to select the fourth li element (Goat) in this list, we can use the nth-of-type, which will find the fourth li in the list.
  
css=ul#recordlist li:nth-of-type(4)
On the other hand, if we want to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case.
 
css=ul#recordlist li:nth-child(4)
Note, if you don’t specify a child type for nth-child it will allow you to select the fourth child without regard to type. This may be useful in testing css layout in selenium.
 
css=ul#recordlist *:nth-child(4)

Sub-string matches

CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each:
^=  Match a prefix
$=  Match a suffix
*=  Match a substring
 
css=a[id^='id_prefix_']
A link with an "id" that starts with the text "id_prefix_"
 
css=a[id$='_id_sufix']
A link with an "id" that ends with the text "_id_sufix"
 
css=a[id*='id_pattern']
A link with an "id" that contains the text "id_pattern"

Matching by inner text

And last, one of the more useful pseudo-classes, :contains() will match elements with the desired text block:
  
css=a:contains('Log Out')
This will find the log out button on your page no matter where it’s located. This is by far my favorite CSS selector and I find it greatly simplifies a lot of my test code.
Tune in next week for more Selenium Tips from Sauce Labs.
Sauce Labs created Sauce OnDemand, a Selenium-based testing service that allows you to test across multiple browsers in the cloud. With Selenium IDE and Selenium RC compatibilities, you can get complete cross-platform browser testing today.

Taken for personal notepad from http://sauceio.com/index.php/2010/01/selenium-totw-css-selectors-in-selenium-demystified/, all credit goes there

Selenium css locators tutorial with example

Selenium css locators tutorial with example

As you know, Locators in selenium are main elements and CSS Locator is another alternative of Xpath element locator, ID or Name locator or any other element locators in selenium. Full form of CSS is "Cascading Style Sheets" and it define that how to display HTML elements on webpage. Click here to read more about CSS. There are few advantages and also few disadvantages of using CSS element locators at
place of Xpath element locators in selenium.
CSS Locators Main Advantage
Main advantage of using CSS locator is - It is much more faster and simpler than the Xpath Locators in IE and also they are more readable compared to Xpath locators. Also CSS locators are little faster compared to Xpath locators in other browsers.

Note : Need good working examples on selenium IDE? Visit this link for great tutorials on selenium IDE.
Now let me come to our main point - How to write CSS locator syntax manually for selenium. I have derived couple of CSS locator syntax with example as bellow. I written CSS locator syntax for three elements(Search text box, Select language drop down and "Go" button) of wikipedia website home page as shown in bellow image.
CSS locator Examples
1. Selenium CSS locator using Tag and any Attribute
css=input[type=search]
\\\\ This syntax will find "input" tag node which contains "type=search" attribute.
css=input[id=searchInput]
 \\\\ This syntax will find "input" tag node which contains "id=searchInput" attribute.
css=form input[id=searchInput]
 \\\\  This syntax will find form containing "input" tag node which contains "id=searchInput" attribute.
(All three CSS path examples given above will locate Search text box.)
2. Selenium CSS locator using Tag and ID attribute
css=input#searchInput
\\\\ Here, '#' sign is specially used for "id" attribute only. It will find "input" tag node which contains "id=searchInput" attribute. This syntax will locate Search text box.
3. Selenium CSS locator using Tag and class attribute
css=input.formBtn
 \\\\  Here, '.' is specially used for "class" attribute only. It will find "input" tag node which contains "class=formBtn" attribute. This syntax will locate Search button (go).
4.  Selenium CSS locator using tag, class, and any attribute
css=input.formBtn[name=go]
 \\\\ It will find "input" tag node which contains "class=formBtn" class and "name=go" attribute. This syntax will locate Search button (go).
5. Tag and multiple Attribute CSS locator
css=input[type=search][name=search]
\\\\  It will find "input" tag node which contains "type=search" attribute and "name=search" attribute. This syntax will locate Search text box.
6. CSS Locator using Sub-string matches(Start, end and containing text) in selenium
css=input[id^='search']
 \\\\  It will find input node which contains 'id' attribute starting with 'search' text.(Here, ^ describes the starting text).
css=input[id$='chInput']
 \\\\  It will find input node which contains 'id' attribute starting with 'chInput' text. (Here, $ describes the ending text).
css=input[id*='archIn']
 \\\\  It will find input node which contains 'id' attribute containing 'archIn' text. (Here, * describes the containing text).
(All three CSS path examples given above will locate Search text box.)
7. CSS Element locator syntax using child Selectors
css=div.search-container>form>fieldset>input[id=searchInput]
 \\\\  First it will find div tag with "class = search-container" and then it will follow remaining path to locate child node. This syntax will locate Search text box.
8. CSS Element locator syntax using adjacent selectors
css=input + input
 \\\\  It will locate "input" node where another "input" node is present before it on page.(for search tect box).
css=input + select
or
css=input + input + select
 \\\\  It will locate "select" node, where "input" node is present before it on page(for language drop down).

9. CSS Element locator using contains keyword
css=strong:contains("English")  \\\\ It will looks for the element containing text "English" as a value on the page.
taken for snippet from : http://software-testing-tutorials-automation.blogspot.com/2013/06/selenium-css-locators-tutorial-with.html

Saturday, October 26, 2013

Auto Multi Upload using C#, Selenium, and AUTOIT.

Files to upload ( with different path ):

"C:\40vid\Curse of Chucky\Curse of Chucky.mp4"
"C:\40vid\Restrepo\Restrepo.mp4" 


Using this method will not working, using Process.Start

'"C:\40vid\Curse of Chucky\Curse of Chucky.mp4" "C:\40vid\Restrepo\Restrepo.mp4"'
and this
""C:\40vid\Curse of Chucky\Curse of Chucky.mp4" "C:\40vid\Restrepo\Restrepo.mp4""

To work on windows ( using xp sp3 ) from commandline using Process.Start, space must inside double quote

like this:
" 'C:\40vid\Curse of Chucky\Curse of Chucky.mp4' 'C:\40vid\Restrepo\Restrepo.mp4' "
But if we use path like that, will not working on Upload windows.

Solutions

In C#

string gb1 = @"C:\40vid\Curse of Chucky\Curse of Chucky.mp4";
string gb2 = @"C:\40vid\Restrepo\Restrepo.mp4";
string jadikansatu = @"""" + "'" + gb1 + "'" + " " + "'" + gb2 + "'" + @"""";
 
 

 
In AutoIt v3
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Outfile=D:\Bara\selenium&autoit\youtubeauto.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
WinWait ("File Upload");
WinActivate("File Upload");
;Local $file = '"C:\40vid\Curse of Chucky\Curse of Chucky.mp4" "C:\40vid\Restrepo\Restrepo.mp4"';
;ControlSetText("File Upload", "", "[CLASS:Edit; INSTANCE:1]", ''&$file&'' )

$removedoublequotes = StringReplace($CmdLine[1], '"', '')
$gantisinglequotes2double = StringReplace($removedoublequotes, "'", '"')
ControlSetText("File Upload", "", "[CLASS:Edit; INSTANCE:1]", $gantisinglequotes2double)
ControlClick("File Upload", "", "[CLASS:Button; INSTANCE:2]")
;ControlClick("File Upload", "", "[CLASS:Button; INSTANCE:2]")



and compile to auto.exe

add this before clicking browse button and done
Process.Start(@"C:\auto.exe", jadikansatu);
Problem solve

Friday, March 22, 2013

Uploading with Selenium RC in FF or IE


Here I would like to share my experience on handling file upload using selenium. Handling File upload with selenium I spent more than two days and googled many sites to overcom this. At last I was able to crack this and found solution for the same. This script is devledoped in Java and can be easily coverted to any other langugage.
To handle file upload using selenium RC (1.0 or higher) comes with two challenges.
1. Clicking on Browse/Upload button. ( As Upload buttion come with input type File which is combination of both text box and Browse button).
2. Selecting a file from windows dialog.
I will share handling this on both Fire fox and IE.
Handling file upload in Fire Fox:

Its really very simple when comes to handle file upload in Fire Fox. You just need to use selenium.type command for input file=type control.
Lets take below sample html code.


All you just need to do is use below command to upload file.
selenium.type("//input[@name='fileupload']","c:\test.txt")
Type command take care of uploading file automatically. No other code is required to handle this.

IE:

When it comes to IE its little tricky. Follow below steps.
1. Download AutoIt latest version.
2. Open new editor and past below code in editor.
If $CmdLine[0]<2 data-blogger-escaped-controlclick="" data-blogger-escaped-controlsettext="" data-blogger-escaped-define="" data-blogger-escaped-dit1="" data-blogger-escaped-else="" data-blogger-escaped-endfunc="" data-blogger-escaped-endif="" data-blogger-escaped-exit="" data-blogger-escaped-false="" data-blogger-escaped-fild="" data-blogger-escaped-file="" data-blogger-escaped-func="" data-blogger-escaped-function="" data-blogger-escaped-handleupload="" data-blogger-escaped-if="" data-blogger-escaped-into="" data-blogger-escaped-mdline="" data-blogger-escaped-path="" data-blogger-escaped-pre="" data-blogger-escaped-put="" data-blogger-escaped-return="" data-blogger-escaped-text="" data-blogger-escaped-then="" data-blogger-escaped-to="" data-blogger-escaped-uploadfile="" data-blogger-escaped-utton2="" data-blogger-escaped-winactivate="" data-blogger-escaped-winwait="" title="">
4. Go to Tools menu click on build the code. It will generate an .exe (e.g. upload.exe)
5. Now write a function in java to make a call to aboe auto it function. Below is sample code for the same.

public void handleUpload(String windowtitle, String filepath) {
         String execute_file = "upload.exe";
         String cmd = "\"" + execute_file + "\"" + " " + "\"" + windowtitle + "\""
                                   + " " + "\"" + filepath + "\""; //with arguments
         try {
                 Process p = Runtime.getRuntime().exec(cmd);
                
         } catch (Exception e) {
                 e.printStackTrace();
         }

}
6. In you TC first call above java function ( remember first you need to call function before click on browse button. Else control never comes back to your code if you click browse button first. 7. Now click on upload button using selenium.click("//input[@name='fileupload']"). In other browsers like chrome and safari I tired either type or AutoIt code will function successfully. Taken From http://www.boddunan.com/articles/programming/69-others/18396-handling-file-upload-using-selenium-rc-in-ie-and-firefox.html NOTE: I still have no luck with auto uploading in swf flash auto upload..

Selenium AUTO UPLOAD [SOLVE]


Hi everyone.
I have a problem with automatic testing using Selenium IDE. I need to upload a file but Selenium seams unable to perform click on browse button. Using http://www.extjs.com/deploy/dev/exam...le-upload.html I can focus browse button but firing selenium click or clickOn event don't produce anything. Am I doing something wrong or is this some Selenium IDE limitation? Any help will be appreciated

the SOLVE is

In my Selenium tests I want to upload some files. However, due to security restrictions in the browser a JavaScript cannot fill in a path in the respective file input field by default. Fortunately, there exists a workaround (originally from http://lists.public.thoughtworks.org/pipermail/selenium-users/2005-March/000213.html).
In FireFox enter "about:config" in the address bar, and set the value of "signed.applets.codebase_principal_suppor" to "true". This allows non-signed scripts to request higher privileges.
In Selenium we then have to request the privilege to upload local files by adding the following JavaScript snippet to the function "Selenium.prototype.doType" in the file "selenium-api.js":
netscape.security.PrivilegeManager.enablePrivilege('UniversalFileRead');
Update 2009-01-04: Fixing links, fixing problem with quotes which got messed up by WordPress.




TAKEN FROM :

http://www.sencha.com/forum/showthread.php?82411-Selenium-and-File-Upload-Field
http://cakebaker.42dh.com/2006/03/29/file-upload-with-selenium/

//Taken for note :D