Google+ Followers

Wednesday, 19 November 2014

Android Phone : how to proxy network requests using charles (explained with screenshots)



Precondition:
Have a wifi network on which PC( MAC) and Mobile phone are connected
record IP address of PC and Mobile
PC: 192.168.1.104
Mobile: 192.168.1.XX



Steps:

Performed on Mobile:

  1. Open Settings
  2. Selected the network connected
  3. Press long tap and choose modify network
  4. Select show advanced options 
  5. Select Manual
  6. Enter the IP address of the machine running 192.168.1.104 and port as 8888 
  7. Press SAVE 
  8. go to browser (chrome) and open a website "timesofindia.com"


PC


  1. Download charles from here and launch it,http://www.charlesproxy.com/download/
  2.  (now perform step 11 in mobile) Charles shows a dialog requesting to allow incoming connections
  3. Once the connections are allowed, any request made to internet from mobile will appear in charles, use the filter to refine the request (as shown in image below


Tuesday, 28 October 2014

command line command to list all IOS simulators installed on my mac

Open Terminal and run the below command
xcrun instruments -s devices

expected output:
Known Devices:
LON02759 (com.apple.instruments.devices.local)
iPhone - Simulator - iOS 7.1
iPhone Retina (3.5-inch) - Simulator - iOS 7.1
iPhone Retina (4-inch) - Simulator - iOS 7.1
iPhone Retina (4-inch 64-bit) - Simulator - iOS 7.1
iPad - Simulator - iOS 7.1
iPad Retina - Simulator - iOS 7.1
iPad Retina (64-bit) - Simulator - iOS 7.1

Wednesday, 30 April 2014

Calabash IOS / Android most used commands


Commands to check id's of all elements present in view
query("view,:id") for IOS 
query("*,:id") for android


Commands to list description of all elements 
query("view,:description") for IOS 
query("*,:description") for android

Sunday, 27 April 2014

Ruby subtract unix times and convert it into days and format DateTime

require 'date'
res=Time.now
days=2
res2=Time.now+(days*24*60*60)
DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")
#find difference between 2 date times
((res2-res)/(24*60*60)).to_i

calabash ruby: Installing ruby rvm on mac OSX why and how

Why Ruby or RVM ?
Calabash commands needs ruby to be installed for interpreting commands to actions.


Which version of ruby to install ? - 
Check here pre requisites section in this link 
https://github.com/calabash/calabash-ios
Currently its 2.0+

Why Rvm ?  -  RVM is used to manage to rubies on mac 

Alternative to RVM ?  -  use rbenv 

How to install rvm ?
run these command from terminal on mac

$ \curl -sSL https://get.rvm.io | bash -s stable --ruby
(there is a backslash before curl. This prevents misbehaving if you have aliased it with configuration in your ~/.curlrc file)
Then install required version of ruby ..
$ rvm install 2.0.0
$ rvm use 2.0.0
You can set a version of Ruby to use as the default for new shells. Note that this overrides the ‘system’ ruby
$ rvm use 2.1.0 --default

Check here for more documentation - http://gauravsohoni.wordpress.com/2014/01/01/rvm-implode-and-rvm-install/
      • When to clean and install - Check errors section below
      • How to verify RVM installation is successful

      Close existing terminal and reopen new terminal window
      a) type this command in terminal 'open ~/.bash_profile' check if you see code the this 


      #RVM


      [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"  # This loads RVM into a shell session.

      b) type this command 'rvm list'
      check ouput it must be like below

      ~ $: rvm list

      rvm rubies
         ruby-2.0.0-p353 [ x86_64 ]
      =* ruby-2.0.0-p451 [ x86_64 ]

      # => - current

      # =* - current && default
      #  * - default

      c) Ruby version currently used 

      ~ $: ruby -v


      ruby 2.0.0p451 


      Common Issues: While installing calabash gems 
        1) Error during RVM installation
        About to install Homebrew, press `Enter` for default installation in `/usr/local`,
        type new path if you wish custom Homebrew installation (the path needs to be writable for user)
        : Requirements installation failed with status: 1.



        2) ERROR:  While executing gem ... (Gem::FilePermissionError)
            You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.
        lon04-04266:~ dakojuu$ sudo gem install calabash-cucumber
        Building native extensions.  This could take a while...
        ERROR:  Error installing calabash-cucumber:
        ERROR: Failed to build gem native extension.

            /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb
        checking for main() in -lc... yes
        creating Makefile
          Solution resintall RVM


          Thursday, 17 April 2014

          Android -adb fast and easy way to get screenshots


          • Connect android device to PC / Mac ( make sure android sdk path is set)
          • run below commands, screen shot of current screen is taken and save on to current folder from where this command is run
          adb shell screencap -p /sdcard/screen.png
          sleep 0.1
          adb pull /sdcard/screen.png

          Sunday, 13 April 2014

          Command to launch ios simulator from mac command line OSX

          Use the below command


          alias sl='open /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app'

            Adding alias to bash profile
            Open Bash profile ( ~/.bash_profile)
            and add the below line  
            alias sl='open /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app'

            2 Solutions: How to find APP_BUNDLE_PATH calabash ios automation

            Solution 1:
            Open Xcode preferences and select location where .app file (generated when IOS code is compiled will be located) should be placed.

            APP_BUNDLE_PATH calabash ios automation

            Solution 2:
            Open Xcode
            Open organizer (or just press 'Command+ Shift +2')
            Find the application for which you are locating .app file (picture below)


            Thursday, 10 April 2014

            calabash IOS & Android FAQ


            1. What are the installation procedure for calabash iOS in windows? 
            No
            I would say not to try calabash ios with windows.
            Even if you want use windows for calabash ios options are limited.


            2. How to avoid install / uninstall the app every-time for android (while running scripts)?
             For android
            Comment this code in app_installation_hooks.rb file in android support folder 
               uninstall_apps
               install_app(ENV["TEST_APP_PATH"])
               install_app(ENV["APP_PATH"])

            3. How to run multiple feature file in one run command?
            Use cucumber tags on features - https://github.com/cucumber/cucumber/wiki/Tags

            Friday, 4 April 2014

            calabash automation : launch genymotion simulator from command line



            Command to launch genymotion headless -
            player --vm-name Nexus_4


          • if player is not already added to path, add it to path using below command in your ~/.bash_profile


            export PATH=/Applications/Genymotion.app/Contents/MacOS/:$PATH

            When more than one device is connect use 'adb -s' is used to redirect commands to particular device
            Once emulator is running they will be listed under adb devices
            Example:

             adb devices            
            List of devices attached            
            192.168.56.101:5555    device
                 
            Verfiy command are send to correct device:

             Send command to click on menu key on android device when multiple devices are connected
            adb -s 192.168.56.101:5555 shell input keyevent KEYCODE_MENU


                    

            Monday, 24 March 2014

            Setting iphone 4 inch simulator as default simulator for calabash tests

            • Open terminal and put the below line - 
            defaults write com.apple.iphonesimulator "SimulateDevice" '"iPhone (Retina)"'Open terminal and put the below line - 
            • now open simulator and check 4inch simulator is launched

            To launch tests on ios7 simulator in calabash.
            add below line to support/env.rb

            `defaults write com.apple.iphonesimulator "SimulateDevice" '"iPhone (Retina)"'`

            Monday, 10 March 2014

            launch and close genymotion emulator from command line (shell script)

            • Create a android emulator with some name ex: Nexus_5
            • launch emulator 
            • wait for device to be recognised
            • if device launch failed try again
            #!/bin/bash
            c=1
            while [ $c -le 5 ]
            do
                ps | grep "player" | awk '{print $1}' | xargs kill
                adb kill-server
                player --vm-name Nexus_5 &
                sleep 2
                adb start-server
                sleep 30
                res=`adb get-state`;echo $res
                if [ $res = "device" ]
                then
                    break
                else
                    echo "repeat simulator launch"
                fi
                c=$(($c+1))
            done


            To install genymotion check herehttp://www.mobiletestworld.com/2014/02/install-genymotion-fastest-android-emulator-on-mac.html


            Thursday, 6 March 2014

            Calabash: Building ios app from command line

            Go to project folder (from terminal) or specify the project folder (where xcodeproj file is present) using PROJ_LOC


            • update the below commands with appropriate values for your application 
            • paste them into as shell script
            • run the shell script


            SCHEME_XC="app-cal" #name of calabash scheme
            BUILD_CONFIG="Debug" # build config (usually its debug)
            FEATURES_PATH="features"
            ARCHITECTURE_SELECTED=i386
            PROJ_LOC="../${PROJ_NAME/app.xcodeproj"

            xcodebuild  -scheme "${SCHEME_XC}" -project "${PROJ_LOC}" -configuration Debug ONLY_ACTIVE_ARCH=NO -sdk iphonesimulator build

            Saturday, 1 March 2014

            calabash:initial-commit of your code to github


            Open the folder where repository was downloaded previously (check here http://www.mobiletestworld.com/2014/03/download-calabash-ios-android-code-github.html for instruction on how to  download code)

            Add/edit  files required to be uploaded to repository 





            • you will the see added files as uncommited changes in source 
            • drag the files to saved on repository
            • drop the files into the window show below
            • press commit button (these files be commited but not pushed on remote repository yet.
            • Enter commit message and submit

            • Push changes to remote location so changes are saved permanently on remote server

            • Select branch on master to push
            Check that changes are now shown in github or where repository is hosted 

            calabash-how to download source code from github

              Create a new repository
                    incase you just want to download code skip to next section 

            • Create GIT hub account at https://github.com/ its free 
            Create GIT hub account
            • Click on top right corner and create a repository if you need a new one or incase you just want to download code (clone) then 
            • Enter you git hub account name and description and submit, your repository will be created
              Download source code

            • To download the repository, copy the link of the repo as indicated below 
            download the repository
            • Open git client ex: source tree and paste the link and choose folder where repository has to be downloaded.
            download source code
            Add caption

            •  Once downloading is complete you will see the files in chosen directory and in source as below

            To add existing code to repository click here - http://www.mobiletestworld.com/2014/03/how-to-do-first-commit-calabash-code.html

            Thursday, 27 February 2014

            Install: genymotion fastest android emulator on mac(with screenshots)


            To open and control genymotion from command line check this link http://www.mobiletestworld.com/2014/03/launch-and-close-genymotion-emulator-from-command-line.html


            Copy app and genymotion shell to applications

            Log into genymotion to get list of devices



            Choose the device to be created





            Select and create the emulator








            Open genymotion app from applications and launch emulator

            Tuesday, 25 February 2014

            Speed up mobile automation with fast android emulator using HAXM or genymotion

            To speed up android automation there are 2 options 

            1) hardware  acceleration using intel Hardware Accelerated Execution Manager
            there are 2 ways to install this

              a) Using android SDK manager (preferred method)
              - Launch  Android SDK Manager.
              - select Intel x86 Emulator Accelerator (HAXM) under Extras
              - Install it 


              b)Manually - look for instructions here - http://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-mac-os-x

            After installing HAXM create AVD(Android virtual device) 
            Creating AVD(Android virtual device) - from android SDK manager , select tools and manage AVD 
            and create a new AVD with intel CPU and enabling host GPU. Like shown in below picture



            2) second fastest simulator is using genymotion 
            check installation screenshots here -http://www.mobiletestworld.com/2014/02/install-genymotion-fastest-android-emulator-on-mac.html


            calabash-android: Start emulator , Set language/region/locale and quit using command line

            • Wipe emulator and start again
            emulator -wipe-data -avd <avd-name>
            TO create avd check here - http://www.mobiletestworld.com/2014/02/fast-android-emulator-haxm-or-genymotion.html

            Check device is launched or wait

            adb wait-for-device
            echo "device ready now"
            • set country to germany - de and locale to german- de and restart emulator (this command also works on rooted devices)
            adb shell 'setprop persist.sys.language de; setprop persist.sys.country de; stop; sleep 5; start'
            • Wait until device is ready
            adb wait-for-device
            echo "device ready now"
            • Run all commands at once
            emulator -wipe-data -avd Android-4.2 &
            adb wait-for-device;echo "device ready now";sleep 10
            adb shell 'setprop persist.sys.language de; setprop persist.sys.country de; stop; sleep 5; start'
            adb wait-for-device;echo "device ready now";sleep 20


            Wednesday, 19 February 2014

            Ruby: How to Read value from strings.xml files

            Sample XML format
            <?xml version="1.0" encoding="UTF-8"?>
            <resources>
              <string name="september">September</string>
              <string name="shortdate">DD.MM.YYYY</string>
            </resources>

            Ruby code to read the XML

            resources/string in below must be used to represent the parent child heirarchy


            #require the gem and module required
            require 'rexml/document'  
            #Read language strings by default or else read specified file
            # filename can be absolute path or relative path
            all_strings_hash will be return value which contains strings and values 
            def read_xml(filename="xxx/filename.xml")
                doc = REXML::Document.new(File.new(filename))
                all_strings_hash={}
                doc.elements.each("resources/string") do |ele|
                  all_strings_hash[ele.attributes["name"]]=ele.text
                end
                return all_strings_hash
            end


            Common Errors : uninitialized constant ReusableMethods::REXML (NameError)
            /Users/tejasvi.manmatha/projects/meine.tui.ui-automation/features/common/support/reusable_methods.rb:106:in `read_xml'
            /Users/tejasvi.manmatha/projects/meine.tui.ui-automation/features/common/support/reusable_methods.rb:36:in `get_localized_string'

            Solution: put this line at beginning of ruby file require 'rexml/document' 

            Android : how to capture screen from adb shell and save them on PC MAC Linux

            • Shell script to copy 10 images at interval of 0.1 seconds and save them on device
            N=10
            for VARIABLE in 1 2 3 4 5 .. N
            do
            adb shell screencap -p /sdcard/screen$VARIABLE.png
            sleep 0.1
            done

            • Shell script to pull the images from devices and save them on PC / MAC / Linux

            N=10
            for VARIABLE in 1 2 3 4 5 .. N
            do
            adb pull /sdcard/screen$VARIABLE.png
            sleep 0.1
            done

            Sunday, 16 February 2014

            Starting calabash ios Testing with simple application Source code + Steps + video

            Source Code: Download source code for project , lets use an open source project https://github.com/mayuur/MJTransitionEffect to set up our tests, 


            Video : 



            Steps:

            First download the app and compile it 
            • Setup calabash using below command (run this command from folder where project is present)
            calabash-ios setup

            • open MJTransitionEffect.xcodeproj file and choose MJTransitionEffect-cal scheme and run the application 
            • Verify below message is shown in xcode 
            MJTransitionEffect[14968:a0b] Started LPHTTP server on port 37265


            • Using terminal navigate to folder where application is present and type below command
            calabash-ios console 
            • Once you see ruby console run below commands and verify output of below command
            MJTransitionEffect $: calabash-ios console 
            Running irb...
            irb(main):001:0> start_test_server_in_background
            irb(main):001:0> touch "view marked:'India'"
            irb(main):001:0> touch "view marked:'DONE'"

            Finally Thanks to mayuur for such a nice project https://github.com/mayuur/MJTransitionEffect

            Tuesday, 11 February 2014

            IOS What are rows and sections , Scroll table view using calabash

            Table views in IOS

            What are rows and sections ??

            A table view has only one column and allows vertical scrolling only. It consists of rows in sections. Each section can have a header and a footer that displays text or an image.

            For more details  refer here - https://developer.apple.com/library/ios/documentation/userexperience/conceptual/tableview_iphone/AboutTableViewsiPhone/AboutTableViewsiPhone.html







            Find value of third tableViewCell in table view by using index:
            query("tableViewCell index:2 label",:text)

            Scrolling down in IOS table view:
             scroll("tableView", :down)
              scroll "scrollView", :down

            Scroll to row 3 in table view
              scroll_to_row "tableView", 2
              
            Scroll to first cell:
              scroll_to_cell

            Scroll to cell options: 

             {:query => "tableView",
             :row => 0,
             :section => 0,
             :scroll_position => :top,
             :animate => true}


            Scroll to each cell and print values of labels
              each_cell(:post_scroll=>0) do |row, sec|
              sleep 0.5
              puts query("tableViewCell indexPath:#{row},#{sec} label",:text)
              end


            Scroll to row or section till particular text is found
            #Scroll to text in table view
              def scroll_table(text)
                section=0
                scroll_to_cell(:row => 0, :section => 0)  #scroll to top of table
                sleep 1
            #Below code loops through each cell to check if the appropriate text was found
                each_cell(:animate => false, :post_scroll => 0.2) do |row, sec|
                  if query("tableViewCell indexPath:#{row},#{sec} label", :text).first==text
                    break # if text found break from loop
                  end
                  section=section+1
                end
              end

            The above code scroll through to table to find text , 
            if you want to click on text , add touch command before break

            Ruby method to read from excel (calabash helper)

            Ruby code to open excel .xls or .xlsx files and then read it into variable

            specify absolute or relative path of file 
            then run this below code from ruby  
              file_path= <location of excel file>
                  workbook ||= RubyXL::Parser.parse(file_path)
                  strings||=workbook[0].get_table[:table]

            Sunday, 9 February 2014

            calabash cross platform extended: calabash ios & Android

            I have extended my test suite to follow page / screen object model.

            have a look at visual representation of the page object pattern and how does it map on to different files in the test suite.

            Classes

            1) Ibase (ios) and Abase( Android) are base classes for IOS / Android
            2) Base page extends base classes further  and implements some functionality that can be used by all classes extending it.
            3) Welcome page extends base class and implements methods which are specific to welcome page

            BDD
            (in a typical scenario)
            1. Each step in a feature file will have implementation in step definitions folder
            2. Each step definitions will create a corresponding object of a page (ex: Welcomepage.new)
            3. Each page object will call some calabash method to verify elements (ex: query ) or do actions on app (ex: touch)  which is implement  with in page.

            Sample Source code:

            1) Feature file -
            Scenario: Navigate to login page
                Given I am on login page
                Then I verify login page

            2)  Step definition-
            Given(/^I am on login page$/) do
              WelcomePage.new(self).wait_for_welcome_screen
              WelcomePage.new(self).navigate_to_login
              LoginPage.new(self).await
            end


            3) method implementation.
            def wait_for_welcome_screen
                wait_for_elements_exist([trait])
            end

            4)Sample class
            
            class WelcomePage < BasePage
            
              def trait
                "* marked:'Start blogging in seconds.'"
              end
            
              def wait_for_welcome_screen
                wait_for_elements_exist([trait])
              end
            
              end
            

            5) Base page
            class BasePage < Calabash::ABase
             # Template for adding commond android methods
            end
            
            

            Wednesday, 5 February 2014

            Steps: to set enviroment variables for calabash android on windows (with screenshots)

            1. Right click on my computer
            2. open Advanced settings -> Environment variables
            3. create new variable 
            4. Put value as 'ANDROID_HOME' and set value as path to android SDK ex: c:\xxxfolder\sdk
              All Steps
            5. Set another variable JAVA_HOME with value as path to JAVA JDK folder 
              Env variable
            6. locate platform-tools under android-sdk folder, copy the path and open PATH env variable , Then  add ';' to end of existing value of path variable. then paste the platform-tools path

            7. Set Android Path
            8.  Repeat step 6 for tools folder located under  android-sdk
            9. Now close terminal or command prompt
            10. relaunch command prompt
            11. type SET  and press enter in command prompt to check if env variables are set
            12. also type 'adb devices' and check if adb command is added to existing path.






            Monday, 3 February 2014

            calabash android: useful commands

            1) back arrow & Menu key
            performAction('go_back')



            performAction('press_menu')

            2) Enter key on virtual key pad 
              performAction('send_key_enter')

            3) Swipe right and left / Scroll up down

              performAction('swipe', 'left')
              performAction('swipe', 'right')


              performAction('scroll_down')
              performAction('scroll_up')


            4) wait until time_out (seconds) for particular text to be shown ,
            if text is shown return true else false

              def wait_for_page_to_load(text, time_out)
                begin
                  wait_poll({:until_exists => "* marked:'#{text}'", :timeout => time_out}) do
                    puts "wait_for_page_to_load: checking text #{text}"
                  end
                rescue
                  return false
                end
                return true
              end

            5) Scroll up and down

              def scroll_view(dir)
                if (dir=="up")
                  performAction('drag', 50, 50, 70, 90, 10)
                elsif (dir=="down")
                  performAction('drag', 50, 50, 90, 70, 10)
                end
              end

            6) Read test data from excel
            require 'rubyXL'

            def read_test_data()
                file_path=$g_booking_data
                
            workbook = RubyXL::Parser.parse(file_path)
                hash_arr=workbook[1].get_table(["Surname", "Today"])
                return hash_arr[:table]
              end