Rescue for ScriptError in Selenium Webdriver? - ruby

I have a written a Code in Selenium Web driver to test the health of the Contact Us page of my web site.
Code is working fine. My further aim is to:
Use Rescue (to get error message when this scripts fail. Specifically when some element is not found during execution in the function > "def test_contact_us_screen_shot").
Code for reference.
require 'rubygems'
require "selenium-webdriver"
require "test/unit"
class ContactUsScreenShot < Test::Unit::TestCase
def setup
#driver = Selenium::WebDriver.for :firefox
#base_url = "http://www.mycompany.com"
#driver.manage.timeouts.implicit_wait = 30
#verification_errors = []
end
def teardown
#driver.quit
assert_equal [], #verification_errors
end
def test_contact_us_screen_shot
#driver.get(#base_url + "/contact_us")
#This method will take screenshot and save it in the same folder from where script is executed.
#driver.save_screenshot("./screen1.png")
puts "screen shot taken"
assert_equal "mycompany.com - Discuss your requirements to Outsource Software Product Development, Offshore Software Testing,", #driver.title
#driver.find_element(:id, "compan").clear
#driver.find_element(:id, "company").send_keys "My Company"
#driver.find_element(:id, "first_name").clear
#driver.find_element(:id, "first_name").send_keys "Mrityunjay"
#driver.find_element(:id, "last_name").clear
#driver.find_element(:id, "last_name").send_keys "Chauhan"
#driver.find_element(:id, "email").clear
#driver.find_element(:id, "email").send_keys "mrityunjay#gmail.com"
#driver.find_element(:id, "phone1").clear
#driver.find_element(:id, "phone1").send_keys "9999999999"
#driver.find_element(:id, "addr1").clear
#driver.find_element(:id, "addr1").send_keys "306 Office Address"
#driver.find_element(:id, "addr2").clear
#driver.find_element(:id, "addr2").send_keys "Office Address"
#driver.find_element(:id, "city").clear
#driver.find_element(:id, "city").send_keys "Dehradun"
#driver.find_element(:id, "state").clear
#driver.find_element(:id, "state").send_keys "UK"
Selenium::WebDriver::Support::Select.new(#driver.find_element(:id, "country")).select_by(:text, "India")
#driver.find_element(:id, "zip").clear
#driver.find_element(:id, "zip").send_keys "248001"
#driver.find_element(:id, "website").clear
#driver.find_element(:id, "website").send_keys "http://www.mycompany.com"
#driver.find_element(:id, "comments").clear
#driver.find_element(:id, "comments").send_keys "This is the Testing Script for Contact Us page. Please Ignore.\nThanks,\nMrityunjay Chauhan"
#driver.find_element(:name, "submit").click
assert_equal "mycompany.com - Discuss your requirements to Outsource Software Product Development, Offshore Software Testing,", #driver.title
begin
rescue Exception => e
puts e.message
#driver.save_screenshot("./error1.png")
end
puts "I am Here"
end
def element_present?(how, what)
#driver.find_element(how, what)
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
def verify(&blk)
yield
rescue Test::Unit::AssertionFailedError => ex
#verification_errors << ex
end
end

Here is an answer -- just use "find_elements" instead which gives an empty array instead of throwing an exception.

Do you mean something like this
begin
#driver.find_element(:name, "submit")
rescue
#driver.save_screenshot("Submit_button_not_present.png")
assert_match "true","false","Your error message"
end

Following Rescue code is working fine in my code...
rescue Exception => e
puts e.message
puts "Element Not Found"
#driver.save_screenshot("./Test-Results/Contact_Us_Error.png")
puts "I am Here"
end #rescue
In rescue we can trace the errors by using Log. For this we have to generated log file. Code is given below:
First define log at the start of your code as:
# Here I have created a log file in my "Test-Result" folder
$log = Logger.new('./Test-Results/logfile.log')
Next, we will move the error message to our log file using code given below:
rescue Exception => e
$log.error "This is the Error occurred when Element/s not found: #{e}"
#driver.save_screenshot("./Test-Results/Contact_Us_Error.png")
puts "I am Here"
end #rescue
Log will be something like this:
E, [2012-06-04T16:03:44.546875 #796] ERROR -- : Error in Elements when not found!: Unable to locate element: {"method":"id","selector":"compan"}

Related

Fail to use statement IF in Selenium

Currently I'm trying use a statement IF (If a button appears in the page, then run the IF), see the method Login in the system:
If the button doesn't appear in the page, I would like to run the next method Remove and add new expense
require "selenium-webdriver"
require "rspec"
require "rspec/expectations"
describe "#Add simple expense and after add a receipt", :suitee => true do
before(:all) do
#driver = Selenium::WebDriver.for :chrome
#base_url = "http://sitetest.com"
#driver.manage.window.maximize
end
it "Login in the system" do
#driver.get(#base_url)
#driver.find_element(:id, "user_email").send_keys "rafael#gmail.com"
#driver.find_element(:id, "user_password").send_keys "123456"
#driver.find_element(:name, "commit").click
if(#driver.find_element(:css, ".btn.btn-lg.btn-success.btn-block").displayed?)
#driver.find_element(:css, ".btn.btn-lg.btn-success.btn-block").click
#driver.find_element(:css, ".introjs-button.introjs-skipbutton").click
#driver.find_element(:css, ".i.i-pencil").click
end
end
it "Remove and add new expense" do
begin
while(#driver.find_element(:css, ".i.i-pencil.icon").displayed?)
button = #driver.find_element(:id, "expense-bulk-select")
#driver.action.click(button).perform
delete = #driver.find_element(:id, "delete-multi-btn")
#driver.action.click(delete).perform
waitDisplayModal = Selenium::WebDriver::Wait.new(:timeout => 10)
waitDisplayModal.until {#driver.find_element(:class => "bootstrap-dialog-footer-buttons")}
#driver.find_element(:xpath, "//div[3]/div/div/button[2]").click
sleep 3
end
rescue Selenium::WebDriver::Error::NoSuchElementError
#driver.find_element(:id, "current_expense_merchant").send_keys "Taxi to work"
#driver.find_element(:id, "current_expense_amount").send_keys "50"
#driver.find_element(:id, "button-add-expense").click
waitDisplayIconTrash = Selenium::WebDriver::Wait.new(:timeout => 20)
waitDisplayIconTrash.until {#driver.find_element(:css => ".i.i-pencil.icon")}
end
end
after(:all) do
#driver.quit
end
end
My problem: When I run this script, appears this in my console:
Failure/Error: if(#driver.find_element(:css, ".btn.btn-lg.btn-success.btn-block").displayed?)
Selenium::WebDriver::Error::NoSuchElementError:
no such element
(Session info: chrome=42.0.2311.135)
(Driver info: chromedriver=2.9.248304,platform=Linux 3.13.0-24-generic x86_64)
That is, the IF is not working as I would like. How can I fix it?
CHeers
https://code.google.com/p/selenium/wiki/RubyBindings
Use the Wait class to explicitly wait for some condition:
wait = Selenium::WebDriver::Wait.new(:timeout => 3)
wait.until { driver.find_element(:css, ".btn.btn-lg.btn-success.btn-block").displayed? }
....

Implemeting amazon Simple nodification service in RUBY

Am trying to implement amazon SNS using ruby.
I want to create a topic,delete a topic,subscribe to a topic,publish to a topic.These are included in the following code.
#!/usr/bin/env ruby
require 'rubygems'
require 'aws-sdk'
AWS.config(:access_key_id => 'BT62W53Q', :secret_access_key => '0Edwg')
#sns=AWS::SNS.new
#D requirements
alpha = #sns.topics.create('CSC470Test-Alpha')
#sns.topics.create('CSC470Test-Beta')
temp=gets
#sns.topics.each do |topic|
puts topic.name
if(topic.name=='CSC470Test-Beta')
topic.delete
end
end
puts
puts 'Beta now deleted.'
puts
#sns.topics.each do |topic|
puts topic.name
end
puts
temp=gets
puts
#C requirements
#sns.topics.each do |topic|
if(topic.name=='CSC470Test-Alpha')
subbed1=false
subbed2=false
subbed3=false
topic.subscriptions.each do |sub|
if(sub.endpoint=='sn#aine.com')
subbed1=true;
end
if(sub.endpoint=='pran#aine.com')
subbed2=true;
end
if(sub.endpoint=='http://cloud.comtor.org/csc470logger/logger')
subbed3=true;
end
end
if(!subbed1)
puts 'Subscribed sika.'
topic.subscribe('sn#aine.com')
end
if(!subbed2)
puts 'Subscribed prka'
topic.subscribe('pran#aine.com', :json => true)
end
if(!subbed3)
puts 'Subscribed comtor site.'
topic.subscribe('http://cloud.comtor.org/csc470logger/logger')
end
end
end
temp=gets
puts 'Topics with info:'
#sns.topics.each do |topic|
puts
puts 'Arn'
puts topic.arn
puts 'Owner'
puts topic.owner
puts 'Policy'
puts topic.policy
puts 'Name'
puts topic.display_name
puts 'Confirmed Subscriptions:'
puts topic.subscriptions.
select{ |s| s.arn != 'PendingConfirmation' }.
map(&:endpoint)
# if(subs.confirmation_authenticated?)
# puts 'Arn: ' + subs.arn
# puts 'Endpoint: ' + subs.endpoint
# puts 'Protocol: ' + subs.protocol
# end
end
puts
temp=gets
#sns.subscriptions.each do |subs|
puts "SubscriptionARN: #{ subs.arn} "
puts "TopicARN: #{subs.topic_arn} "
puts "Owner: #{subs.owner_id} "
puts "Delivery Policy: #{ subs.delivery_policy_json} "
end
while running this code in rails console. iam getting this error
C:/ProgramData/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/aws-sdk-1.8.5/l
ib/aws/core/client.rb:339:in `return_or_raise': The request signature we calcula
ted does not match the signature you provided. Check your AWS Secret Access Key
and signing method. Consult the service documentation for details. (AWS::SNS::Er
rors::SignatureDoesNotMatch)
from C:/ProgramData/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/aw
s-sdk-1.8.5/lib/aws/core/client.rb:440:in `client_request'
from (eval):3:in `create_topic'
from C:/ProgramData/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/aw
s-sdk-1.8.5/lib/aws/sns/topic_collection.rb:24:in `create'

Importing/Reading parameters in Ruby Test Unit

Please please help me before I lose it!
I'm using Ruby Test Unit and Selenium Webdriver. All of my tests start with a login function, therefore I want the tests to pull the username and password values from a central script/csv/text file, whatever is easiest. This would make it easier to control login details from one place rather than hard coding them into every script. I am not a Ruby programmer and therefore I am not finding this particularly easy. I'm thinking I should be able to declare the username and password parameters in the 'def setup' section, so that it reads the values from an external source.
Is this possible?
require "selenium-webdriver"
require "test/unit"
class CMSNewslist < Test::Unit::TestCase
def setup
#driver = Selenium::WebDriver.for :firefox
#base_url = "http://skyintranet/"
#driver.manage.timeouts.implicit_wait = 90
#verification_errors = []
end
def teardown
#driver.quit
assert_equal [], #verification_errors
end
def test_c_m_s_newslist
#driver.get(#base_url + "/Enterprise-Applications-Test/")
#driver.find_element(:link, "Login").click
#driver.find_element(:id, "ctl00_MainRegion_LoginView_LoginControl_UserName").clear
#driver.find_element(:id, "ctl00_MainRegion_LoginView_LoginControl_UserName").send_keys "Ruband"
#driver.find_element(:id, "ctl00_MainRegion_LoginView_LoginControl_Password").clear
#driver.find_element(:id, "ctl00_MainRegion_LoginView_LoginControl_Password").send_keys "Donn1982"
#driver.find_element(:id, "ctl00_MainRegion_LoginView_LoginControl_LoginBtn").click
assert_equal "Logout", #driver.find_element(:class, "loginButton").text, "Login Unsuccessful"
puts "Login Successful"
Many Thanks.
You can put them in a separate file and read it or have a mixin that gets included in each script.
module LoginConfig
##username = 'foo'
##password = 'bar'
end
Then within your class CMSNewslist:
...
require 'login_config'
class CMSNewslist < Test::Unit::TestCase
include LoginConfig
...
Then you can use ##username and ##password. Here's a decent tutorial on Mixins...
http://www.tutorialspoint.com/ruby/ruby_modules.htm

Selenium WebDriver for ruby fails with "too many redirects"

I've got this simple test case that tests a login form.
For some reason webdriver refuses to run the test and comes back with a "too many redirects" message. The page is just an ordinary login screen, very simple and there are no redirects whatsoever. Access from the server to the page seems ok.
I'm using selenium-webdriver-2.25.0 on a centos server.
Below the error message:
(...)
[WARNING] MultiJson is using the default adapter (ok_json). We recommend loading a different JSON library to improve performance.
EE
Finished in 0.206445 seconds.
1) Error: test_login(Login):
Selenium::WebDriver::Error::WebDriverError: too many redirects
/usr/lib/ruby/gems/1.8/gems/selenium-webdriver-2.25.0/lib/selenium/webdriver/remote/http/default.rb:62:in `request'
/usr/lib/ruby/gems/1.8/gems/selenium-webdriver-2.25.0/lib/selenium/webdriver/remote/http/default.rb:63:in `request'
/usr/lib/ruby/gems/1.8/gems/selenium-webdriver-2.25.0/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
(...)
My code:
require "rubygems"
require "selenium-webdriver"
require "test/unit"
class Login < Test::Unit::TestCase
def setup
#driver =Selenium::WebDriver.for(:remote, :url => "http://selenium.server.com/wd/hub")
#base_url = "http://www.myservice.com"
#driver.manage.timeouts.implicit_wait = 30
#verification_errors = []
end
def teardown
#driver.quit
assert_equal [], #verification_errors
end
def test_login
#driver.get(#base_url + "/login/")
#driver.find_element(:id, "username").clear
#driver.find_element(:id, "username").send_keys "user#server"
#driver.find_element(:id, "password").clear
#driver.find_element(:id, "password").send_keys "mykeys!"
#driver.find_element(:xpath, "//input[#value='Login']").click
verify { assert element_present?(:link, "Logout") }
verify { assert element_present?(:link, "Settings") }
verify { assert element_present?(:link, "Products") }
end
def element_present?(how, what)
#driver.find_element(how, what)
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
def verify(&blk)
yield
rescue Test::Unit::AssertionFailedError => ex
#verificatiohttp://jenkins.dev.emesa-auctions.com/cms/n_errors << ex
end
end
UPDATE
It seems that no matter what url I use for the 'base url' the errors keeps occuring.
I managed to solve this problem myself. The issue was that I was accessing the server through its public facing url (selenium.server.com) instead of through the internal lan url (which bypass the firewall).
Changing that fixed the problem.

ruby shoes ssh connection

I am trying my hands on shoes but got stuck. I am trying to connect to a remote computer using ssh and issue a command, got it working in cli but it is a no go for me to get it working on shoes.
This might be a simple thing but new as I am I can't get past it.
Here is what my code looks like atm
Shoes.setup do
gem 'net-ssh'
end
require "rubygems"
require "net/ssh"
Shoes.app do
button "Connect" do
append Net::SSH.start( '192.168.100.127', 'fox', :password => "xxxxxx" ) do
|ssh_connection|
ssh_connection.open_channel do |channel|
channel.on_data do |ch, data|
puts data
channel.exec "ls -la" do |ch, success|
para success
if success then
alert "uploaded"
else
alert "Fail"
end
end
end
end
end
end
end
Your code is trying to receive data first which is not the case usually. Remove the on_data:
Shoes.app do
button "Connect" do
append Net::SSH.start( '192.168.100.127', 'fox', :password => "xxxxxx" ) do |ssh_connection|
ssh_connection.open_channel do |channel|
channel.exec "ls -la" do |ch, success|
para success
if success then
alert "uploaded"
else
alert "Fail"
end
end
end
end
end
end

Resources