Sha256: 5664b6e4902edbfc2b165dfc96d9c6884d9cf855a22eb0d605ee5e5cbc590126

Contents?: true

Size: 1.23 KB

Versions: 3

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

require 'rest-client'

# Module for checking parts on a site
module Checker
  class << self
    def valid_link?(href)
      !href.start_with?('mailto:')
    end

    # Usign Javascript fetch to retrieve URL. See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch and
    # https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters for details
    # @return [Integer] Status code
    def link_status(href)
      init_options = "const myInit = {
        method: 'GET',
        credentials: 'same-origin',
        cache: 'default',
        mode: 'cors'
      };"
      get_js_code = "var url='#{href}'; #{init_options} return fetch(url, myInit).then(res=>{return res.status});"
      GenericTest.browser.execute_script get_js_code
    rescue Selenium::WebDriver::Error::JavascriptError
      return call_via_rest_client(href) unless GenericTest.only_javascript

      raise GenericTest::Error, "Failed to fetch url '#{href}'"
    end

    # Use rest-client to try and get status of URL
    def call_via_rest_client(href)
      RestClient.get(href).code
    rescue RestClient::Exception => e
      return e.response&.code if e.respond_to? :response

      raise e
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
generic_test-0.1.9 lib/generic_test/checker.rb
generic_test-0.1.8 lib/generic_test/checker.rb
generic_test-0.1.7 lib/generic_test/checker.rb