Total Pageviews

Monday 16 July 2012

Selenium 8


The only topic with more information online than interview tips is ways to deal with sexuality issues. 
Sites and books and self-help courses on how to crack a job interview come cheaper than a dime a dozen, yet when their advice doesn’t work, the blame is conveniently laid on the larger number of applicants than available jobs.
They say that the best jobs aren’t advertised, and I quite believe them. After all, how often have you seen openings for CEOs and MDs? LinkedIn lists some vacancies that aren’t advertised openly, and other important posts are filled through a referral system. Ramit Sethi, a 29-year-old US-born Indian who runs a course called Dream Job Boot Camp, says that it’s all about the contacts, but how does a guy without networking skills make his way up in corporate India?
I encourage you to check out Ramit at IWillTeachYouToBeRich.com, but just as a teaser, here are a few tips from the pro himself that are guaranteed to get you noticed and taken seriously at an interview:
1. Find the 3 must-says that you want your interviewer to know about you, that you don’t want to get out of the room without saying
It’s happened to me so often, has it happened to you too? You walk out of the interview knowing that you haven’t made the impression you’d have wanted to, knowing that the conversation didn’t go the way you’d planned. What you should do is preplan what you absolutely have to tell the interviewer before you get out. Then, if possible, weave this into your resume, into the headline or objective.
Yes, that means tailoring your CV to fit each organization and post that you apply to. Yes, it means that you must do considerable research about the organization and the solutions it’s looking for. And yes, this extra work will be worth your while.
2. Handpick what you want to tell the interviewer when he asks you to tell him about yourself
I used to begin answering these types of questions by giving the interviewer a rundown of my educational qualifications, until one manager asked to me to stop giving him facts and start telling him about the ‘real me’. I guess it comes down to whether or not you think you are a worthwhile person if you couldn’t talk about your degrees and your job history. Besides, why would I want to waste the interviewer’s time by regaling him with information that I had already put down in my resume?

This is the time to tell the interviewer, even boast a bit, about why you’re a well-rounded, self-actualized person in your own right. What personal accomplishments are you most proud of? What are your goals (but please keep these in line with the company’s vision.) In my case, I began to speak about my black-belt status in Tae Kwon Do, which is a form of kick-boxing, and then I really watched managers’ eyes light up. Keep this part of the interview short and sweet, though; talk about two or three of your achievements in brief instead of describing incidents in your life.
3. Tell a riveting story when asked for your weak point. But don’t try to make it sound positive
The one rule that all interview websites recommend is naming your supposed ‘weak points’ but making them sound positive. Take a moment to laugh at the idea that someone’s only claim to shame is that they’re a workaholic, or that they are too detail-oriented, or that they take copious notes at meetings.

While I agree that interviewers should stay away from this question, because, let’s accept it, how honest can a person be when he wants a job that you might never hand him if he were to tell you that he’s a procrastinator, I use the time I saved in point 2 to tell a detailed story when asked this question. It works, and I’m not sure whether the additional detail convinces the interviewer that I’m telling the truth, or whether he just bores of me and proceeds to the next question.
4. Show how you are better than most people/other interviewees
I know, easier said that done. But this is where your research about the needs of this company comes in. if you know that the company is currently facing so-and-so problem, which you might be expected to help tackle if you are taken aboard, why not give your interviewer some ideas about how you’d go about handling the situation? This is guaranteed to blow him away even if the other applicants for the post are better qualified and more experienced than you are.
The most important way to really crack an interview is not on this list, but it’s also the most important way to succeed at life: be confident. If you haven’t perfected this skill, check out where the closest personality development school in your locality is located.
Often, the people who get the best jobs act like they believe that they can do the impossible and so should you.
Writing the first test :
To quickly write some tests that you can use as a foundation for your automated tests, you can use Selenium IDE to get started. Selenium IDE is a plug-in for Firefox that lets you record tests. You can then export the recorded tests so that you can add fanciness to them—conditions, iterations, and so on.
To get started with Selenium IDE, download it from the link in Resources. Install it as a Firefox plug-in by clicking the link. Firefox should prompt you to install the plug-in, and then you must restart the browser for the changes to take effect.
After you have the plug-in installed, start your server so you can begin using your web application. Open Selenium IDE by clicking Tools > Selenium IDE in Firefox. When Selenium IDE is open, click Record. After Selenium IDE is recording, it will remember all of the actions that you take in the browser. To log in to your sample application, perform the following steps:
  1. With Selenium IDE recording, navigate to the index.jsp web page.
  2. Type your user name.
  3. Type the valid password in the Password box.
  4. Click Login.
Upon successful login, your web application should go to the enterInfo.jsp page. At this point, your test has the actions in it, but so far, there is nothing to verify that your actions worked. Selenium needs to know what to look for in order to know that your enterInfo.jsp page is being rendered as expected.
You can add verify actions to make sure your application is displaying the correct content. While Selenium is still recording, perform the following steps:
  1. Right-click one of the HTML elements, such as the Your name label, and then click verifyTextPresent Your name:.
  2. Repeat step 1 with the Your birth date label.
  3. Click Record to stop recording.
If you want to see your test in action, click Run All (see Figure 1). The test will execute and pass.
To see how Selenium IDE is really testing your application, go to your IDE and change the value of the valid user name. Re-deploy your application, and then click Run All again. This time, your tests will fail, because the web application will not display the enterInfo.jsp page with the correct labels.
Exporting the test to JUnit
Now that you have recorded your first test, you can export it for use in JUnit. With your test highlighted in Selenium IDE, click File > Export Test Case As > Java (JUnit) - Selenium RC. Type the name for your test (for example, IndexTests.java), and save it where you can remember it so that you can import it into Eclipse.
Perform the following steps:
  1. Create a new Java project that includes the Java unit tests built using JUnit.
  2. Download the Selenium RC binaries (see Resources for a link). Save the archive file to a location where you can import the files inside it into your new Java project in Eclipse.
  3. Create a new folder in your Java project called lib.
  4. Click File > Import, and then click File System from the list. Click Next.
  5. Browse to the location in which you extracted the Selenium RC files, and choose the selenium-java-client-driver-1.0.1 directory.
  6. Select the selenium-java-client-driver.jar from the list, and click OK to import the Selenium Java client driver JAR file into your project's lib directory.
  7. Import the Java file that you exported from Selenium IDE into the src directory of your new Java project.
The first thing you'll notice is that you will get many compile errors. First, your new Java file is probably not in the correct package, because it's directly in the src folder. Second, the JUnit or Selenium classes cannot be found. Fortunately, these errors are easy to resolve using Eclipse.
Resolving errors in Eclipse
Resolve the package errors by clicking the error, and then pressing Ctrl-1 to open the hints. Select Move MyTest.java to package 'com.example.mywebapp.tests'. Eclipse creates the package structure for you and moves the file.
Adding the JUnit test
Now, add the Selenium and JUnit test by clicking the Java project in Package Explorer and clicking Build Path > Configure Build Path. On the Libraries tab, click Add JARs, and select the selenium-java-client-driver.jar file. Click OK.
When the Java source file is compiling, it should look similar to Listing 3.
                    
package com.example.mywebapp.tests;
 
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;
 
import org.junit.BeforeClass;
import org.junit.Test;
 
public class MyTest extends SeleneseTestCase {
    
    @BeforeClass
    public void setUp() throws Exception {
        setUp("http://localhost:8080/tested-webapp/index.jsp", "*chrome");
    }
    
    @Test
    public void testMy() throws Exception {
        selenium.open("/tested-webapp/index.jsp");
        selenium.type("username", "user");
        selenium.type("password", "secret");
        selenium.click("//input[@value='Login']");
        selenium.waitForPageToLoad("30000");
        verifyTrue(selenium.isTextPresent("Your name:"));
        verifyTrue(selenium.isTextPresent("Your birth date (in MM/DD/YYYY format):"));
    }
}

If you are unable to download and install Selenium IDE because you have restrictions that prevent you from using Firefox, you can still write tests that you can run using Selenium RC. Just use the examples shown here as a start and the documentation for Selenium provided in Resources.
Viewing the test results
Now that you have the first example test written, you can see it in action by starting the Selenium server and running the test as a standard JUnit unit test. Start the Selenium server by typing the following command:
java -jar selenium-server.jar

Running the server from the IDE

For a fully integrated experience, you can set up an external tool configuration in Eclipse to start the Selenium server directly from Eclipse. Click Run > External Tools > External Tool Configurations to set up the configuration. Simply enter the command for starting the server into a new tool configuration.
After you have the Selenium server started, you can run the unit test by right-clicking the IndexTest.java file, and then clicking Run As > JUnit Test. It may take a while as the Selenium server starts up an instance of your browser and runs the tests. When the test is finished, you will see the same output in Eclipse as with normal unit tests.
Digging deeper
Now that you've used Selenium IDE to create a simple test and exported it as a Java file, create a more complicated test to verify the functions of the enterInfo.jsp page. The example test is shown in Listing 4.
                    
package com.example.mywebapp.tests;
 
import org.junit.BeforeClass;
import org.junit.Test;
 
import com.thoughtworks.selenium.SeleneseTestCase;
 
public class EnterInfoTests extends SeleneseTestCase {
    
    @BeforeClass
    public void setUp() throws Exception {
        setUp("http://localhost:8080/tested-webapp/index.jsp", "*firefox");
    }
    
    @Test
    public void testBadDate() {
        doLogin();
        selenium.type("name", "User");
        selenium.type("birthdate", "@#$#@");
        selenium.click("//input[@value='Submit']");
        selenium.waitForPageToLoad("30000");
        verifyTrue(selenium.isTextPresent("Please enter a valid date"));
    }
    
    @Test
    public void testValidDate() {
        doLogin();
        selenium.type("name", "User");
        selenium.type("birthdate", "12/2/1999");
        selenium.click("//input[@value='Submit']");
        selenium.waitForPageToLoad("30000");
        verifyFalse(selenium.isTextPresent("Please enter a valid date"));
    }
    
    private void doLogin()
    {
        selenium.open("/tested-webapp/index.jsp");
        selenium.type("username", "user");
        selenium.type("password", "secret");
        selenium.click("//input[@value='Login']");
        selenium.waitForPageToLoad("30000");
    }
}

The example test used the LoginTest class shown in Listing 3 as a starting point. The doLogin() function has the code to log you in to the application, which is used at the start of the tests to get you to the proper point.
The testBadDate() method is used to enter bad values into the birthdate field on the form, and then submit it. It verifies that the appropriate error message is displayed if the date is incorrect. The testValidDate() method tests the valid date on the form and makes sure the message that provides the user's age is correct.
Using the power of Java technology available to you in JUnit, you can loop through examples, add conditions to your tests, and expect exceptions. See the links in Resources to learn more about JUnit and unit testing.
Automating the tests
Now that you have the tests running in the Eclipse IDE, with the help of an Apache Ant script and a few targets, you can automate the tests completely. After you have this Ant script, you can use tools such as Hudson or CruiseControl (see Resources) to run these tests continuously.
To automate the test, you can use an Ant script that employs the JUnit target to execute the Selenium RC tests. The script is shown in Listing 5.
                    
<project name="tested-webapp-tests" default="run-tests" basedir=".">
 
    <property name="selenium.server.jar" value="path/to/selenium-server.jar" />
    <property name="src" value="${basedir}/src" />
    <property name="build" value="${basedir}/bin" />
    <property name="lib" value="${basedir}/lib" />
 
    <path id="classpath">
        <fileset dir="${lib}" includes="**/*.jar" />
    </path>
 
    <target name="start-selenium-server">
        <java jar="${selenium.server.jar}" fork="true" spawn="true">
            <arg line="-timeout 30" />
        </java>
    </target>
 
    <target name="compile-tests">
        <javac srcdir="${src}" destdir="${build}" fork="true" />
    </target>
 
    <target name="run-tests" depends="compile-tests">
        <junit printsummary="yes">
            <classpath>
                <path refid="classpath" />
            </classpath>
 
            <batchtest fork="yes">
                <fileset dir="${src}">
                    <include name="**/*Tests.java" />
                </fileset>
            </batchtest>
        </junit>
        <echo message="Finished running tests." />
    </target>
 
    <target name="stop-selenium-server">
        <get taskname="selenium-shutdown" 
            src="http://localhost:4444/selenium-server/driver/?cmd=shutDown" 
            dest="result.txt" 
            ignoreerrors="true" />
    </target>
 
    <target name="run-all">
        <parallel>
            <antcall target="start-selenium-server">
            </antcall>
            <sequential>
                <echo taskname="waitfor" message="Wait for proxy server launch" />
                <waitfor maxwait="1" maxwaitunit="minute" checkevery="100">
                    <http url="http://localhost:4444/selenium-server/
                        driver/?cmd=testComplete" />
                </waitfor>
                <antcall target="run-tests">
                </antcall>
                <antcall target="stop-selenium-server">
                </antcall>
            </sequential>
        </parallel>
    </target>
 
</project>

The Ant script has three targets. The first target, start-selenium-server, starts the Selenium server in forked and spawned mode so that it runs in the background. The run-tests target actually executes the JUnit tests, and the stop-selenium-server target stops the server by calling a URL that sends the server a shutdown command.
Using an Ant script like this one, you can run the Selenium tests in an automated fashion by scheduling them or using the Ant script in a continuous integration tool. See Resources for links to more information about continuous integration builds.
Running the tests in other browsers
As written so far in this example, the tests are executed in Firefox. However, there may be times when it is necessary to test the web application in other browsers to make sure functions work across browsers.
You may have noticed that when the Selenium tests where set up in the setUp() method of the JUnit test, *chrome was passed as the second parameter to the parent's setUp() method. This parameter starts an instance of the Firefox browser.
To run the test for a different browser, simply supply the name of the browser as the second argument. For example, *iexplore uses Internet Explorer as the browser instead of Firefox. Use *opera for the Opera browser or *safari for Apple Safari.
Note that the browser must be supported on the operating system on which you are running the tests. You will get exceptions and, therefore, failed tests if you attempt to execute tests for a browser that doesn't exist on your operating system, such as *safari or *iexplore on a system running Linux®.
Conclusion
This article introduced Selenium and two of its components: Selenium IDE and Selenium RC. Selenium IDE is an easy way to start writing tests for your web applications. Selenium RC is a component that you can use to add features to and automate your tests.
Automated web application testing from the browser perspective can be a great way to augment existing unit tests that cover other parts of your application. With automated testing, developers can get faster feedback on problems, and testing regressions becomes faster.

Resources
Learn
Get products and technologies
Discuss



Selenium Core FAQ

This is an initial list of FAQs that have been collected for Selenium Core. We encourage people to add to this list and continue feedback on the items listed below.

What is Selenium for?

It is used for functional or system testing web applications. These tests are also sometimes called acceptance, customer, or integration tests. Selenium is not meant for unit testing.

Why can't I get Selenium Core tests to work with Google?

I was trying to write a simple script that does a google search; I get a "Permission Denied" error. Here is my test:
Test Type


open

type
q
testing tools
click
Submit Button

The quick answer is that because of cross-site scripting security built into JavaScript engines in all browsers, you can't edit the content of a web page from another domain. The foreign page will probably load correctly and be visible in the test runner window, but Selenium won't be able to query or edit its contents. ..
In other words, you can't run selenium on "foo.com" and run a test that edits values and clicks buttons against "bar.com". So, in its current form, you can't "script" google.com because your script isn't currently hosted on google.com. When Selenium and the application you are testing is hosted on the same domain, however, you do not run into the cross-site scripting security feature/limitation.
You can read more about cross-site scripting here: Dev Articles

How can I run my test against a foreign or remote server and get around cross-site scripting security?

There are a few ways around cross-site scripting:
  1. If possible, deploy Selenium Core, and your tests, on the same web site as the application you're testing.
  2. You may need to use Selenium IDE or Selenium Remote Control to run your tests. See Which Selenium Tool Should I Use?
    Selenium IDE is a Firefox extension, (it runs as a "chrome" url) and is therefore not subject to browser security restrictions. Selenium Remote Control provides a client-configured proxy to trick the browser into the thinking the application and the testing tool are coming from the same domain.
  3. IE Only: Run Selenium as an "HTA" application, or "HTML Application" in Internet Explorer. HTA applications run in the security context of any trusted application on the client, so there is no cross-site scripting limitation. (You can find out more here: MSDN
  4. Safari Only: Just run Selenium Core directly off of your hard disk as a "file://" URL. HTML files run off the file system aren't restricted by the same-origin policy in Safari 3.x on Mac/Windows.

Why do I get a "Permission Denied" error when accessing my website via HTTPS?

This is actually the same problem as scripting a foreign web-site, described above. "http://mydomain.com" is not the "same origin" as "https://mydomain.com"; using Selenium Core, you can test HTTP or HTTPS, but not both. If you need to test both during a single test, you need to use one of the strategies listed above to test a foreign website.

I can't seem to use Selenium Core to upload a file; when I try to type in the file upload text field, nothing happens!

Unfortunately, this is yet another JavaScript security restriction; JS is not allowed to modify the value of <input type="file"> form fields. You can work around this by running your tests under Selenium IDE or under Selenium RC running in the experimental "*chrome" mode for Firefox, but at present there is no way to do this on any other browser. This is filed as bug SEL-63, but there may be no way to fix it in Selenium Core.

How do I use Selenium to login to sites that require HTTP basic authentication (where the browser makes a modal dialog asking for credentials)?

Use a username and password in the URL, as described in RFC 1738:
Test Type


open

Note that on Internet Explorer this won't work, since Microsoft has disabled usernames/passwords in URLs in IE. However, you can add that functionality back in by modifying your registry, as described in the linked KB article. Set an "iexplore.exe" DWORD to 0 in HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE.
If you don't want to modify the registry yourself, you can always just use Selenium Remote Control, which automatically sets that that registry key for you as of version 0.9.2.

I don't have access to the server where my AUT (application under test) is deployed, does that matter? IE., is physical deployment of app server and testrunner an issue?

Physical deployment doesn't strictly matter, but if you can't modify your AUT, you do have to somehow either force the browser to disable the same-origin policy or trick the browser into thinking that your tests and your AUT have the same origin.

Selenium isn't working, where are the diagnostics for problem solving?

Look for JavaScript errors. (In IE, check for a warning in your browser status bar; in other browsers you'll want to check the JavaScript console for errors.) Additionally, try opening the logging window before you run your tests; that may reveal problems. You may also want to try using a JavaScript debugger. In Internet Explorer you can configure the MS Script Debugger; in Mozilla you can configure Firebug.

Selenium scripts are rather verbose - Is it possible to record these scripts to speed things up?

Yes, use Selenium IDE This is a firefox plugin, so it requires firefox, but the results can be replayed using any browser you choose once the script has been created.

Is it possible to run a Selenium test without using a real browser?

No. Selenium is written in JavaScript; it's designed to run in a real browser to test compatibility with a real browser. There are a variety of other tools out there designed to run tests that simulate a browser; we recommend HtmlUnit or Canoo WebTest.

Is it possible to use Selenium for multi-user load testing?

Yes, but it requires a LOT of hardware. We recommend you check out BrowserMob, which does load testing with real browsers and is powered by Selenium.

How can I use a javascript{...} expression as a locator in a Selenium command?

The core documentation states that "All Selenium command parameters can be constructed using both simple variable substitution as well as full javascript". Since locators are important command parameters you might wonder how you can use Javascript to specify a locator e.g. in a 'click' command.
The answer is: Used as a locator, the 'javascript{..}' idiom has to evaluate to a string that represents a valid Selenium locator, e.g. an identifier, css or xpath locator. So if you have a working locator like id=myButton then javascript{["id=","my","Button"].join('')} should work too.
Gotchas:
  • If your Javascript block contains multiple statements, the value of the last statement determines the value of the block.
  • You can use the 'getEval' command, to debug your Javascript expressions.

How to do it with Selenium

How do I work with a popup window?

In Selenium, you work with one window at a time. To work with a different window, for example one that has popped up as a result of clicking a link, you need to first select that window. In order to select it, you must somehow identify it. Various identification methods can be used (see documentation on the selectWindow command at http://selenium-core.openqa.org/reference.html); the easiest may be for you to capture the id by recording the popup creation with the Selenium IDE. Something like the following will be recorded:
selectWindow | winId
You probably want to wait for the popup to load before you start interacting with it. Also, when you're done with it, you'll probably want to close it, and reselect the original window. A simple idiom to follow would then be:
waitForPopUp | winId | 30000
selectWindow | winId
...
close
selectWindow

How do I download a file?

Currently it is only possible to do this by configuring Firefox with a profile template, telling it to save a file to a specified location without prompting the user with a file chooser dialog. See here: http://clearspace.openqa.org/message/31350 . There do not appear to be workarounds for other browsers yet.

7 comments:

  1. It turns out that even the hottest port has a few places where you can get off the beaten path. Here are some recommendations that will make you feel like you're in the know
    سایت پوکر خارجی

    ReplyDelete
  2. Great post full of useful tips! My site is fairly new and I am also having a hard time getting my readers to leave comments. Analytics shows they are coming to the site but I have a feeling “nobody wants to be first”.
    รีวิวufa800

    ReplyDelete
  3. Consequently, starting in the amount of electronic marketing strategy, is whenever a company's existing website, which will be to review the present site and its purpose is to improve the potency of the future. There is no evidence that the development and implementation of a method to be significantly different way of electronic marketing. Strategic planning for enterprise development or strategic marketing to comply with the established framework should still beรีวิวufa800

    ReplyDelete
  4. Daisy Limousine provides the best black car service in the tri-state area. We can provide limo service or airport service in New Jersey, New York, Rhode Island, Massachusetts, Pennsylvania, and Connecticut. Our on-time ground transportation service will drive you pretty much from A to B anywhere in the North East of America. Give us a call or book a ride online at your convenience
    แทงบอล

    ReplyDelete
  5. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work.
    สูตรแทงบอลรอง

    ReplyDelete
  6. I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job! แทงบอลลาลีกา

    ReplyDelete
  7. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include
    แทงบอลไม่มีขั้นต่ำ

    ReplyDelete