How to use proxy method of Selenium.WebDriver.Firefox Package

Best Selenium code snippet using Selenium.WebDriver.Firefox.proxy

capabilities.rb

Source:capabilities.rb Github

copy

Full Screen

...32            :browser_version,33            :platform_name,34            :accept_insecure_certs,35            :page_load_strategy,36            :proxy,37            :set_window_rect,38            :timeouts,39            :unhandled_prompt_behavior,40            :strict_file_interactability,41            # remote-specific42            :remote_session_id,43            # TODO: (alex) deprecate in favor of Firefox::Options?44            :accessibility_checks,45            :device,46            # TODO: (alex) deprecate compatibility with OSS-capabilities47            :implicit_timeout,48            :page_load_timeout,49            :script_timeout50          ].freeze51          KNOWN.each do |key|52            define_method key do53              @capabilities.fetch(key)54            end55            next if key == :proxy56            define_method "#{key}=" do |value|57              case key58              when :accessibility_checks59                WebDriver.logger.deprecate(":accessibility_checks capability")60              when :device61                WebDriver.logger.deprecate(":device capability")62              end63              @capabilities[key] = value64            end65          end66          #67          # Backward compatibility68          #69          alias_method :version, :browser_version70          alias_method :version=, :browser_version=71          alias_method :platform, :platform_name72          alias_method :platform=, :platform_name=73          #74          # Convenience methods for the common choices.75          #76          class << self77            def edge(opts = {})78              WebDriver.logger.deprecate('Selenium::WebDriver::Remote::W3C::Capabilities.edge',79                                         'Selenium::WebDriver::Remote::Capabilities.edge')80              Remote::Capabilities.edge(opts)81            end82            def firefox(opts = {})83              WebDriver.logger.deprecate('Selenium::WebDriver::Remote::W3C::Capabilities.firefox',84                                         'Selenium::WebDriver::Remote::Capabilities.firefox')85              Remote::Capabilities.firefox(opts)86            end87            alias_method :ff, :firefox88            #89            # @api private90            #91            def json_create(data)92              data = data.dup93              caps = new94              caps.browser_name = data.delete('browserName')95              caps.browser_version = data.delete('browserVersion')96              caps.platform_name = data.delete('platformName')97              caps.accept_insecure_certs = data.delete('acceptInsecureCerts') if data.key?('acceptInsecureCerts')98              caps.page_load_strategy = data.delete('pageLoadStrategy')99              timeouts = data.delete('timeouts')100              caps.implicit_timeout = timeouts['implicit'] if timeouts101              caps.page_load_timeout = timeouts['pageLoad'] if timeouts102              caps.script_timeout = timeouts['script'] if timeouts103              proxy = data.delete('proxy')104              caps.proxy = Proxy.json_create(proxy) unless proxy.nil? || proxy.empty?105              # Remote Server Specific106              caps[:remote_session_id] = data.delete('webdriver.remote.sessionid')107              # Marionette Specific108              caps[:accessibility_checks] = data.delete('moz:accessibilityChecks')109              caps[:profile] = data.delete('moz:profile')110              caps[:rotatable] = data.delete('rotatable')111              caps[:device] = data.delete('device')112              # any remaining pairs will be added as is, with no conversion113              caps.merge!(data)114              caps115            end116            #117            # Creates W3C compliant capabilities from OSS ones.118            # @param oss_capabilities [Hash, Remote::Capabilities]119            #120            def from_oss(oss_capabilities) # rubocop:disable Metrics/MethodLength121              w3c_capabilities = new122              # TODO: (alex) make capabilities enumerable?123              oss_capabilities = oss_capabilities.__send__(:capabilities) unless oss_capabilities.is_a?(Hash)124              oss_capabilities.each do |name, value|125                next if value.nil?126                next if value.is_a?(String) && value.empty?127                capability_name = name.to_s128                snake_cased_capability_names = KNOWN.map(&:to_s)129                camel_cased_capability_names = snake_cased_capability_names.map(&w3c_capabilities.method(:camel_case))130                next unless snake_cased_capability_names.include?(capability_name) ||131                            camel_cased_capability_names.include?(capability_name) ||132                            capability_name.match(EXTENSION_CAPABILITY_PATTERN)133                w3c_capabilities[name] = value134              end135              # User can pass :firefox_options or :firefox_profile.136              #137              # TODO: (alex) Refactor this whole method into converter class.138              firefox_options = oss_capabilities['firefoxOptions'] || oss_capabilities['firefox_options'] || oss_capabilities[:firefox_options]139              firefox_profile = oss_capabilities['firefox_profile'] || oss_capabilities[:firefox_profile]140              firefox_binary  = oss_capabilities['firefox_binary'] || oss_capabilities[:firefox_binary]141              if firefox_options142                WebDriver.logger.deprecate(':firefox_options capabilitiy', 'Selenium::WebDriver::Firefox::Options')143              end144              if firefox_profile145                WebDriver.logger.deprecate(':firefox_profile capabilitiy', 'Selenium::WebDriver::Firefox::Options#profile')146              end147              if firefox_binary148                WebDriver.logger.deprecate(':firefox_binary capabilitiy', 'Selenium::WebDriver::Firefox::Options#binary')149              end150              if firefox_profile && firefox_options151                second_profile = firefox_options['profile'] || firefox_options[:profile]152                if second_profile && firefox_profile != second_profile153                  raise Error::WebDriverError, 'You cannot pass 2 different Firefox profiles'154                end155              end156              if firefox_options || firefox_profile || firefox_binary157                options = WebDriver::Firefox::Options.new(firefox_options || {})158                options.binary = firefox_binary if firefox_binary159                options.profile = firefox_profile if firefox_profile160                w3c_capabilities.merge!(options.as_json)161              end162              w3c_capabilities163            end164          end165          #166          # @param [Hash] opts167          # @option :browser_name             [String] required browser name168          # @option :browser_version          [String] required browser version number169          # @option :platform_name            [Symbol] one of :any, :win, :mac, or :x170          # @option :accept_insecure_certs    [Boolean] does the driver accept insecure SSL certifications?171          # @option :proxy                    [Selenium::WebDriver::Proxy, Hash] proxy configuration172          #173          # @api public174          #175          def initialize(opts = {})176            @capabilities = opts177            self.proxy = opts.delete(:proxy)178          end179          #180          # Allows setting arbitrary capabilities.181          #182          def []=(key, value)183            @capabilities[key] = value184          end185          def [](key)186            @capabilities[key]187          end188          def merge!(other)189            if other.respond_to?(:capabilities, true) && other.capabilities.is_a?(Hash)190              @capabilities.merge! other.capabilities191            elsif other.is_a? Hash192              @capabilities.merge! other193            else194              raise ArgumentError, 'argument should be a Hash or implement #capabilities'195            end196          end197          def proxy=(proxy)198            case proxy199            when Hash200              @capabilities[:proxy] = Proxy.new(proxy)201            when Proxy, nil202              @capabilities[:proxy] = proxy203            else204              raise TypeError, "expected Hash or #{Proxy.name}, got #{proxy.inspect}:#{proxy.class}"205            end206          end207          #208          # @api private209          #210          def as_json(*)211            hash = {}212            @capabilities.each do |key, value|213              case key214              when :platform215                hash['platform'] = value.to_s.upcase216              when :proxy217                if value218                  hash['proxy'] = value.as_json219                  hash['proxy']['proxyType'] &&= hash['proxy']['proxyType'].downcase220                  hash['proxy']['noProxy'] = hash['proxy']['noProxy'].split(', ') if hash['proxy']['noProxy'].is_a?(String)221                end222              when String, :firefox_binary223                hash[key.to_s] = value224              when Symbol225                hash[camel_case(key.to_s)] = value226              else227                raise TypeError, "expected String or Symbol, got #{key.inspect}:#{key.class} / #{value.inspect}"228              end229            end230            hash231          end232          def to_json(*)233            JSON.generate as_json234          end...

Full Screen

Full Screen

minitest_helper.rb

Source:minitest_helper.rb Github

copy

Full Screen

1require File.dirname(__FILE__) + '/config/automation_config';2require File.dirname(__FILE__) + '/config/proxy/settings';3require 'minitest/autorun' 4require 'shoulda/context' 5require 'selenium-webdriver' 6require 'browsermob/proxy'7require 'timeout'8require 'minitest/reporters'9Minitest::Reporters.use! Minitest::Reporters::DefaultReporter.new10#### HEALTHCENTRAL11HC_BASE_URL    = Configuration["healthcentral"]["base_url"]12HC_DRUPAL_URL  = Configuration["healthcentral"]["drupal_url"]13IMMERSIVE_URL  = Configuration["healthcentral"]["immersive"]14COLLECTION_URL = Configuration["collection_url"]15ASSET_HOST     = Configuration["asset_host"]16MED_BASE_URL   = Configuration["medtronic"]["base_url"]17#### BERKELEY WELLNESS18BW_BASE_URL    = Configuration["berkeley"]["base_url"]19BW_ASSET_HOST  = Configuration["berkeley"]["asset_host"]20#### THE BODY21BODY_URL            = Configuration["thebody"]["base_url"]22THE_BODY_ASSET_HOST = Configuration["thebody"]["asset_host"]23  24$_cache_buster ||= "?foo=#{rand(36**8).to_s(36)}"25def firefox26  # Selenium::WebDriver::Firefox::Binary.path= '/opt/firefox/firefox'27  # Selenium::WebDriver::Firefox::Binary.path= '/Applications/Firefox.app/Contents/MacOS/firefox'28  @driver = Selenium::WebDriver.for :firefox29  @driver.manage.window.resize_to(1224,1000)30  @driver.manage.timeouts.implicit_wait = 531end32def firefox_with_proxy33  proxy_location = Settings.location34	@server = BrowserMob::Proxy::Server.new(proxy_location)35	@server.start36	@proxy = server.create_proxy37	@profile = Selenium::WebDriver::Firefox::Profile.new38	@profile.proxy = @proxy.selenium_proxy39	@driver = Selenium::WebDriver.for :firefox, :profile => @profile40  @driver.manage.window.resize_to(1224,1000)41  @driver.manage.timeouts.implicit_wait = 542end43def fire_fox_with_secure_proxy44  proxy_location = Settings.location45  $_server ||= BrowserMob::Proxy::Server.new(proxy_location).start46  @proxy = $_server.create_proxy47  @profile = Selenium::WebDriver::Firefox::Profile.new48  @profile.proxy = @proxy.selenium_proxy(:http, :ssl)49  @driver = Selenium::WebDriver.for :firefox, :profile => @profile50  @driver.manage.window.resize_to(1224,1000)51  @driver.manage.timeouts.implicit_wait = 352  @driver.manage.timeouts.page_load = 2453end54def fire_fox_remote_proxy55  proxy_location = Settings.location56  server = BrowserMob::Proxy::Server.new(proxy_location)57  server.start58  @proxy = server.create_proxy59  @profile = Selenium::WebDriver::Firefox::Profile.new60  @profile.proxy = @proxy.selenium_proxy(:http, :ssl)61  caps = Selenium::WebDriver::Remote::Capabilities.new(62    :browser_name => "firefox", :firefox_profile => @profile63  )64  @driver = Selenium::WebDriver.for(65    :remote,66    url: 'http://jenkins.choicemedia.com:4444//wd/hub',67    desired_capabilities: caps) 68  @driver.manage.window.resize_to(1224,1000)69  @driver.manage.timeouts.implicit_wait = 570end71def mobile_fire_fox_with_secure_proxy72  proxy_location = Settings.location73  $_server ||= BrowserMob::Proxy::Server.new(proxy_location).start74  75  @proxy = $_server.create_proxy76  @profile = Selenium::WebDriver::Firefox::Profile.new77  @profile.proxy = @proxy.selenium_proxy(:http, :ssl)78  @profile['general.useragent.override'] = 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'79  @driver = Selenium::WebDriver.for :firefox, :profile => @profile80  @driver.manage.window.resize_to(425,960)81  @driver.manage.timeouts.implicit_wait = 582  @driver.manage.timeouts.page_load = 2483end84def fire_fox_remote85  @driver = Selenium::WebDriver.for(86    :remote,87    url: 'http://jenkins.choicemedia.com:4444//wd/hub',88    desired_capabilities: :firefox)89  @driver.manage.window.resize_to(1224,1000)90  @driver.manage.timeouts.implicit_wait = 591end92def cleanup_driver_and_proxy93  @driver.quit  94  @proxy.close95end96def phantomjs97  @driver = Selenium::WebDriver.for :remote, url: 'http://localhost:8001'98end99def visit(url)100  preload_page(url)101  begin102    @driver.navigate.to url 103  rescue Timeout::Error, Net::ReadTimeout, Selenium::WebDriver::Error::TimeOutError104  end105  begin106    @driver.execute_script("window.stop();")107  rescue Timeout::Error, Net::ReadTimeout, Selenium::WebDriver::Error::JavascriptError108  end109  110  #Avoid race conditions111  sleep 0.75112end113def preload_page(url)114  if ENV['TEST_ENV'] == "production" || ENV['TEST_ENV'] == "staging"115    begin116      RestClient::Request.execute(method: :get, url: url,117                                timeout: 10)118    rescue RestClient::RequestTimeout119    end120  end121end122def wait_for_page_to_load123  begin124    Timeout::timeout(3) do125      loop until finished_loading?126    end127  rescue Timeout::Error, Net::ReadTimeout, EOFError128  end129  sleep 0.5130  begin131    @driver.execute_script("window.stop();")132  rescue Timeout::Error, Net::ReadTimeout133  end134end135def finished_loading?136  state = @driver.execute_script "return window.document.readyState"137  sleep 0.5138  if state == "complete"139    true140  else141    false142  end143end144def wait_for145  begin146    Selenium::WebDriver::Wait.new(:timeout => 3).until { yield }147  rescue Selenium::WebDriver::Error::NoSuchElementError, Selenium::WebDriver::Error::TimeOutError148    false149  rescue Net::ReadTimeout150    false151  end152end153#Find an element by css 154#If the element.diplayed? == true then return the element155#Otherwise return nil156def find(css)157  begin158    node = @driver.find_element(:css, css)159    node = nil if ( node.displayed? == false )160  rescue Selenium::WebDriver::Error::NoSuchElementError161    node = nil162  end163  node164end165#Looks for a Selenium element with the given css166#Text fails if the element is not on the page, or does not have text167#168# present_with_text?(".content_pad h1")169#170def present_with_text?(css)171  node = find css172  unless node173    self.errors.add(:functionality, "#{css} missing from page")174  end175  if node 176    unless node.text.length > 0177      self.errors.add(:functionality, "#{css} was blank")178    end179  end180end181def scroll_to_bottom_of_page182  @driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")183end184def open_omniture_debugger185  @driver.execute_script "javascript:void(window.open(\"\",\"dp_debugger\",\"width=600,height=600,location=0,menubar=0,status=1,toolbar=0,resizable=1,scrollbars=1\").document.write(\"<script language='JavaScript' id=dbg src='https://www.adobetag.com/d1/digitalpulsedebugger/live/DPD.js'></\"+\"script>\"))"186  sleep 1187end188def get_omniture_from_debugger189  original_window = @driver.window_handles.first190  second_window   = @driver.window_handles.last191  @driver.switch_to.window second_window192  wait_for { @driver.find_element(:css, 'td#request_list_cell').displayed? }193  omniture_node = find 'td#request_list_cell'194  begin195    omniture_text = omniture_node.text if omniture_node196  rescue Selenium::WebDriver::Error::StaleElementReferenceError197    omniture_text = nil198  end199  if omniture_text == nil200    sleep 1201    wait_for { @driver.find_element(:css, 'td#request_list_cell').displayed? }202    omniture_node = find 'td#request_list_cell'203    if omniture_node204      omniture_text = omniture_node.text205    else206      omniture_text = nil207    end208  end209  @driver.switch_to.window original_window210  omniture_text211end212def evaluate_script(script)213  begin214    @driver.execute_script "return #{script}"215  rescue Selenium::WebDriver::Error::JavascriptError216    "javascript error"217  end218end219def page_has_ad(ad_url)220  ads = []221  @proxy.har.entries.each do |entry|222    if entry.request.url.include?(ad_url)223      ads << entry.request.url224    end225  end226  if ads.compact.length >= 1227    true228  else229    false230  end231end...

Full Screen

Full Screen

proxy

Using AI Code Generation

copy

Full Screen

1proxy = Selenium::WebDriver::Proxy.new(:http => "localhost:8080")2caps = Selenium::WebDriver::Remote::Capabilities.firefox(:proxy => proxy)3proxy = Selenium::WebDriver::Proxy.new(:http => "localhost:8080")4caps = Selenium::WebDriver::Remote::Capabilities.ie(:proxy => proxy)5proxy = Selenium::WebDriver::Proxy.new(:http => "localhost:8080")6proxy = Selenium::WebDriver::Proxy.new(:http => "localhost:8080")7proxy = Selenium::WebDriver::Proxy.new(:http => "localhost:8080")8proxy = Selenium::WebDriver::Proxy.new(:http => "localhost:8080")

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful