Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[rb] move Driver Finder logic out of Selenium Manager #12429

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rb/.rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Metrics/AbcSize:
Metrics/BlockLength:
Max: 18
Exclude:
- 'lib/selenium/logger/matchers.rb'
- 'spec/**/*.rb'
- 'selenium-*.gemspec'

Expand Down
25 changes: 25 additions & 0 deletions rb/lib/selenium/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# frozen_string_literal: true

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
require 'selenium/logger/logger'

begin
require 'selenium/logger/matchers'
rescue LoadError
# project is not using RSpec
end
8 changes: 8 additions & 0 deletions rb/lib/selenium/logger/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
load("@rules_ruby//ruby:defs.bzl", "rb_library")

package(default_visibility = ["//rb:__subpackages__"])

rb_library(
name = "logger",
srcs = ["logger.rb"],
)
214 changes: 214 additions & 0 deletions rb/lib/selenium/logger/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
# frozen_string_literal: true

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

require 'forwardable'
require 'logger'

module Selenium
#
# @example Enable full logging
# logger = Selenium::Logger.new
# logger.level = :debug
#
# @example Log to file
# logger = Selenium::Logger.new
# logger.output = 'selenium.log'
#
# @example Use logger manually
# logger = Selenium::Logger.new
# logger.info('This is info message')
# logger.warn('This is warning message')
#
class Logger
extend Forwardable

def_delegators :@logger,
:progname,
:close,
:debug?,
:info?,
:warn?,
:error?,
:fatal, :fatal?,
:level

#
# @param [String] progname Allow child projects to use Selenium's Logger pattern
#
def initialize(progname, default_level: nil, ignored: nil, allowed: nil)
default_level ||= $DEBUG || ENV.key?('DEBUG') ? :debug : :warn

@logger = create_logger(progname, level: default_level)
@ignored = Array(ignored)
@allowed = Array(allowed)
@first_warning = false
end

def level=(level)
if level == :info && @logger.level == :info
info(':info is now the default log level, to see additional logging, set log level to :debug')
end

@logger.level = level
end

#
# Changes logger output to a new IO.
#
# @param [String] io
#
def output=(io)
@logger.reopen(io)
end

#
# Returns IO object used by logger internally.
#
# Normally, we would have never needed it, but we want to
# use it as IO object for all child processes to ensure their
# output is redirected there.
#
# It is only used in debug level, in other cases output is suppressed.
#
# @api private
#
def io
@logger.instance_variable_get(:@logdev).dev
end

#
# Will not log the provided ID.
#
# @param [Array, Symbol] ids
#
def ignore(*ids)
@ignored += Array(ids).flatten
end

#
# Will only log the provided ID.
#
# @param [Array, Symbol] ids
#
def allow(ids)
@allowed += Array(ids).flatten
end

#
# Used to supply information of interest for debugging a problem
# Overrides default #debug to skip ignored messages by provided id
#
# @param [String] message
# @param [Symbol, Array<Sybmol>] id
# @yield appends additional message to end of provided template
#
def debug(message, id: [], &block)
discard_or_log(:debug, message, id, &block)
end

#
# Used to supply information of general interest
#
# @param [String] message
# @param [Symbol, Array<Sybmol>] id
# @yield appends additional message to end of provided template
#
def info(message, id: [], &block)
discard_or_log(:info, message, id, &block)
end

#
# Used to supply information that suggests an error occurred
#
# @param [String] message
# @param [Symbol, Array<Sybmol>] id
# @yield appends additional message to end of provided template
#
def error(message, id: [], &block)
discard_or_log(:error, message, id, &block)
end

#
# Used to supply information that suggests action be taken by user
#
# @param [String] message
# @param [Symbol, Array<Sybmol>] id
# @yield appends additional message to end of provided template
#
def warn(message, id: [], &block)
discard_or_log(:warn, message, id, &block)
end

#
# Marks code as deprecated with/without replacement.
#
# @param [String] old
# @param [String, nil] new
# @param [Symbol, Array<Symbol>] id
# @param [String] reference
# @yield appends additional message to end of provided template
#
def deprecate(old, new = nil, id: [], version: nil, reference: '', &block)
id = Array(id)
return if @ignored.include?(:deprecations)

id << :deprecations if @allowed.include?(:deprecations)

release = version || 'a future release'
message = +"[DEPRECATION] #{old} is deprecated, and will be removed in #{release}. "
message << "Use #{new} instead." if new
message << " See explanation for this deprecation: #{reference}." unless reference.empty?

discard_or_log(:warn, message, id, &block)
end

private

def create_logger(name, level:)
logger = ::Logger.new($stdout)
logger.progname = name
logger.level = level
logger.formatter = proc do |severity, time, progname, msg|
"#{time.strftime('%F %T')} #{severity} #{progname} #{msg}\n"
end

logger
end

def discard_or_log(level, message, id)
id = Array(id)
return if (@ignored & id).any?
return if @allowed.any? && (@allowed & id).none?

return if ::Logger::Severity.const_get(level.upcase) < @logger.level

unless @first_warning
@first_warning = true
info("Details on how to use and modify Selenium logger:\n", id: [:logger_info]) do
"https://selenium.dev/documentation/webdriver/troubleshooting/logging\n"
end
end

msg = id.empty? ? message : "[#{id.map(&:inspect).join(', ')}] #{message} "
msg += " #{yield}" if block_given?

@logger.send(level) { msg }
end
end # Logger
end # Selenium
77 changes: 77 additions & 0 deletions rb/lib/selenium/logger/matchers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# frozen_string_literal: true

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

module Selenium
class Logger
LEVELS = {error: 'ERROR',
warning: 'WARN',
deprecated: 'WARN',
info: 'INFO',
debugged: 'DEBUG'}.freeze

LEVELS.each_key do |level|
RSpec::Matchers.define :"have_#{level}" do |expected_ids, logger|
expected_ids = Array(expected_ids)

match do |actual|
# Suppresses logging output to stdout while ensuring that it is still happening
default_output = logger.io
io = StringIO.new
logger.output = io

begin
actual.call
rescue StandardError => e
raise e, 'Can not evaluate output when statement raises an exception'
ensure
logger.output = default_output
end

read = io.rewind && io.read

# Put log type, id, and deprecation tag in entry array
entries_found = read.scan(/([^ ]*) #{logger.progname} (\[:[^\]]*\])( \[.*\])?/)
levels_filtered = entries_found.select { |entry| entry.first == LEVELS[level] }
entries_filtered = levels_filtered.select { |entry| (level == :deprecated) == !entry.last.nil? }

@found_ids = entries_filtered.map { |val| val[1][/\[:(.*)\]/, 1].to_sym }
expect(expected_ids - @found_ids).to be_empty
end

failure_message do
but_message = if @found_ids.nil? || @found_ids.empty?
"not all #{Array(expected_ids)} entries were reported"
else
"instead these entries were found: #{Array(@found_ids.join(', '))}"
end
"expected #{expected_ids} to have been logged, but #{but_message}"
end

failure_message_when_negated do
but_message = "it was found among these entries: #{Array(@found_ids.join(', '))}"
"expected :#{expected_ids} not to have been logged, but #{but_message}"
end

def supports_block_expectations?
true
end
end
end
end # Logger
end # Selenium
Loading