Monday, 4 May 2015

Cucumber _get scenario tags, feature name and scenario name during cucumber scenario execution in Ruby - Interesting..

Feature: Development feature
   To login to portal using valid credentials


   @portal   Scenario Outline: Login with valid credentials
      Given I launch portal login page
     Then I Sign in with valid credentials 
     Examples:     |brand|     |xyz|
   @portal    Scenario: Login with invalid credentials
     Given I launch portal login page
     Then sign in using invalid user_name and password
     And I should see error_message on login page
 
 
hooks.rb file:
 
Before do |scenario|
  # Feature name  case scenario    when Cucumber::Ast::Scenario      @feature_name = scenario.feature.name
    when Cucumber::Ast::OutlineTable::ExampleRow      @feature_name = scenario.scenario_outline.feature.name
  end  puts @feature_name
  # Scenario name  case scenario    when Cucumber::Ast::Scenario      @scenario_name = scenario.name
    when Cucumber::Ast::OutlineTable::ExampleRow      @scenario_name = scenario.scenario_outline.name
  end
  puts @scenario_name
  # Tags (as an array)  @scenario_tags = scenario.source_tag_names
  # puts "Printing tags: #{@scenario_tags}"end 


In Execution Results:

Development feature
To login to portal using valid credentials

Login with valid credentials

Printing tags: ["@portal"]

Thursday, 16 April 2015

Approve Rest Request without xml object:
Method: POST

def approve_order(anatwine_order_id)
   #Post Request    host = "https://something/approved"    user = 'User id'    pwd = 'Pwd'
    request_body_map = { } #if no body/xml object
    response = RestClient.post("#{host}", request_body_map ,{:authorization => "Basic #{Base64.strict_encode64("#{user}:#{pwd}")}"})
    response.code.to_s.must_equal '200'     responseend

Method: PUT

 def create_anatwine_order_id(channel, partner)
    file = File.open(xml_file)
    xml_obj= Nokogiri::XML(file)
    ##Note: Install ---------gem install rest-client -v 1.6.7 if you     get below error:     # #OpenSSL::X509::StoreError: No message available, rest-client     uri = create_order_uri(channel, partner)
    #eg= https://host/version/channel/partner/order 
    @response = RestClient.put(uri, xml_obj.to_xml,
    {:content_type => :'text/xml',
    :authorization => 'Basic pwd'     })
    @responseend


Method: GET

def get_response_code(response)
  response.code
end
 
def retrive_order(channel, retailer_order)
  # uri = "https://test/#{order_id}"  uri = build_retrive_order_uri(channel, retailer_order)
  @resource = RestClient::Resource.new(uri)
  @response = @resource.get(:Authorization => 'Basic' )
  @responseend 

Thursday, 2 April 2015

Ruby Interview Questions

http://anilpunjabi.tumblr.com/post/25948339235/ruby-and-rails-interview-questions-and-answers


Wednesday, 25 March 2015

Cucumber project structure creation in Ruby using testgen gem

Install the testgen gem:
ruby: gem install tesgen
JRuby: jruby -S gem install testgen


 
1. create normal cucumber project folder structure:

c:\>testgen project test_puppies
io/console not supported; tty will not be manipulated
      create  est_puppies
      create  est_puppies/cucumber.yml
      create  est_puppies/Gemfile
      create  est_puppies/Rakefile
      create  est_puppies/features
      create  est_puppies/features/support
      create  est_puppies/features/step_definitions
      create  est_puppies/features/support/env.rb


2. Watir Webdriver folder structure:

c:\>testgen project test_puppies1 --pageobject-driver=watir
io/console not supported; tty will not be manipulated
      create  est_puppies1
      create  est_puppies1/cucumber.yml
      create  est_puppies1/Gemfile
      create  est_puppies1/Rakefile
      create  est_puppies1/features
      create  est_puppies1/features/support
      create  est_puppies1/features/step_definitions
      create  est_puppies1/features/support/env.rb
      create  est_puppies1/features/support/hooks.rb
      create  est_puppies1/features/support/pages


2. SeleniumWebdriver folder structure:

c:\>testgen project test_puppies2 --pageobject-driver=selenium
       io/console not supported; tty will not be manipulated
      create  est_puppies2
      create  est_puppies2/cucumber.yml
      create  est_puppies2/Gemfile
      create  est_puppies2/Rakefile
      create  est_puppies2/features
      create  est_puppies2/features/support
      create  est_puppies2/features/step_definitions
      create  est_puppies2/features/support/env.rb
      create  est_puppies2/features/support/hooks.rb
      create  est_puppies2/features/support/pages


Tuesday, 24 March 2015

random numbers in ruby

random number: 5 digits:
numberofdigits = 5
puts rand(10**numberofdigits - 1).to_s
54686
==============
randon floating number:
number = (Random.new(rand(10000)).rand * 100).round / 1.0
puts number

51.0
==========
BigDecimal to integer
puts BigDecimal.new "0.961E4"
puts ("%f" % "0.961E4").to_i
puts 0.961E4.class == Float

output:
0.961E4
9610
true
=======================
Random string of length 10 characters:
range = [*'0'..'9',  *'a'..'z', *'A'..'Z']
puts Array.new(10) { range.sample }.join.upcase
output:
CBBAUTPRBX

xml builder in ruby- remove namespace etc

# updates node content 
def update_node_content(file_obj, key, index, code)
  getxml_elements_object(file_obj,
                         getxpath_forkey(key))[index].content = code.call
end# updates node content 
def update_node_native_content(file_obj, key, index, code)
  getxml_elements_object(file_obj,
                         getxpath_forkey(key))[index].native_content = code.call
end
def get_node(xmlFileObject, strNodeXPath)
  xmlFileObject.xpath(strNodeXPath)
end
def get_node_at(xmlFileObject, strNodeXPath, index=0)
  xmlFileObject.xpath(strNodeXPath)[index]
end
def add_node(xmlFileObject, strXpath, strNode, index)
  if xmlFileObject.xpath(strXpath).count >= 0    xmlFileObject.xpath(strXpath)[index].add_next_sibling(strNode)
    xmlFileObject  endend
# gets node countdef get_node_count(file_obj, key)
  getxml_elements_object(file_obj, getxpath_forkey(key)).count.to_s
end
# gets countdef get_count(xmlFileObject, xpath)
  xmlFileObject.xpath(xpath).count.to_s
end
# gets node contentdef get_node_content(file_obj, key, index)
  getxml_elements_object(file_obj, getxpath_forkey(key))[index].content
end
def remove_nodes_but_one(file_obj, xpath_key)
  count = file_obj.xpath(getxpath_forkey(xpath_key)).length
  while count > 1    file_obj.xpath(getxpath_forkey(xpath_key))[count-1].remove
    count-=1  endend

# xmlObject = setattribute_value(node,'key',"AUTI")
 def setattribute_value(node, attributename, valueto_assign)
  node.attributes[attributename].value = valueto_assign 
end


remove namespace from xml:
# xmlObject = get_xml_object("../Files/Product.xml") 
def get_xml_object(path)
  @file = File.read(path)
  xmlObj = Nokogiri::XML(@file, nil, 'utf-8')
  @get_namespaces = xml_obj.namespaces
  xmlObj.remove_namespaces!
  xmlObj 
end

in xml file:
<?xml version="1.0" encoding="utf-8"?>
 <order xmlns="http://testing.pic/party/export">

xmlns is the namespace..


Sunday, 22 March 2015

Key board operations using JRUBY and Robot class


blog: http://alvinalexander.com/java/java-robot-class-example-mouse-keystroke
http://ruby.about.com/od/Automation-and-FFI/fl/Automating-with-Robot.htm
key shortcuts: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

eg: 
http://ruby.about.com/od/Automation-and-FFI/fl/Automating-with-Robot.htm

Use JRuby if you want to implement Robot class:

require 'rubygems'
require 'Selenium-webdriver'
require 'java'
java_import 'java.awt.Robot'
java_import 'java.awt.event.InputEvent'
java_import 'java.awt.event.KeyEvent'
class WatirTest
#  browser = Watir::Browser.new :firefox
  browser = Selenium::WebDriver.for :firefox
  browser.get 'http://gmail.com'
  sleep 3
  browser.find_element(:id, 'Email').send_keys 'vicky.venu81'
#  puts browser.execute_script("return document.body").inspect

  robot = Robot.new
 
  robot.key_press(KeyEvent::VK_ENTER)
  puts robot.methods
#  robot.mouseMove(963,10);

#  browser.quit
end


Working eg: 2
require 'java'
java_import 'java.awt.Robot'
java_import 'java.awt.event.InputEvent'
java_import 'java.awt.event.KeyEvent'

class RobotTest
  def testing
    x = 'a'
    puts x.ord
    
    puts "ASCII value of 'a': #{'a'.ord}"
    puts "ASCII value of 'z': #{'z'.ord}"
   
    puts "ASCII value of 'A': #{'A'.ord}"
    puts "ASCII value of 'Z': #{'Z'.ord}"
   
    word = "abcdefg"
    word.each_byte {|b| print b.chr }
    puts '+++++++++++++++++'
    sleep 5
    word.each_byte do |chr|
      puts chr
      robot = Robot.new
      code = chr-32
      robot.key_press(code)
    end

  end
end

RobotTest.new.testing()
 

Output:
97
ASCII value of 'a': 97
ASCII value of 'z': 122
ASCII value of 'A': 65
ASCII value of 'Z': 90
abcdefg+++++++++++++++++
97
98
99
100
101
102
103

 

 

++++++++++++++++++++++++++++++++
if wanted to implement additional methods using Robot class, ref the below the example in java:


public class JavaRobotExample
{
  Robot robot = new Robot();
  public static void main(String[] args) throws AWTException
  {
    new JavaRobotExample();
  }
   
  public JavaRobotExample() throws AWTException
  {
    robot.setAutoDelay(40);
    robot.setAutoWaitForIdle(true);
     
    robot.delay(4000);
    robot.mouseMove(40, 130);
    robot.delay(500);
    leftClick();
    robot.delay(500);
    leftClick();
    robot.delay(500);
    type("Hello, world");
    robot.mouseMove(40, 160);
    robot.delay(500);
    leftClick();
    robot.delay(500);
    leftClick();
     
    robot.delay(500);
    type("This is a test of the Java Robot class");
     
    robot.delay(50);
    type(KeyEvent.VK_DOWN);
     
    robot.delay(250);
    type("Four score and seven years ago, our fathers ...");
    robot.delay(1000);
    System.exit(0);
  }
   
  private void leftClick()
  {
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(200);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(200);
  }
   
  private void type(int i)
  {
    robot.delay(40);
    robot.keyPress(i);
    robot.keyRelease(i);
  }
  private void type(String s)
  {
    byte[] bytes = s.getBytes();
    for (byte b : bytes)
    {
      int code = b;
      // keycode only handles [A-Z] (which is ASCII decimal [65-90])
      if (code > 96 && code < 123) code = code - 32;
      robot.delay(40);
      robot.keyPress(code);
      robot.keyRelease(code);
    }
  }
}

Friday, 20 March 2015

Browser stack Ruby and Selenium - Nice

http://www.browserstack.com/automate/ruby
http://www.browserstack.com/automate/ruby#

Contents: Upload file, Download File
Taking screenshots
browser capabilities
parallel execution

Saturday, 14 March 2015

Automatic Firefox authentication when using Selenium-WebDriver with AutoAuth - Basic Browser Authentication

http://watirwebdriver.com/basic-browser-authentication/
https://addons.mozilla.org/en-us/firefox/addon/autoauth/
http://watirmelon.com/2012/06/27/automatic-firefox-authentication-when-using-selenium-webdriver-with-autoauth/

Thursday, 26 February 2015

Healper classes in Ruby using singletons

class Generics  include Singleton
  # creates Singleton Object for Product Update  def self.obj    Generics.instance
  end
  def text_comparison(str1, str2, ignore_case)
    if ignore_case or ignore_case == 'yes'      str1 = str1.strip.downcase
      str2 = str2.strip.downcase
    end    begin      flag = (str1 == str2)
      raise Exception, "String #{str1.inspect} not matching with #{str2.inspect}" if not flag    end  end
end

class UserHelper
  def self.generics
    Generics.obj
  end
end

UserHelper.generics

Read/Write XML in Ruby using Nokogiri

require 'nokogiri'

$imgNode= "<METADATA order=\"22\" key=\"Key22\"><![CDATA[2 cm]]></METADATA>"class ReadXMLNodes  def initialize()
    @file = File.open('../Orders/ShoeTemplate.xml')
    @xmlObj= Nokogiri::XML(@file)
    puts @xmlObj.to_s
    puts 'Node Count: '+ @xmlObj.xpath('//PRODUCT/P_NR').count.to_s
  end
  def getNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath)
  end
  def saveXML()
    @timeStamp= Time.new
    timestmp= @timeStamp.strftime("%Y-%m-%d-%H-%M-%S-%s")
    File.delete('../Results/FileOutput'+ timestmp+ ".xml") if File.exist? ('../Results/FileOutput'+ timestmp+ ".xml")
    @fileWr=File.new('../Results/FileOutput'+ timestmp+ ".xml", "w")
    @fileWr.write(@xmlObj.to_xml)
    @fileWr.close
  end
  def getFirstNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).first()  #Or    # @xmlObj.xpath(strNodeXPath)[0]  end
  def getLasttNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).last()  #Or    # @xmlObj.xpath(strNodeXPath)[0]  end
  def readFirstNodeContent(strXpath, strAttrVal)
    # @xmlObj.xpath("//P_ACTIVE[@channel='"+ strAttrVal + "']")[0].content    @xmlObj.xpath(strXpath + "'"+ strAttrVal + "']")[0].content  #If we dont keep content here, it reads the whole node value  end
  def readLastNodeContent(strXpath, strAttrVal)
    # @xmlObj.xpath("//P_ACTIVE[@channel='"+ strAttrVal + "']")[0].content    @xmlObj.xpath(strXpath + "'"+ strAttrVal + "']").last().content  #If we dont keep content here, it reads the whole node value  end
  def readNodeContent(strXpath, index)
    # @xmlObj.xpath(strXpath).last().content    @xmlObj.xpath(strXpath)[index.to_i].content
  end
  def removeNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).remove
  end  def removeFirstNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath)[0].remove
  end  def removeLastNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).last().remove
  end
  def countNodes(strXpath)
    @xmlObj.xpath(strXpath).count
  end
  def modify_node_content(strXpath, strValue)
    @xmlObj.xpath(strXpath)[0].content=strValue  end
  def AddNode(strXpath, strNode, index)
    if @xmlObj.xpath(strXpath).count >= 0      @xmlObj.xpath(strXpath)[index].add_next_sibling(strNode)
    end  end
  def getAttributeValue(strXpath, strAttribute)
    node= @xmlObj.xpath(strXpath)[0]
    node.attributes[strAttribute].value
  end  def modify_attribute_val(strXpath, strAttribute, val_to_assign)
    node= @xmlObj.xpath(strXpath)[0]
    node.attributes[strAttribute].value=val_to_assign  endend

readNodes= ReadXMLNodes.new
puts 'First Node is: '+ readNodes.getFirstNode('//A_MEDIADATA/A_MEDIA')
puts 'Last Node is: '+ readNodes.getLasttNode('//A_MEDIADATA/A_MEDIA')
puts 'Convert to xml: '+ readNodes.getLasttNode('//A_MEDIADATA/A_MEDIA').to_xml

# puts 'Read Node: '+ readNodes.getNode('//P_METADATA/METADATA')# puts 'Remove Node: '+ readNodes.removeNode('//P_METADATA/METADATA')# puts 'Read Node: '+ readNodes.getNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ First Read+++++++++++++++++++++++++++'puts readNodes.getNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ Remove Node +++++++++++++++++++++++++++'puts readNodes.removeLastNode('//P_METADATA/METADATA')
puts readNodes.removeNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ Read After +++++++++++++++++++++++++++'puts readNodes.getNode('//P_METADATA/METADATA')
puts readNodes.readFirstNodeContent('//P_ACTIVE[@channel=', 'tiau')
puts readNodes.readLastNodeContent('//A_PRICEDATA/A_PRICE[@channel=', 'test')
puts readNodes.readLastNodeContent('//A_MEDIADATA/A_MEDIA[@type=', 'image')
puts 'Print Node content'puts readNodes.readNodeContent("//A_MEDIADATA/A_MEDIA[@type='image']", 4)

print "Counting Nodes: "puts readNodes.countNodes("//A_MEDIADATA/A_MEDIA")
puts readNodes.modify_node_content("//P_ACTIVE[@channel='test']", "Venu")
puts readNodes.modify_node_content("//ARTICLEDATA/ARTICLE/NR", "999999")
puts "testing"puts readNodes.AddNode('//A_MEDIADATA/A_MEDIA', $imgNode, 4)
puts 'reading attribute value'puts readNodes.getAttributeValue('//P_ACTIVE', 'channel')
puts 'modify attribute value: 'readNodes.modify_attribute_val('//P_ACTIVE', 'channel', 'AttributeValChanged')
print 'Changed attribute value is: 'puts readNodes.getAttributeValue('//P_ACTIVE', 'channel')
puts readNodes.saveXML

=begin1. Add Nodes2. Add Attribute3. Modify Attribute4. Remove Attribute5. Read Attribute value6.=end

Wednesday, 25 February 2015

class UserHelper 

 
def self.sd_sftp_user  SftpHelper.obj.connect_sftp FigNewton.sftp.mass.sftp_host,
                              FigNewton.sftp.mass.sftp_uname,
                              FigNewton.sftp.mass.sftp_key
  SftpHelper.obj
end
 
 
def self.dynamo_user  @dynamo_db = AWS::DynamoDB.new(access_key_id: FigNewton.dynamodb.access_key_id,
                                 secret_access_key: FigNewton.dynamodb.secret_access_key,
                                 region: FigNewton.dynamodb.region)
  @dynamo_dbend 

end


class Dynamo  include Singleton  def initialize 
 # @dynamo_db = AWS::DynamoDB.new(access_key_id: FigNewton.dynamodb.access_key_id,    #                                secret_access_key: FigNewton.dynamodb.secret_access_key,    #                                region: FigNewton.dynamodb.region)
    @dynamo_db = AWS::DynamoDB.new(access_key_id: 'enter access key id ',
                                   secret_access_key: 'enter secret key here,
                                   region: 'enter region id')
  end  

  
  # {'email' => 'mai@email.com', 'rollno' => 3},'name')   
def get_col_values(table_name, ref_column_hash, col_name)
    items = []
    table = @dynamo_db.tables[table_name]
    table.load_schema
    rows = table.items
    ref_column_hash.each do |key, value|
      rows = rows.where(key.to_sym=>value)
    end    rows.each do |row|
      items.push row.attributes[col_name]
    end    items 
 end
  def get_rows(table_name, ref_column_name, ref_col_value, col_name)
    items = []
    table = @dynamo_db.tables[table_name]
    table.load_schema
    table.items.select(ref_column_name.to_sym,col_name.to_sym ) do |row|
      if row.attributes[ref_column_name].to_i.equal? ref_col_value.to_i
        items.push row      end    end    items  end
  # returns the table object  def get_table(table_name)
    table = @dynamo_db.tables[table_name]
    table.load_schema
    table  end
  
end
 
# A helper class to access information stored in S3.
 class S3Helper   
include Singleton 
 # creates the singleton object   
def self.obj 
 S3Helper.instance
end
  
 # Initialize the helper and get the AWS S3 object. 
 def initialize     
# @s3_object = AWS::S3.new access_key_id: FigNewton.s3.access_key_id,    #                          secret_access_key: FigNewton.s3.secret_access_key    
 end 
 
 # Read a file from an S3 bucket.  #  # ==== Attributes  #  #   +fname+ - The name of the file to read from S3.  #  # ==== Examples  #  #   # To read a file from an S3 bucket, call the .read_file method from  #   # your code in the following way:  #   @s3_user.read_file 'test.xml'  def read_file(fname)
    @s3_object.buckets[@bucket].objects[fname].read
  end
 
end   


UserHelper.sd_sftp_user.read_file('folder/test.csv')