Saturday, May 2, 2015

Write UnitTests in Selenium using Python


Selenium does not provide any Test Framework/Tool. We can use Python's unittest module to write the tests. Let's see how automate the following test steps:

1. Open www.gmail.com
2. Asset if the page contains the Text "Sign in to continue to Gmail"

here is the HTML code, how it looks like:

<div class="banner">
<h1>One account. All of Google. </h1>
<h2 class="hidden-small"> Sign in to continue to Gmail </h2>
</div>

Code:

#!/bin/python
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class GmailSignUpTest(unittest.TestCase):
    "Tests for Gmail SignUp page"
  def setUp(self):
    self.driver = webdriver.Firefox()
  def tearDown(self):
    self.driver.close()
  def test_open_gmail_application(self):
    driver = self.driver
    driver.get("https://www.gmail.com")
    banner = driver.find_element_by_css_selector(".banner h2")
    self.assertEqual('Sign in to continue to Gmail', banner.text)

  if __name__ == "__main__":
    unittest.main()

Walk through the example:

Find the Element:
First let us see how to find the element in the page. If you look at the HTML, the required text is in the <h2> tag, which is a descendant of <div> with class name "banner". Selenium provides various ways to find the element. We can find the element by tag "h2" or find the element by class "hidden-small". But, I am using the CSS selector ".banner h2" this equivalent to <div class="banner"><h2> </h2></div>.

The DOT preceding the class name "banner" indicates that it is a class name. class name followed by h2 means, h2 is child of the element with class name "banner"
banner = driver.find_element_by_css_selector(".banner h2")
Get the Element Text:
There are various ways to get the element text in selenium. One of which is using "element.text" which returns the inner text of an element.
banner.text

UnitTests:
The fist line "import unittest" loads the Python's Unit Test module. To start with unittests, create class that inherits unittest "Test Class". Test cases start with "test_". When unittest reads the line 'test_' it understood as a unit test case.
setUp:
setUp() is a special method which will be called before executing the test case. This is similar to "before" statement in JAVA

tearDown:
tearDown() is a special method which will be called after executing the test case, this is similar to "after" statement. Most of the time we place code to close the browser and database cleanup

Running the Unit Tests:
Finally, "unittest.main()" is the method used to execute the Unit Test.

To understand "__name__" and "__main__" let us see the what happens when we execute these programs
#module1.py
print "Module 1: __name__ = %s", __name

The output of the above program is 
Module 1: __name__ = __main__

Now, will write another program 'module2' and import 'module1'
#module2.py
import module1

The output of the above program is
Module 1: __name__ = module1

Python assigns module name to '__name__' when it is imported by some other program. And when the program is executed as a main it assigns '__main__' to '__name__'

The statement if __name__ == "__main__" is just to make ensure that the test are executed only when it is executed as a program, not when it is imported by other programmes.

Thursday, April 30, 2015

Input text using 'Send_Keys' in Selenium

Selenium supports various methods to enter text in 'Input' Text field. One of which is using 'send_keys'.

'send_keys' simulates keyboard inputs, you can enter text as you are typing in keyboard. You can also input special keys like RETURN, F1, F2, ALT etc.. Special keys can be send using Keys class imported from selenium.webdriver.common.keys:

Let us write small test code to Automate the following steps
  1. Open 'Google' web page
  2. Asset if Page got loaded by looking at the title
  3. Input some text in the Search Bar using 'send_keys'
  4. Input 'RETURN' key to search
  5. Assert if the Search results are loaded by looking at the Page title

Code:
#!/bin/python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
 
#create instance for Firefox driver
driver = webdriver.Firefox()

#Open Google.com website
driver.get("http://www.google.com")

#assertion
assert "Google" in driver.title

#Enter text in the input field
search_input = driver.find_element_by_id("lst-ib")
search_input.send_keys("Selenium")
search_input.send_keys(Keys.RETURN)

#assertion
assert "Selenium" in driver.title

#close the browser
driver.quit()

Explanation:
I hope most of the code is self explanatory except find_by_element_id which is used to locate the
 element by unique ID.

Let us see how to use Browser developer tools to inspect an Element. If you press F12 in Chrome/Firefox, it will open 'Developer Tools', which has many features. But, let us limit our self to find an element properties.

From the 'Developer Tool' which usually opens in the bottom of the page, click on 'Inspect Element' button and place it on the element (in our case Input field) to get the properties. Look at the following screenshot.


Here is the HTML code for the element
<input id="lst-ib" class="gsfi" type="text ...></input>
 
Webdriver provides various ways to find an element, "find_element_by_id" is one of them, which is used to find an element by using it's ID. In the above example the element id is "lst-ib". So, we have used driver.find_element_by_id("lst-ib") to get the element . 

After locating an element, we can perform various operations on it like Input some text, Click() etc..

How to Install Python and Selenium in Windows?

Follow these instructions to setup Python and Selenium test environment on Windows:

Step 1: Install Python 3.4 using the MSI available in python.org download page.

Step 2: Start a command prompt using the cmd.exe program and run the pip command as given below to install selenium.
   C:\Python34\Scripts\pip.exe install selenium

Step 3: Now you can run your test scripts using Python. For example, if you have created a Selenium based script and saved it inside C:\my_selenium_script.py, you can run it like this:

   C:\Python34\python.exe C:\my_selenium_script.py

Wednesday, April 29, 2015

selenium.common.exceptions.WebDriverException: Message: f.QueryInterface is not a function


browser.get('google.com')

&

browser.get('www.google.com')

while trying to execute the above statement, I see the following error


browser.get('google.com')
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 187, in get
    self.execute(Command.GET, {'url': url})
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 175, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: f.QueryInterface is not a function


If you look at the line self.execute(Command.GET, {'url': url}) the statement says GET method accepts the URL 


So, selenium throws error if the URL is not in the proper format. URL should contain http/https and www (Ex: "http://www.google.com")

The following code works:

 browser.get("http://www.google.com")

What is Selenium?

Selenium does browser automation. Basically, Selenium tells a browser to click some element, populate and submit a form, navigate to a page or do any other form of user interaction.

Key features include:
  • Support multiple browsers like Firefox, Chrome, Safari, Opera and yes, even Internet Explorer.
  • Support multiple OS: Windows, OS X, Linux, Android and iOS
  • Support multiple language like Python, Ruby, Java, etc.
  • It's Free
  • For more features see seleniumhq.org

Sample python program using selenium web driver

In my previous post, we have seen how to install Python and Selenium. Now, let us write a sample program using Selenium web driver

I just want to automate the following manual test steps:
  1. Open FireFox web browser
  2. Load 'google.com' website
  3. Asset if Google page is loaded
  4. Close the browser
Code:

#!/bin/python
# Import Selenium webdriver module
from selenium import webdriver


#Initiate FireFox webdriver
browser = webdriver.Firefox()
 
#Load the webpage in FireFox browser
browser.get('https://www.google.com')
 
#debug statement
print "Page Title is: %s" %browser.title
 
#Assert by Page title
assert 'Google' in browser.title
 
#Close the browser
browser.quit()



 

Code Explanation: 
"from selenium import webdriver" statement imports webdriver form Selenium module. 

'webdriver.Firefox()' load FireFox driver. 

'browser.get()' loads the specified url in the browser. Note that 'browser' is the object name that we have given.

'assert <A> in <B>" is python statement which checks if the A is listed in B. Here we check if page title contains the text 'Google'. 


Comparison is case sensitive.  e.g: Assume that the Page title is "Google Search Engine". when we call the assert statement, python check if page title contains the text 'Google'. 

The following statement will fail as the comparison is case sensitive
assert 'google' in browser.title


How to Install Python and Selenium in Linux (Ubuntu)?


To install Selenium means to set up a project in a development so you can write a program using Selenium.

Supported Python Versions:
  • Python 2.6, 2.7
  • Python 3.2, 3.3
Step 1: Install pip, if not already installed:

pip is a package management system used to install and manage software packages written in Python. You can install it by typing:
sudo apt-get install python-pip
Step 2: Install or upgrade the Python bindings:

pip install -U selenium

Alternately, you can download the source distribution from PyPI (e.g. selenium-2.45.tar.gz), unarchive it, and run:

python setup.py install