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

Tuesday, 30 August 2011

Handling Browser Security


Handling Browser Security –
1)  Handle FireFox Security
Method-1:
·         Run the selenium test
·         Select "Accept this certificate permanently" when prompted by popup
·         Click on the OK button
·         Open Windows Explorer and navigate to => "C:\Users\xxxxxxxx\AppData\Local\Temp\customProfileDirxxxx"
·         This is a temparary profile created by Firefox which contains a file called "cert_override.txt"
·         Copy "cert_override.txt" to your temp directory
·         Stop your selenium server.
·         Open your "selenium-server.jar" file from "c:\selenium-remote-control-xxx\selenium-server-xxx" using WinRar
·         Drag "cert_override.txt" file into the "selenium-server.jar\customProfileDirCUSTFFCHROME" folder in WinRar (do not delete or edit anything in the .jar file)
·         Close WinRar, start selenium and try it again :)
Method-2:
·         Navigate your application in firefox.
·         Select "Accept this certificate permanently" when prompted by popup.
·         Copy "cert_override.txt" and "cert8.db" to your temp directory.
·         Create a new directory in any drive. Ex – C:\FFProfile. Paste the above two files under this.
·         Now run the selenium server with below option – java -jar selenium-server-standalone-2.3.0.jar –firefoxprofile C:\FFProfile
·         Now it will not show the certificate screen.

2)  Handle IE7 Security
-- Use the below code in your script
if (brw.is_text_present("Continue to this website (not recommended).")):
        brw.click("link=Continue to this website (not recommended).")
        time.sleep(10)

HTML Report using HTMLTestRunner


Example –
from selenium import selenium
import HTMLTestRunner
import unittest, time

class main_script(unittest.TestCase):
    selenium = selenium("localhost", 4444, "*firefox","http://google.co.in")
    selenium.start()
    selenium.open("/")
    def test01_script(self):
        browser=self.selenium
        print "Open the google page"
        browser.type("q", "selenium RC")
        print "Enter the search test Selenium RC"
        browser.click("btnG")
        print "Click on Google Search button"
        browser.stop()
if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(main_script))
    dateTimeStamp = time.strftime('%Y%m%d_%H_%M_%S')
    buf = file("TestReport" + "_" + dateTimeStamp + ".html", 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(
            stream=buf,
            title='Test the Report',
            description='Result of tests'
            )
    runner.run(suite)


Report – 

Selenium API using Python


Selenium API using Python

The Selenium API defines dozens of commands that can be categorized into the following:
  • Actions
    • Actions are commands that change the state of the application like clicking links or buttons, select an option in a <select> or type a character sequence in a given textbox. Ex - click(locator)
  • Accessors
    • Accessors inspect the state of the application and store values in variables
  • Assertions
    • Assertions are also able to inspect the current page. It comes into 3 flavors
    • assert : if assertion fails, test is aborted and marked as failed.
    • verify : if a verification fails, the test doesn’t stop but a trace will be printed in the log.
    • waitFor : these commands pause the test until a condition is satisfied or a timeout is reached
Selenium uses what is called locators to find and match the elements of your page that it needs to interact with. There are 8 locators strategies included in Selenium:
  • Identifier
  • Id
  • Name
  • Link
  • DOM
  • XPath
  • CSS
  • UI-element
1)  Browser Initialization

from selenium import selenium
selenium=selenium("localhost",4444,"*firefox","<URL>")
                   or
selenium=selenium("localhost",4444,”*iexplore","<URL>")

host - Specifies the IP address of the computer where the server is located.
Port - Specifies the TCP/IP socket where the server is listening waiting for the client to establish a connection.
Browser - The browser in which you want to run the tests. This is a required parameter.
url - The base url of the application under test.

2)  Navigating Application URL

selenium.start()
selenium.open("/")

3)  Wait
selenium.wait_for_page_to_load('30000')
selenium.set_timeout('30000')
time.sleep(5)

4)  Buttons
-- Use click method.

HTML –
<input type="submit" name="" value="Log In" class="submitbutton" id="loginbtn" />

Example –
selenium.click("id= loginbtn ")
selenium.click("//input[@id=' loginbtn ']")
selenium.click("css=# loginbtn")

5)  Textboxes
-- Use type method.

HTML –
<input type="text" name="username" id="username" class="textfield" value="">

Example –
selenium.type("id=username","test123")
selenium.type("name=username","test123")
selenium.type("//input[@id='username']","test123")
selenium.type("css=#username","test123")

6)  Link
-- Use click method

HTML –
<li id="nav-login"><a href="https://www.example.com/login.do" title="My account">My Login</a></li>

Example –
selenium.click ("link=My Login")
selenium.click ("//a[contains(text(),'My Login')]")
selenium.click ("//li[@id='nav-login']/a")

7)  Selection
-- Use select method

HTML –
<select name="country">
<option value="01">India</option>
<option value="02">Malaysia</option>

Example –
selenium.select("name=country", "India")
selenium.select("//select[@name='country']", "India")
selenium.select("css=select[name=country]", "India")

8)  Checkbox
-- Use click method

HTML –
<em class="checker"><input type="checkbox" name="rememberMe" value="1" checked="checked" >Remember me</em>

Example –
selenium.click("name=rememberMe")
selenium.click("//input[@name='rememberMe']")

9)  Image
-- Use click method

HTML –
<li id="nav-sign"><a href="/logout.do" title="Sign out"><img src="https://www.example.com/logoutbutton.xxx?image=logout&amp;time=1324324324" alt="Sign Out" /></a></li>

Example –
selenium.click("//img[@alt='Sign Out']")
selenium.click("css=img[alt='Sign Out']")

10)         Verify text on page
-- Use is_text_present method

Example –
selenium.is_text_present("Secret Question")

11)         New Window
-- Use select_window(self, windowID) method
-- Selects a popup window using a window locator; once a popup window has been selected, all commands go to that window. To select the main window again, use null as the target.

Example (When you know the window name)–

selenium.click("send")
     selenium.wait_for_pop_up("_blank", "30000")
     selenium.select_window("send email page")
     selenium.type("toAddress1", "abs@gmail.com")
     selenium.type("shortNote", "test")
     selenium.click("link=Send Email")
     selenium.wait_for_page_to_load("30000")
selenium.select_window("null")

Example (When you don’t know the window name)–

win_title=[]
selenium.click("print")
selenium.wait_for_pop_up("_blank", "30000")
win_title=selenium.get_all_window_titles()
selenium.select_window(win_title[1])
selenium.close() #Close the popup window
time.sleep(2)
selenium.select_window("null") #select the main window
time.sleep(5)

12)         Set focus on element
-- Use focus() method
-- Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field

Example –
focus("//input[@id='username']")

13)         Stop the selenium execution
-- Use stop() method

Example –
selenium.stop()

14)         Few more commonly used APIs –
·         get_location(self) - Gets the absolute URL of the current page.
·         get_title(self) - Gets the title of the current page.
·         get_body_text(self) - Gets the entire text of the page.
·         get_value(self, locator) - Gets the value of an input field (or anything else with a value parameter).
·         get_text(self, locator) - Gets the text of an element.

Tuesday, 16 August 2011

Selenium With Python - Introduction

The below details describe about the use of Selenium RC using the Python scripting language. I have mentioned all the required details like how to use Selenium Server, Selenium IDE and Python client libraries.


What is Selenium?
Selenium is a software testing framework for web applications. Selenium was developed by a team of programmers and testers at Thought Works. The tests can be written as HTML tables or coded in a number of popular programming languages and can be run directly in most modern web browsers.

Selenium Components –
–        Selenium IDE
–        Selenium Core
–        Selenium Remote Control (RC)
–        Selenium Grid

Please see below brief about Selenium IDE and in details about Selenium RC.

Selenium IDE
1. Selenium IDE features:
  • record/play mechanism: create/edit tests by recording the user actions on the page
  • Debugging feature with step-by-step and breakpoints
  • Page abstraction capabilities
  • Automatic assertions for the page title
  • An extensibility feature allowing the use of plug-in or user extensions that extend the capabilities of Selenium IDE

2. Installation

Selenium IDE is distributed as Firefox extension:
  1. Go to the Selenium website (http://www.seleniumhq.org) or the Firefox add-ons website (http://addons.mozilla.org)
  2. Download the latest release (1.0.8 at the time of writing)
  3. Follow the instructions and restart Firefox
  4. Selenium IDE is accessible from the ‘Tools’ Menu of Firefox
 

Selenium RC

Selenium-RC allows the test automation developer to use a programming language for maximum flexibility and extensibility in developing test logic. For instance, if the application under test returns a result set, and if the automated test program needs to run tests on each element in the result set, the programming language’s iteration support can be used to iterate through the result set, calling Selenium commands to run tests on each item.

Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby. This ability to use Selenium-RC with a high-level programming language to develop test cases also allows the automated testing to be integrated with a project’s automated build environment.
Selenium RC comes in two parts.
  1. A server which automatically launches and kills browsers, and acts as a HTTP proxy for web requests from them.
  2. Client libraries for your favorite computer language.

1. Selenium Server

  • Selenium server is the program that drives the browser
  • It embeds Selenium Core framework and injects it into the browser
  • It communicates with the running test client and drives the browser
  • Client tests sends commands that the server interpretes in order to drive the browser
  • The server sends back results to the client
  • Client and server communicates via HTTP GETs and POSTs so you can easily plug into
  • Server is configurable at startup via command-line options. use java -jar selenium-server.jar -h to see the list of options

2. Client libraries

  • Client libraries provides the API to program tests and execute them on the server
  • Each implementation provides access to all Selenium commands
·         Supported API implementation exists in:
    • Java
    • .Net
    • PHP
    • Python
    • Perl
    • Ruby
Pre-Requisites –

Selenium Server –
Java Runtime Environment (JRE) 1.6 is recommended to run Selenium server.

Python Client Libraries
Python should be installed (Python 3.x is not yet supported)
Python Window (PyWin32)
Setup Tool
Python-Selenium libraries