From 39aa9b6fbc6795b2c70a58ffb0843724c547f568 Mon Sep 17 00:00:00 2001 From: Fabian Larranaga Date: Tue, 18 Dec 2018 20:02:26 -0300 Subject: [PATCH 1/3] Fix several rubocop offenses --- Appraisals | 2 +- Gemfile | 2 +- examples/sinatra/Gemfile | 12 +- examples/sinatra/config.ru | 2 +- examples/sinatra/sinatra_app.rb | 19 +- exception_notification.gemspec | 48 +++--- gemfiles/rails4_0.gemfile | 6 +- gemfiles/rails4_1.gemfile | 6 +- gemfiles/rails4_2.gemfile | 6 +- gemfiles/rails5_0.gemfile | 6 +- gemfiles/rails5_1.gemfile | 6 +- gemfiles/rails5_2.gemfile | 6 +- lib/exception_notification/rack.rb | 11 +- lib/exception_notification/sidekiq.rb | 17 +- lib/exception_notifier.rb | 8 +- lib/exception_notifier/base_notifier.rb | 4 +- lib/exception_notifier/campfire_notifier.rb | 11 +- lib/exception_notifier/datadog_notifier.rb | 59 +++---- lib/exception_notifier/email_notifier.rb | 62 +++---- .../google_chat_notifier.rb | 19 +- lib/exception_notifier/hipchat_notifier.rb | 21 ++- lib/exception_notifier/irc_notifier.rb | 53 +++--- lib/exception_notifier/mattermost_notifier.rb | 162 +++++++++--------- .../modules/error_grouping.rb | 6 +- lib/exception_notifier/notifier.rb | 9 +- lib/exception_notifier/slack_notifier.rb | 10 +- lib/exception_notifier/sns_notifier.rb | 14 +- lib/exception_notifier/teams_notifier.rb | 85 +++++---- lib/exception_notifier/webhook_notifier.rb | 5 +- .../install_generator.rb | 2 +- test/dummy/Rakefile | 2 +- test/dummy/config.ru | 2 +- test/dummy/config/application.rb | 8 +- test/dummy/config/boot.rb | 2 +- test/dummy/config/environment.rb | 14 +- test/dummy/config/environments/production.rb | 2 +- test/dummy/config/environments/test.rb | 2 +- test/dummy/config/routes.rb | 2 +- test/dummy/db/schema.rb | 17 +- test/dummy/script/rails | 4 +- .../test/functional/posts_controller_test.rb | 130 +++++++------- test/dummy/test/test_helper.rb | 4 +- test/exception_notification/rack_test.rb | 15 +- .../campfire_notifier_test.rb | 66 ++++--- .../datadog_notifier_test.rb | 96 +++++------ .../exception_notifier/email_notifier_test.rb | 142 +++++++-------- .../google_chat_notifier_test.rb | 24 +-- .../hipchat_notifier_test.rb | 94 +++++----- test/exception_notifier/irc_notifier_test.rb | 48 +++--- .../mattermost_notifier_test.rb | 34 ++-- .../modules/error_grouping_test.rb | 77 ++++----- test/exception_notifier/sidekiq_test.rb | 10 +- .../exception_notifier/slack_notifier_test.rb | 114 ++++++------ test/exception_notifier/sns_notifier_test.rb | 53 +++--- .../exception_notifier/teams_notifier_test.rb | 33 ++-- .../webhook_notifier_test.rb | 41 +++-- test/exception_notifier_test.rb | 74 ++++---- test/test_helper.rb | 14 +- 58 files changed, 880 insertions(+), 923 deletions(-) diff --git a/Appraisals b/Appraisals index 987feadd..24a06a5b 100644 --- a/Appraisals +++ b/Appraisals @@ -1,7 +1,7 @@ rails_versions = ['~> 4.0.5', '~> 4.1.1', '~> 4.2.0', '~> 5.0.0', '~> 5.1.0', '~> 5.2.0'] rails_versions.each do |rails_version| - appraise "rails#{rails_version.slice(/\d+\.\d+/).gsub('.', '_')}" do + appraise "rails#{rails_version.slice(/\d+\.\d+/).tr('.', '_')}" do gem 'rails', rails_version end end diff --git a/Gemfile b/Gemfile index b4e2a20b..fa75df15 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,3 @@ -source "https://rubygems.org" +source 'https://rubygems.org' gemspec diff --git a/examples/sinatra/Gemfile b/examples/sinatra/Gemfile index b03b5372..d6c9f377 100644 --- a/examples/sinatra/Gemfile +++ b/examples/sinatra/Gemfile @@ -1,8 +1,8 @@ -source "https://rubygems.org" +source 'https://rubygems.org' -gem "exception_notification", path: "../../" +gem 'exception_notification', path: '../../' -gem "thin", "~> 1.5.1" -gem "sinatra", "~> 1.3.5" -gem "foreman" -gem "mailcatcher" +gem 'foreman' +gem 'mailcatcher' +gem 'sinatra', '~> 1.3.5' +gem 'thin', '~> 1.5.1' diff --git a/examples/sinatra/config.ru b/examples/sinatra/config.ru index 1b41b714..9b26ef06 100644 --- a/examples/sinatra/config.ru +++ b/examples/sinatra/config.ru @@ -1,3 +1,3 @@ -require ::File.expand_path('../sinatra_app', __FILE__) +require ::File.expand_path('../sinatra_app', __FILE__) run SinatraApp diff --git a/examples/sinatra/sinatra_app.rb b/examples/sinatra/sinatra_app.rb index fb1ba164..65d31bbf 100644 --- a/examples/sinatra/sinatra_app.rb +++ b/examples/sinatra/sinatra_app.rb @@ -9,24 +9,25 @@ class SinatraApp < Sinatra::Base end use ExceptionNotification::Rack, - email: { - email_prefix: '[Example] ', - sender_address: %{"notifier" }, - exception_recipients: %w{exceptions@example.com}, - smtp_settings: { - address: 'localhost', - port: 1025 + email: { + email_prefix: '[Example] ', + sender_address: %("notifier" ), + exception_recipients: %w[exceptions@example.com], + smtp_settings: { + address: 'localhost', + port: 1025 + } } - } get '/' do raise StandardError, "ERROR: #{params[:error]}" unless params[:error].blank? + 'Everything is fine! Now, lets break things clicking here . Dont forget to see the emails at mailcatcher !' end get '/background_notification' do begin - 1/0 + 1 / 0 rescue Exception => e ExceptionNotifier.notify_exception(e, data: { msg: 'Cannot divide by zero!' }) end diff --git a/exception_notification.gemspec b/exception_notification.gemspec index 75cf3a87..154eeb03 100644 --- a/exception_notification.gemspec +++ b/exception_notification.gemspec @@ -1,12 +1,12 @@ Gem::Specification.new do |s| s.name = 'exception_notification' s.version = '4.3.0' - s.authors = ["Jamis Buck", "Josh Peek"] - s.date = %q{2018-11-22} - s.summary = "Exception notification for Rails apps" - s.homepage = "https://smartinez87.github.io/exception_notification/" - s.email = "smartinez87@gmail.com" - s.license = "MIT" + s.authors = ['Jamis Buck', 'Josh Peek'] + s.date = '2018-11-22' + s.summary = 'Exception notification for Rails apps' + s.homepage = 'https://smartinez87.github.io/exception_notification/' + s.email = 'smartinez87@gmail.com' + s.license = 'MIT' s.required_ruby_version = '>= 2.0' s.required_rubygems_version = '>= 1.8.11' @@ -16,24 +16,24 @@ Gem::Specification.new do |s| s.test_files = `git ls-files -- test`.split("\n") s.require_path = 'lib' - s.add_dependency("actionmailer", ">= 4.0", "< 6") - s.add_dependency("activesupport", ">= 4.0", "< 6") + s.add_dependency('actionmailer', '>= 4.0', '< 6') + s.add_dependency('activesupport', '>= 4.0', '< 6') - s.add_development_dependency "rails", ">= 4.0", "< 6" - s.add_development_dependency "resque", "~> 1.8.0" + s.add_development_dependency 'rails', '>= 4.0', '< 6' + s.add_development_dependency 'resque', '~> 1.8.0' # Sidekiq 3.2.2 does not support Ruby 1.9. - s.add_development_dependency "sidekiq", "~> 3.0.0", "< 3.2.2" - s.add_development_dependency "tinder", "~> 1.8" - s.add_development_dependency "httparty", "~> 0.10.2" - s.add_development_dependency "mocha", ">= 0.13.0" - s.add_development_dependency "sqlite3", ">= 1.3.4" - s.add_development_dependency "coveralls", "~> 0.8.2" - s.add_development_dependency "appraisal", "~> 2.2.0" - s.add_development_dependency "hipchat", ">= 1.0.0" - s.add_development_dependency "carrier-pigeon", ">= 0.7.0" - s.add_development_dependency "slack-notifier", ">= 1.0.0" - s.add_development_dependency "aws-sdk-sns", "~> 1" - s.add_development_dependency "dogapi", ">= 1.23.0" - s.add_development_dependency "timecop", "~>0.9.0" - s.add_development_dependency "mock_redis", "~> 0.18.0" + s.add_development_dependency 'appraisal', '~> 2.2.0' + s.add_development_dependency 'aws-sdk-sns', '~> 1' + s.add_development_dependency 'carrier-pigeon', '>= 0.7.0' + s.add_development_dependency 'coveralls', '~> 0.8.2' + s.add_development_dependency 'dogapi', '>= 1.23.0' + s.add_development_dependency 'hipchat', '>= 1.0.0' + s.add_development_dependency 'httparty', '~> 0.10.2' + s.add_development_dependency 'mock_redis', '~> 0.18.0' + s.add_development_dependency 'mocha', '>= 0.13.0' + s.add_development_dependency 'sidekiq', '~> 3.0.0', '< 3.2.2' + s.add_development_dependency 'slack-notifier', '>= 1.0.0' + s.add_development_dependency 'sqlite3', '>= 1.3.4' + s.add_development_dependency 'timecop', '~>0.9.0' + s.add_development_dependency 'tinder', '~> 1.8' end diff --git a/gemfiles/rails4_0.gemfile b/gemfiles/rails4_0.gemfile index 4f47847a..7117a086 100644 --- a/gemfiles/rails4_0.gemfile +++ b/gemfiles/rails4_0.gemfile @@ -1,7 +1,7 @@ # This file was generated by Appraisal -source "https://rubygems.org" +source 'https://rubygems.org' -gem "rails", "~> 4.0.5" +gem 'rails', '~> 4.0.5' -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails4_1.gemfile b/gemfiles/rails4_1.gemfile index 7e4bd92e..213be9c6 100644 --- a/gemfiles/rails4_1.gemfile +++ b/gemfiles/rails4_1.gemfile @@ -1,7 +1,7 @@ # This file was generated by Appraisal -source "https://rubygems.org" +source 'https://rubygems.org' -gem "rails", "~> 4.1.1" +gem 'rails', '~> 4.1.1' -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails4_2.gemfile b/gemfiles/rails4_2.gemfile index 6977eb02..dbed7dd7 100644 --- a/gemfiles/rails4_2.gemfile +++ b/gemfiles/rails4_2.gemfile @@ -1,7 +1,7 @@ # This file was generated by Appraisal -source "https://rubygems.org" +source 'https://rubygems.org' -gem "rails", "~> 4.2.0" +gem 'rails', '~> 4.2.0' -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails5_0.gemfile b/gemfiles/rails5_0.gemfile index 10f52e7a..49df9648 100644 --- a/gemfiles/rails5_0.gemfile +++ b/gemfiles/rails5_0.gemfile @@ -1,7 +1,7 @@ # This file was generated by Appraisal -source "https://rubygems.org" +source 'https://rubygems.org' -gem "rails", "~> 5.0.0" +gem 'rails', '~> 5.0.0' -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails5_1.gemfile b/gemfiles/rails5_1.gemfile index 6100e830..953d45c7 100644 --- a/gemfiles/rails5_1.gemfile +++ b/gemfiles/rails5_1.gemfile @@ -1,7 +1,7 @@ # This file was generated by Appraisal -source "https://rubygems.org" +source 'https://rubygems.org' -gem "rails", "~> 5.1.0" +gem 'rails', '~> 5.1.0' -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails5_2.gemfile b/gemfiles/rails5_2.gemfile index 5a706dcb..0b87fd88 100644 --- a/gemfiles/rails5_2.gemfile +++ b/gemfiles/rails5_2.gemfile @@ -1,7 +1,7 @@ # This file was generated by Appraisal -source "https://rubygems.org" +source 'https://rubygems.org' -gem "rails", "~> 5.2.0" +gem 'rails', '~> 5.2.0' -gemspec path: "../" +gemspec path: '../' diff --git a/lib/exception_notification/rack.rb b/lib/exception_notification/rack.rb index 2706b103..e8eb4fd6 100644 --- a/lib/exception_notification/rack.rb +++ b/lib/exception_notification/rack.rb @@ -1,6 +1,6 @@ module ExceptionNotification class Rack - class CascadePassException < Exception; end + class CascadePassException < RuntimeError; end def initialize(app, options = {}) @app = app @@ -25,7 +25,7 @@ def initialize(app, options = {}) if options.key?(:ignore_crawlers) ignore_crawlers = options.delete(:ignore_crawlers) - ExceptionNotifier.ignore_if do |exception, opts| + ExceptionNotifier.ignore_if do |_exception, opts| opts.key?(:env) && from_crawler(opts[:env], ignore_crawlers) end end @@ -38,11 +38,11 @@ def initialize(app, options = {}) end def call(env) - _, headers, _ = response = @app.call(env) + _, headers, = response = @app.call(env) if !@ignore_cascade_pass && headers['X-Cascade'] == 'pass' - msg = "This exception means that the preceding Rack middleware set the 'X-Cascade' header to 'pass' -- in " << - "Rails, this often means that the route was not found (404 error)." + msg = "This exception means that the preceding Rack middleware set the 'X-Cascade' header to 'pass' -- in " \ + 'Rails, this often means that the route was not found (404 error).' raise CascadePassException, msg end @@ -53,6 +53,7 @@ def call(env) end raise exception unless exception.is_a?(CascadePassException) + response end diff --git a/lib/exception_notification/sidekiq.rb b/lib/exception_notification/sidekiq.rb index 245403c5..b01e8360 100644 --- a/lib/exception_notification/sidekiq.rb +++ b/lib/exception_notification/sidekiq.rb @@ -3,15 +3,12 @@ # Note: this class is only needed for Sidekiq version < 3. module ExceptionNotification class Sidekiq - def call(worker, msg, queue) - begin - yield - rescue Exception => exception - ExceptionNotifier.notify_exception(exception, data: { sidekiq: msg }) - raise exception - end + def call(_worker, msg, _queue) + yield + rescue Exception => exception + ExceptionNotifier.notify_exception(exception, data: { sidekiq: msg }) + raise exception end - end end @@ -23,8 +20,8 @@ def call(worker, msg, queue) end else ::Sidekiq.configure_server do |config| - config.error_handlers << Proc.new { |ex, context| + config.error_handlers << proc do |ex, context| ExceptionNotifier.notify_exception(ex, data: { sidekiq: context }) - } + end end end diff --git a/lib/exception_notifier.rb b/lib/exception_notifier.rb index 8c85e011..d4f2aaae 100644 --- a/lib/exception_notifier.rb +++ b/lib/exception_notifier.rb @@ -30,7 +30,7 @@ class UndefinedNotifierError < StandardError; end # Define a set of exceptions to be ignored, ie, dont send notifications when any of them are raised. mattr_accessor :ignored_exceptions - @@ignored_exceptions = %w{ActiveRecord::RecordNotFound Mongoid::Errors::DocumentNotFound AbstractController::ActionNotFound ActionController::RoutingError ActionController::UnknownFormat ActionController::UrlGenerationError} + @@ignored_exceptions = %w[ActiveRecord::RecordNotFound Mongoid::Errors::DocumentNotFound AbstractController::ActionNotFound ActionController::RoutingError ActionController::UnknownFormat ActionController::UrlGenerationError] mattr_accessor :testing_mode @@testing_mode = false @@ -46,9 +46,10 @@ def testing_mode! self.testing_mode = true end - def notify_exception(exception, options={}, &block) + def notify_exception(exception, options = {}, &block) return false if ignored_exception?(options[:ignore_exceptions], exception) return false if ignored?(exception, options) + if error_grouping errors_count = group_error!(exception, options) return false unless send_notification?(exception, errors_count) @@ -98,8 +99,9 @@ def clear_ignore_conditions! end private + def ignored?(exception, options) - @@ignores.any?{ |condition| condition.call(exception, options) } + @@ignores.any? { |condition| condition.call(exception, options) } rescue Exception => e raise e if @@testing_mode diff --git a/lib/exception_notifier/base_notifier.rb b/lib/exception_notifier/base_notifier.rb index 7b5978b1..1276ada0 100644 --- a/lib/exception_notifier/base_notifier.rb +++ b/lib/exception_notifier/base_notifier.rb @@ -2,11 +2,11 @@ module ExceptionNotifier class BaseNotifier attr_accessor :base_options - def initialize(options={}) + def initialize(options = {}) @base_options = options end - def send_notice(exception, options, message, message_opts=nil) + def send_notice(exception, options, message, message_opts = nil) _pre_callback(exception, options, message, message_opts) result = yield(message, message_opts) _post_callback(exception, options, message, message_opts) diff --git a/lib/exception_notifier/campfire_notifier.rb b/lib/exception_notifier/campfire_notifier.rb index 27b3ccf1..bf7c743f 100644 --- a/lib/exception_notifier/campfire_notifier.rb +++ b/lib/exception_notifier/campfire_notifier.rb @@ -1,6 +1,5 @@ module ExceptionNotifier class CampfireNotifier < BaseNotifier - attr_accessor :subdomain attr_accessor :token attr_accessor :room @@ -12,17 +11,17 @@ def initialize(options) room_name = options.delete(:room_name) @campfire = Tinder::Campfire.new subdomain, options @room = @campfire.find_room_by_name room_name - rescue + rescue StandardError @campfire = @room = nil end end - def call(exception, options={}) + def call(exception, options = {}) if active? message = if options[:accumulated_errors_count].to_i > 1 - "The exception occurred #{options[:accumulated_errors_count]} times: '#{exception.message}'" - else - "A new exception occurred: '#{exception.message}'" + "The exception occurred #{options[:accumulated_errors_count]} times: '#{exception.message}'" + else + "A new exception occurred: '#{exception.message}'" end message += " on '#{exception.backtrace.first}'" if exception.backtrace send_notice(exception, options, message) do |msg, _| diff --git a/lib/exception_notifier/datadog_notifier.rb b/lib/exception_notifier/datadog_notifier.rb index 950a1e55..1697474d 100644 --- a/lib/exception_notifier/datadog_notifier.rb +++ b/lib/exception_notifier/datadog_notifier.rb @@ -1,9 +1,7 @@ module ExceptionNotifier - class DatadogNotifier < BaseNotifier - attr_reader :client, - :default_options + :default_options def initialize(options) super @@ -32,10 +30,10 @@ class DatadogExceptionEvent MAX_TITLE_LENGTH = 120 MAX_VALUE_LENGTH = 300 MAX_BACKTRACE_SIZE = 3 - ALERT_TYPE = "error" + ALERT_TYPE = 'error'.freeze attr_reader :exception, - :options + :options def initialize(exception, options) @exception = exception @@ -59,7 +57,7 @@ def tags end def title_prefix - options[:title_prefix] || "" + options[:title_prefix] || '' end def event @@ -88,11 +86,11 @@ def formatted_title def formatted_body text = [] - text << "%%%" + text << '%%%' text << formatted_request if request text << formatted_session if request text << formatted_backtrace - text << "%%%" + text << '%%%' text.join("\n") end @@ -103,26 +101,26 @@ def formatted_key_value(key, value) def formatted_request text = [] - text << "### **Request**" - text << formatted_key_value("URL", request.url) - text << formatted_key_value("HTTP Method", request.request_method) - text << formatted_key_value("IP Address", request.remote_ip) - text << formatted_key_value("Parameters", request.filtered_parameters.inspect) - text << formatted_key_value("Timestamp", Time.current) - text << formatted_key_value("Server", Socket.gethostname) + text << '### **Request**' + text << formatted_key_value('URL', request.url) + text << formatted_key_value('HTTP Method', request.request_method) + text << formatted_key_value('IP Address', request.remote_ip) + text << formatted_key_value('Parameters', request.filtered_parameters.inspect) + text << formatted_key_value('Timestamp', Time.current) + text << formatted_key_value('Server', Socket.gethostname) if defined?(Rails) && Rails.respond_to?(:root) - text << formatted_key_value("Rails root", Rails.root) + text << formatted_key_value('Rails root', Rails.root) end - text << formatted_key_value("Process", $$) - text << "___" + text << formatted_key_value('Process', $PROCESS_ID) + text << '___' text.join("\n") end def formatted_session text = [] - text << "### **Session**" - text << formatted_key_value("Data", request.session.to_hash) - text << "___" + text << '### **Session**' + text << formatted_key_value('Data', request.session.to_hash) + text << '___' text.join("\n") end @@ -130,11 +128,11 @@ def formatted_backtrace size = [backtrace.size, MAX_BACKTRACE_SIZE].min text = [] - text << "### **Backtrace**" - text << "````" + text << '### **Backtrace**' + text << '````' size.times { |i| text << backtrace[i] } - text << "````" - text << "___" + text << '````' + text << '___' text.join("\n") end @@ -144,15 +142,12 @@ def truncate(string, max) def inspect_object(object) case object - when Hash, Array - truncate(object.inspect, MAX_VALUE_LENGTH) - else - object.to_s + when Hash, Array + truncate(object.inspect, MAX_VALUE_LENGTH) + else + object.to_s end end - end end - end - diff --git a/lib/exception_notifier/email_notifier.rb b/lib/exception_notifier/email_notifier.rb index 00f405a5..c4eaeac3 100644 --- a/lib/exception_notifier/email_notifier.rb +++ b/lib/exception_notifier/email_notifier.rb @@ -1,4 +1,4 @@ -require "active_support/core_ext/hash/reverse_merge" +require 'active_support/core_ext/hash/reverse_merge' require 'active_support/core_ext/time' require 'action_mailer' require 'action_dispatch' @@ -7,25 +7,24 @@ module ExceptionNotifier class EmailNotifier < BaseNotifier attr_accessor(:sender_address, :exception_recipients, - :pre_callback, :post_callback, - :email_prefix, :email_format, :sections, :background_sections, - :verbose_subject, :normalize_subject, :include_controller_and_action_names_in_subject, - :delivery_method, :mailer_settings, :email_headers, :mailer_parent, :template_path, :deliver_with) + :pre_callback, :post_callback, + :email_prefix, :email_format, :sections, :background_sections, + :verbose_subject, :normalize_subject, :include_controller_and_action_names_in_subject, + :delivery_method, :mailer_settings, :email_headers, :mailer_parent, :template_path, :deliver_with) module Mailer class MissingController - def method_missing(*args, &block) - end + def method_missing(*args, &block); end end def self.extended(base) base.class_eval do - self.send(:include, ExceptionNotifier::BacktraceCleaner) + send(:include, ExceptionNotifier::BacktraceCleaner) # Append application view path to the ExceptionNotifier lookup context. - self.append_view_path "#{File.dirname(__FILE__)}/views" + append_view_path "#{File.dirname(__FILE__)}/views" - def exception_notification(env, exception, options={}, default_options={}) + def exception_notification(env, exception, options = {}, default_options = {}) load_custom_views @env = env @@ -37,12 +36,12 @@ def exception_notification(env, exception, options={}, default_options={}) @timestamp = Time.current @sections = @options[:sections] @data = (env['exception_notifier.exception_data'] || {}).merge(options[:data] || {}) - @sections = @sections + %w(data) unless @data.empty? + @sections += %w[data] unless @data.empty? compose_email end - def background_exception_notification(exception, options={}, default_options={}) + def background_exception_notification(exception, options = {}, default_options = {}) load_custom_views @exception = exception @@ -65,7 +64,7 @@ def compose_subject subject << " (#{@exception.class})" subject << " #{@exception.message.inspect}" if @options[:verbose_subject] subject = EmailNotifier.normalize_digits(subject) if @options[:normalize_subject] - subject.length > 120 ? subject[0...120] + "..." : subject + subject.length > 120 ? subject[0...120] + '...' : subject end def set_data_variables @@ -82,17 +81,17 @@ def truncate(string, max) def inspect_object(object) case object - when Hash, Array - truncate(object.inspect, 300) - else - object.to_s + when Hash, Array + truncate(object.inspect, 300) + else + object.to_s end end helper_method :safe_encode def safe_encode(value) - value.encode("utf-8", invalid: :replace, undef: :replace, replace: "_") + value.encode('utf-8', invalid: :replace, undef: :replace, replace: '_') end def html_mail? @@ -125,7 +124,7 @@ def compose_email def load_custom_views if defined?(Rails) && Rails.respond_to?(:root) - self.prepend_view_path Rails.root.nil? ? "app/views" : "#{Rails.root}/app/views" + prepend_view_path Rails.root.nil? ? 'app/views' : "#{Rails.root}/app/views" end end @@ -142,17 +141,20 @@ def initialize(options) mailer_settings_key = "#{delivery_method}_settings".to_sym options[:mailer_settings] = options.delete(mailer_settings_key) - options.reverse_merge(EmailNotifier.default_options).select{|k,v|[ - :sender_address, :exception_recipients, :pre_callback, - :post_callback, :email_prefix, :email_format, - :sections, :background_sections, :verbose_subject, :normalize_subject, - :include_controller_and_action_names_in_subject, :delivery_method, :mailer_settings, - :email_headers, :mailer_parent, :template_path, :deliver_with].include?(k)}.each{|k,v| send("#{k}=", v)} + options.reverse_merge(EmailNotifier.default_options).select do |k, _v| + %i[ + sender_address exception_recipients pre_callback + post_callback email_prefix email_format + sections background_sections verbose_subject normalize_subject + include_controller_and_action_names_in_subject delivery_method mailer_settings + email_headers mailer_parent template_path deliver_with + ].include?(k) + end .each { |k, v| send("#{k}=", v) } end def options @options ||= {}.tap do |opts| - self.instance_variables.each { |var| opts[var[1..-1].to_sym] = self.instance_variable_get(var) } + instance_variables.each { |var| opts[var[1..-1].to_sym] = instance_variable_get(var) } end end @@ -163,7 +165,7 @@ def mailer end end - def call(exception, options={}) + def call(exception, options = {}) message = create_email(exception, options) # FIXME: use `if Gem::Version.new(ActionMailer::VERSION::STRING) < Gem::Version.new('4.1')` @@ -178,7 +180,7 @@ def call(exception, options={}) end end - def create_email(exception, options={}) + def create_email(exception, options = {}) env = options[:env] default_options = self.options if env.nil? @@ -198,8 +200,8 @@ def self.default_options exception_recipients: [], email_prefix: '[ERROR] ', email_format: :text, - sections: %w(request session environment backtrace), - background_sections: %w(backtrace data), + sections: %w[request session environment backtrace], + background_sections: %w[backtrace data], verbose_subject: true, normalize_subject: false, include_controller_and_action_names_in_subject: true, diff --git a/lib/exception_notifier/google_chat_notifier.rb b/lib/exception_notifier/google_chat_notifier.rb index e8140e3c..6e79d8a3 100644 --- a/lib/exception_notifier/google_chat_notifier.rb +++ b/lib/exception_notifier/google_chat_notifier.rb @@ -24,7 +24,7 @@ def call(exception, opts = {}) def body text = [ header, - "", + '', "⚠️ Error 500 in #{Rails.env} ⚠️", "*#{exception.message.tr('`', "'")}*" ] @@ -46,18 +46,19 @@ def header def message_request return [] unless (env = options[:env]) + request = ActionDispatch::Request.new(env) [ - "", - "*Request:*", - "```", + '', + '*Request:*', + '```', "* url : #{request.original_url}", "* http_method : #{request.method}", "* ip_address : #{request.remote_ip}", "* parameters : #{request.filtered_parameters}", "* timestamp : #{Time.current}", - "```" + '```' ] end @@ -69,16 +70,16 @@ def message_backtrace text = [] text << '' - text << "*Backtrace:*" - text << "```" + text << '*Backtrace:*' + text << '```' backtrace.first(3).each { |line| text << "* #{line}" } - text << "```" + text << '```' text end def app_name - @app_name ||= options[:app_name] || rails_app_name || "N/A" + @app_name ||= options[:app_name] || rails_app_name || 'N/A' end def errors_count diff --git a/lib/exception_notifier/hipchat_notifier.rb b/lib/exception_notifier/hipchat_notifier.rb index 39d4a156..9d851037 100644 --- a/lib/exception_notifier/hipchat_notifier.rb +++ b/lib/exception_notifier/hipchat_notifier.rb @@ -1,6 +1,5 @@ module ExceptionNotifier class HipchatNotifier < BaseNotifier - attr_accessor :from attr_accessor :room attr_accessor :message_options @@ -11,29 +10,29 @@ def initialize(options) api_token = options.delete(:api_token) room_name = options.delete(:room_name) opts = { - api_version: options.delete(:api_version) || 'v1' - } + api_version: options.delete(:api_version) || 'v1' + } opts[:server_url] = options.delete(:server_url) if options[:server_url] @from = options.delete(:from) || 'Exception' @room = HipChat::Client.new(api_token, opts)[room_name] - @message_template = options.delete(:message_template) || ->(exception, errors_count) { + @message_template = options.delete(:message_template) || lambda { |exception, errors_count| msg = if errors_count > 1 - "The exception occurred #{errors_count} times: '#{Rack::Utils.escape_html(exception.message)}'" - else - "A new exception occurred: '#{Rack::Utils.escape_html(exception.message)}'" + "The exception occurred #{errors_count} times: '#{Rack::Utils.escape_html(exception.message)}'" + else + "A new exception occurred: '#{Rack::Utils.escape_html(exception.message)}'" end msg += " on '#{exception.backtrace.first}'" if exception.backtrace msg } - @message_options = options + @message_options = options @message_options[:color] ||= 'red' - rescue + rescue StandardError @room = nil end end - def call(exception, options={}) - return if !active? + def call(exception, options = {}) + return unless active? message = @message_template.call(exception, options[:accumulated_errors_count].to_i) send_notice(exception, options, message, @message_options) do |msg, message_opts| diff --git a/lib/exception_notifier/irc_notifier.rb b/lib/exception_notifier/irc_notifier.rb index 122c22be..990036be 100644 --- a/lib/exception_notifier/irc_notifier.rb +++ b/lib/exception_notifier/irc_notifier.rb @@ -6,7 +6,7 @@ def initialize(options) parse_options(options) end - def call(exception, options={}) + def call(exception, options = {}) errors_count = options[:accumulated_errors_count].to_i message = "'#{exception.message}'" @@ -21,35 +21,36 @@ def call(exception, options={}) end def send_message(message) - CarrierPigeon.send @config.irc.merge({message: message}) + CarrierPigeon.send @config.irc.merge(message: message) end private - def parse_options(options) - nick = options.fetch(:nick, 'ExceptionNotifierBot') - password = options[:password] ? ":#{options[:password]}" : nil - domain = options.fetch(:domain, nil) - port = options[:port] ? ":#{options[:port]}" : nil - channel = options.fetch(:channel, '#log') - notice = options.fetch(:notice, false) - ssl = options.fetch(:ssl, false) - join = options.fetch(:join, false) - uri = "irc://#{nick}#{password}@#{domain}#{port}/#{channel}" - prefix = options.fetch(:prefix, nil) - recipients = options[:recipients] ? options[:recipients].join(', ') + ':' : nil - - @config.prefix = [*prefix, *recipients].join(' ') - @config.irc = { uri: uri, ssl: ssl, notice: notice, join: join } - end - def active? - valid_uri? @config.irc[:uri] - end + def parse_options(options) + nick = options.fetch(:nick, 'ExceptionNotifierBot') + password = options[:password] ? ":#{options[:password]}" : nil + domain = options.fetch(:domain, nil) + port = options[:port] ? ":#{options[:port]}" : nil + channel = options.fetch(:channel, '#log') + notice = options.fetch(:notice, false) + ssl = options.fetch(:ssl, false) + join = options.fetch(:join, false) + uri = "irc://#{nick}#{password}@#{domain}#{port}/#{channel}" + prefix = options.fetch(:prefix, nil) + recipients = options[:recipients] ? options[:recipients].join(', ') + ':' : nil + + @config.prefix = [*prefix, *recipients].join(' ') + @config.irc = { uri: uri, ssl: ssl, notice: notice, join: join } + end - def valid_uri?(uri) - !!URI.parse(uri) - rescue URI::InvalidURIError - false - end + def active? + valid_uri? @config.irc[:uri] + end + + def valid_uri?(uri) + !!URI.parse(uri) + rescue URI::InvalidURIError + false + end end end diff --git a/lib/exception_notifier/mattermost_notifier.rb b/lib/exception_notifier/mattermost_notifier.rb index c8c85fe6..827b53b9 100644 --- a/lib/exception_notifier/mattermost_notifier.rb +++ b/lib/exception_notifier/mattermost_notifier.rb @@ -6,8 +6,7 @@ class MattermostNotifier include ExceptionNotifier::BacktraceCleaner class MissingController - def method_missing(*args, &block) - end + def method_missing(*args, &block); end end attr_accessor :httparty @@ -27,14 +26,16 @@ def call(exception, options = {}) @application_name = @options.delete(:app_name) || Rails.application.class.parent_name.underscore @gitlab_url = @options.delete(:git_url) - @username = @options.delete(:username) || "Exception Notifier" + @username = @options.delete(:username) || 'Exception Notifier' @avatar = @options.delete(:avatar) @channel = @options.delete(:channel) @webhook_url = @options.delete(:webhook_url) - raise ArgumentError.new "You must provide 'webhook_url' parameter." unless @webhook_url + raise ArgumentError, "You must provide 'webhook_url' parameter." unless @webhook_url - unless @env.nil? + if @env.nil? + @controller = @request_items = nil + else @controller = @env['action_controller.instance'] || MissingController.new request = ActionDispatch::Request.new(@env) @@ -45,121 +46,118 @@ def call(exception, options = {}) parameters: request.filtered_parameters, timestamp: Time.current } - if request.session["warden.user.user.key"] - current_user = User.find(request.session["warden.user.user.key"][0][0]) - @request_items.merge!({ current_user: { id: current_user.id, email: current_user.email } }) + if request.session['warden.user.user.key'] + current_user = User.find(request.session['warden.user.user.key'][0][0]) + @request_items[:current_user] = { id: current_user.id, email: current_user.email } end - else - @controller = @request_items = nil end payload = message_text.merge(user_info).merge(channel_info) @options[:body] = payload.to_json @options[:headers] ||= {} - @options[:headers].merge!({ 'Content-Type' => 'application/json' }) + @options[:headers]['Content-Type'] = 'application/json' @httparty.post(@webhook_url, @options) end private - def channel_info - if @channel - { channel: @channel } - else - {} - end + def channel_info + if @channel + { channel: @channel } + else + {} end + end - def user_info - infos = {} + def user_info + infos = {} - infos.merge!({ username: @username }) if @username - infos.merge!({ icon_url: @avatar }) if @avatar + infos[:username] = @username if @username + infos[:icon_url] = @avatar if @avatar - infos - end + infos + end - def message_text - text = [] + def message_text + text = [] - text += ["@channel"] - text += message_header - text += message_request if @request_items - text += message_backtrace if @backtrace - text += message_issue_link if @gitlab_url + text += ['@channel'] + text += message_header + text += message_request if @request_items + text += message_backtrace if @backtrace + text += message_issue_link if @gitlab_url - { text: text.join("\n") } - end + { text: text.join("\n") } + end - def message_header - text = [] + def message_header + text = [] - errors_count = @options[:accumulated_errors_count].to_i - text << "### :warning: Error 500 in #{Rails.env} :warning:" - text << "#{errors_count > 1 ? errors_count : 'An'} *#{@exception.class}* occured" + if @controller then " in *#{controller_and_method}*." else "." end - text << "*#{@exception.message}*" + errors_count = @options[:accumulated_errors_count].to_i + text << "### :warning: Error 500 in #{Rails.env} :warning:" + text << "#{errors_count > 1 ? errors_count : 'An'} *#{@exception.class}* occured" + (@controller ? " in *#{controller_and_method}*." : '.') + text << "*#{@exception.message}*" - text - end + text + end - def message_request - text = [] + def message_request + text = [] - text << "### Request" - text << "```" - text << hash_presentation(@request_items) - text << "```" + text << '### Request' + text << '```' + text << hash_presentation(@request_items) + text << '```' - text - end + text + end - def message_backtrace(size = 3) - text = [] + def message_backtrace(size = 3) + text = [] - size = @backtrace.size < size ? @backtrace.size : size - text << "### Backtrace" - text << "```" - size.times { |i| text << "* " + @backtrace[i] } - text << "```" + size = @backtrace.size < size ? @backtrace.size : size + text << '### Backtrace' + text << '```' + size.times { |i| text << '* ' + @backtrace[i] } + text << '```' - text - end + text + end - def message_issue_link - text = [] + def message_issue_link + text = [] - link = [@gitlab_url, @application_name, "issues", "new"].join("/") - params = { - "issue[title]" => ["[BUG] Error 500 :", - controller_and_method, - "(#{@exception.class})", - @exception.message].compact.join(" ") - }.to_query + link = [@gitlab_url, @application_name, 'issues', 'new'].join('/') + params = { + 'issue[title]' => ['[BUG] Error 500 :', + controller_and_method, + "(#{@exception.class})", + @exception.message].compact.join(' ') + }.to_query - text << "[Create an issue](#{link}/?#{params})" + text << "[Create an issue](#{link}/?#{params})" - text - end + text + end - def controller_and_method - if @controller - "#{@controller.controller_name}##{@controller.action_name}" - else - "" - end + def controller_and_method + if @controller + "#{@controller.controller_name}##{@controller.action_name}" + else + '' end + end - def hash_presentation(hash) - text = [] - - hash.each do |key, value| - text << "* #{key} : #{value}" - end + def hash_presentation(hash) + text = [] - text.join("\n") + hash.each do |key, value| + text << "* #{key} : #{value}" end + text.join("\n") + end end end diff --git a/lib/exception_notifier/modules/error_grouping.rb b/lib/exception_notifier/modules/error_grouping.rb index 6eacacfd..4f6c2cc2 100644 --- a/lib/exception_notifier/modules/error_grouping.rb +++ b/lib/exception_notifier/modules/error_grouping.rb @@ -27,7 +27,7 @@ def fallback_cache_store def error_count(error_key) count = begin error_grouping_cache.read(error_key) - rescue => e + rescue StandardError => e ExceptionNotifier.logger.warn("#{error_grouping_cache.inspect} failed to read, reason: #{e.message}. Falling back to memory cache store.") fallback_cache_store.read(error_key) end @@ -37,7 +37,7 @@ def error_count(error_key) def save_error_count(error_key, count) error_grouping_cache.write(error_key, count, expires_in: error_grouping_period) - rescue => e + rescue StandardError => e ExceptionNotifier.logger.warn("#{error_grouping_cache.inspect} failed to write, reason: #{e.message}. Falling back to memory cache store.") fallback_cache_store.write(error_key, count, expires_in: error_grouping_period) end @@ -74,4 +74,4 @@ def send_notification?(exception, count) end end end -end \ No newline at end of file +end diff --git a/lib/exception_notifier/notifier.rb b/lib/exception_notifier/notifier.rb index e689c7e2..6ac829fa 100644 --- a/lib/exception_notifier/notifier.rb +++ b/lib/exception_notifier/notifier.rb @@ -2,14 +2,13 @@ module ExceptionNotifier class Notifier - - def self.exception_notification(env, exception, options={}) - ActiveSupport::Deprecation.warn "Please use ExceptionNotifier.notify_exception(exception, options.merge(env: env))." + def self.exception_notification(env, exception, options = {}) + ActiveSupport::Deprecation.warn 'Please use ExceptionNotifier.notify_exception(exception, options.merge(env: env)).' ExceptionNotifier.registered_exception_notifier(:email).create_email(exception, options.merge(env: env)) end - def self.background_exception_notification(exception, options={}) - ActiveSupport::Deprecation.warn "Please use ExceptionNotifier.notify_exception(exception, options)." + def self.background_exception_notification(exception, options = {}) + ActiveSupport::Deprecation.warn 'Please use ExceptionNotifier.notify_exception(exception, options).' ExceptionNotifier.registered_exception_notifier(:email).create_email(exception, options) end end diff --git a/lib/exception_notifier/slack_notifier.rb b/lib/exception_notifier/slack_notifier.rb index f3fbeefa..8202ef52 100644 --- a/lib/exception_notifier/slack_notifier.rb +++ b/lib/exception_notifier/slack_notifier.rb @@ -15,7 +15,7 @@ def initialize(options) @message_opts = options.fetch(:additional_parameters, {}) @color = @message_opts.delete(:color) { 'danger' } @notifier = Slack::Notifier.new webhook_url, options - rescue + rescue StandardError @notifier = nil end end @@ -40,13 +40,9 @@ def valid? def deep_reject(hash, block) hash.each do |k, v| - if v.is_a?(Hash) - deep_reject(v, block) - end + deep_reject(v, block) if v.is_a?(Hash) - if block.call(k, v) - hash.delete(k) - end + hash.delete(k) if block.call(k, v) end end diff --git a/lib/exception_notifier/sns_notifier.rb b/lib/exception_notifier/sns_notifier.rb index 72b98edb..b1d67332 100644 --- a/lib/exception_notifier/sns_notifier.rb +++ b/lib/exception_notifier/sns_notifier.rb @@ -3,9 +3,9 @@ class SnsNotifier < BaseNotifier def initialize(options) super - raise ArgumentError.new "You must provide 'region' option" unless options[:region] - raise ArgumentError.new "You must provide 'access_key_id' option" unless options[:access_key_id] - raise ArgumentError.new "You must provide 'secret_access_key' option" unless options[:secret_access_key] + raise ArgumentError, "You must provide 'region' option" unless options[:region] + raise ArgumentError, "You must provide 'access_key_id' option" unless options[:access_key_id] + raise ArgumentError, "You must provide 'secret_access_key' option" unless options[:secret_access_key] @notifier = Aws::SNS::Client.new( region: options[:region], @@ -35,8 +35,8 @@ def call(exception, custom_opts = {}) def build_subject(exception, options) subject = "#{options[:sns_prefix]} - " subject << accumulated_exception_name(exception, options) - subject << " occurred" - subject.length > 120 ? subject[0...120] + "..." : subject + subject << ' occurred' + subject.length > 120 ? subject[0...120] + '...' : subject end def build_message(exception, options) @@ -58,7 +58,7 @@ def build_message(exception, options) text += "Hostname: #{Socket.gethostname}\n" if exception.backtrace - formatted_backtrace = "#{exception.backtrace.first(options[:backtrace_lines]).join("\n")}" + formatted_backtrace = exception.backtrace.first(options[:backtrace_lines]).join("\n").to_s text += "Backtrace:\n#{formatted_backtrace}\n" end end @@ -66,7 +66,7 @@ def build_message(exception, options) def accumulated_exception_name(exception, options) errors_count = options[:accumulated_errors_count].to_i measure_word = errors_count > 1 ? errors_count : (exception.class.to_s =~ /^[aeiou]/i ? 'An' : 'A') - "#{measure_word} #{exception.class.to_s}" + "#{measure_word} #{exception.class}" end def default_options diff --git a/lib/exception_notifier/teams_notifier.rb b/lib/exception_notifier/teams_notifier.rb index c2f639a8..d419f924 100644 --- a/lib/exception_notifier/teams_notifier.rb +++ b/lib/exception_notifier/teams_notifier.rb @@ -6,8 +6,7 @@ class TeamsNotifier < BaseNotifier include ExceptionNotifier::BacktraceCleaner class MissingController - def method_missing(*args, &block) - end + def method_missing(*args, &block); end end attr_accessor :httparty @@ -18,7 +17,7 @@ def initialize(options = {}) @httparty = HTTParty end - def call(exception, options={}) + def call(exception, options = {}) @options = options.merge(@default_options) @exception = exception @backtrace = exception.backtrace ? clean_backtrace(exception) : nil @@ -30,9 +29,11 @@ def call(exception, options={}) @jira_url = @options.delete(:jira_url) @webhook_url = @options.delete(:webhook_url) - raise ArgumentError.new "You must provide 'webhook_url' parameter." unless @webhook_url + raise ArgumentError, "You must provide 'webhook_url' parameter." unless @webhook_url - unless @env.nil? + if @env.nil? + @controller = @request_items = nil + else @controller = @env['action_controller.instance'] || MissingController.new request = ActionDispatch::Request.new(@env) @@ -43,19 +44,17 @@ def call(exception, options={}) parameters: request.filtered_parameters, timestamp: Time.current } - if request.session["warden.user.user.key"] - current_user = User.find(request.session["warden.user.user.key"][0][0]) - @request_items.merge!({ current_user: { id: current_user.id, email: current_user.email } }) + if request.session['warden.user.user.key'] + current_user = User.find(request.session['warden.user.user.key'][0][0]) + @request_items[:current_user] = { id: current_user.id, email: current_user.email } end - else - @controller = @request_items = nil end payload = message_text @options[:body] = payload.to_json @options[:headers] ||= {} - @options[:headers].merge!({ 'Content-Type' => 'application/json' }) + @options[:headers]['Content-Type'] = 'application/json' @options[:debug_output] = $stdout @httparty.post(@webhook_url, @options) @@ -67,17 +66,17 @@ def message_text errors_count = @options[:accumulated_errors_count].to_i text = { - "@type" => "MessageCard", - "@context" => "http://schema.org/extensions", - "summary" => "#{@application_name} Exception Alert", - "title" => "⚠️ Exception Occurred in #{Rails.env} ⚠️", - "sections" => [ + '@type' => 'MessageCard', + '@context' => 'http://schema.org/extensions', + 'summary' => "#{@application_name} Exception Alert", + 'title' => "⚠️ Exception Occurred in #{Rails.env} ⚠️", + 'sections' => [ { - "activityTitle" => "#{errors_count > 1 ? errors_count : 'A'} *#{@exception.class}* occurred" + if @controller then " in *#{controller_and_method}*." else "." end, - "activitySubtitle" => "#{@exception.message}" + 'activityTitle' => "#{errors_count > 1 ? errors_count : 'A'} *#{@exception.class}* occurred" + (@controller ? " in *#{controller_and_method}*." : '.'), + 'activitySubtitle' => @exception.message.to_s } ], - "potentialAction" => [] + 'potentialAction' => [] } text['sections'].push details @@ -90,8 +89,8 @@ def message_text def details details = { - "title" => "Details", - "facts" => [] + 'title' => 'Details', + 'facts' => [] } details['facts'].push message_request unless @request_items.nil? @@ -102,59 +101,59 @@ def details def message_request { - "name" => "Request", - "value" => "#{hash_presentation(@request_items)}\n " + 'name' => 'Request', + 'value' => "#{hash_presentation(@request_items)}\n " } end def message_backtrace(size = 3) text = [] size = @backtrace.size < size ? @backtrace.size : size - text << "```" - size.times { |i| text << "* " + @backtrace[i] } - text << "```" + text << '```' + size.times { |i| text << '* ' + @backtrace[i] } + text << '```' { - "name" => "Backtrace", - "value" => "#{text.join(" \n")}" + 'name' => 'Backtrace', + 'value' => text.join(" \n").to_s } end def gitlab_view_link { - "@type" => "ViewAction", - "name" => "🦊 View in GitLab", - "target" => [ + '@type' => 'ViewAction', + 'name' => "\u{1F98A} View in GitLab", + 'target' => [ "#{@gitlab_url}/#{@application_name}" ] } end def gitlab_issue_link - link = [@gitlab_url, @application_name, "issues", "new"].join("/") + link = [@gitlab_url, @application_name, 'issues', 'new'].join('/') params = { - "issue[title]" => ["[BUG] Error 500 :", + 'issue[title]' => ['[BUG] Error 500 :', controller_and_method, "(#{@exception.class})", - @exception.message].compact.join(" ") + @exception.message].compact.join(' ') }.to_query { - "@type" => "ViewAction", - "name" => "🦊 Create Issue in GitLab", - "target" => [ + '@type' => 'ViewAction', + 'name' => "\u{1F98A} Create Issue in GitLab", + 'target' => [ "#{link}/?#{params}" - ] + ] } end def jira_issue_link { - "@type" => "ViewAction", - "name" => "🐞 Create Issue in Jira", - "target" => [ + '@type' => 'ViewAction', + 'name' => '🐞 Create Issue in Jira', + 'target' => [ "#{@jira_url}/secure/CreateIssue!default.jspa" - ] + ] } end @@ -162,7 +161,7 @@ def controller_and_method if @controller "#{@controller.controller_name}##{@controller.action_name}" else - "" + '' end end diff --git a/lib/exception_notifier/webhook_notifier.rb b/lib/exception_notifier/webhook_notifier.rb index b1751a45..76e949b7 100644 --- a/lib/exception_notifier/webhook_notifier.rb +++ b/lib/exception_notifier/webhook_notifier.rb @@ -3,13 +3,12 @@ module ExceptionNotifier class WebhookNotifier < BaseNotifier - def initialize(options) super @default_options = options end - def call(exception, options={}) + def call(exception, options = {}) env = options[:env] options = options.reverse_merge(@default_options) @@ -18,7 +17,7 @@ def call(exception, options={}) options[:body] ||= {} options[:body][:server] = Socket.gethostname - options[:body][:process] = $$ + options[:body][:process] = $PROCESS_ID if defined?(Rails) && Rails.respond_to?(:root) options[:body][:rails_root] = Rails.root end diff --git a/lib/generators/exception_notification/install_generator.rb b/lib/generators/exception_notification/install_generator.rb index 9193c773..d4f78b38 100644 --- a/lib/generators/exception_notification/install_generator.rb +++ b/lib/generators/exception_notification/install_generator.rb @@ -3,7 +3,7 @@ module Generators class InstallGenerator < Rails::Generators::Base desc 'Creates a ExceptionNotification initializer.' - source_root File.expand_path('../templates', __FILE__) + source_root File.expand_path('templates', __dir__) class_option :resque, type: :boolean, desc: 'Add support for sending notifications when errors occur in Resque jobs.' class_option :sidekiq, type: :boolean, desc: 'Add support for sending notifications when errors occur in Sidekiq jobs.' diff --git a/test/dummy/Rakefile b/test/dummy/Rakefile index 9724472e..20ddc49e 100644 --- a/test/dummy/Rakefile +++ b/test/dummy/Rakefile @@ -1,7 +1,7 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('../config/application', __FILE__) +require File.expand_path('config/application', __dir__) require 'rake' Dummy::Application.load_tasks diff --git a/test/dummy/config.ru b/test/dummy/config.ru index 1989ed8d..cbd74159 100644 --- a/test/dummy/config.ru +++ b/test/dummy/config.ru @@ -1,4 +1,4 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) run Dummy::Application diff --git a/test/dummy/config/application.rb b/test/dummy/config/application.rb index a766c4db..16768057 100644 --- a/test/dummy/config/application.rb +++ b/test/dummy/config/application.rb @@ -1,4 +1,4 @@ -require File.expand_path('../boot', __FILE__) +require File.expand_path('boot', __dir__) require 'rails/all' @@ -34,12 +34,12 @@ class Application < Rails::Application # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) # Configure the default encoding used in templates for Ruby 1.9. - config.encoding = "utf-8" + config.encoding = 'utf-8' # Configure sensitive parameters which will be filtered from the log file. - config.filter_parameters += [:password, :secret] + config.filter_parameters += %i[password secret] rails_version = Gem::Version.new(Rails.version) - config.active_record.sqlite3.represent_boolean_as_integer = true if rails_version >= Gem::Version.new("5.2.0") + config.active_record.sqlite3.represent_boolean_as_integer = true if rails_version >= Gem::Version.new('5.2.0') end end diff --git a/test/dummy/config/boot.rb b/test/dummy/config/boot.rb index f2830ae3..24efefdb 100644 --- a/test/dummy/config/boot.rb +++ b/test/dummy/config/boot.rb @@ -1,6 +1,6 @@ require 'rubygems' # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) diff --git a/test/dummy/config/environment.rb b/test/dummy/config/environment.rb index f85d3cde..00d98427 100644 --- a/test/dummy/config/environment.rb +++ b/test/dummy/config/environment.rb @@ -1,16 +1,16 @@ # Load the rails application -require File.expand_path('../application', __FILE__) +require File.expand_path('application', __dir__) Dummy::Application.config.middleware.use ExceptionNotification::Rack, email: { email_prefix: '[Dummy ERROR] ', - sender_address: %{"Dummy Notifier" }, - exception_recipients: %w{dummyexceptions@example.com}, + sender_address: %("Dummy Notifier" ), + exception_recipients: %w[dummyexceptions@example.com], email_headers: { 'X-Custom-Header' => 'foobar' }, - sections: ['new_section', 'request', 'session', 'environment', 'backtrace'], - background_sections: %w(new_bkg_section backtrace data), - pre_callback: proc { |opts, notifier, backtrace, message, message_opts| message_opts[:pre_callback_called] = 1 }, - post_callback: proc { |opts, notifier, backtrace, message, message_opts| message_opts[:post_callback_called] = 1 } + sections: %w[new_section request session environment backtrace], + background_sections: %w[new_bkg_section backtrace data], + pre_callback: proc { |_opts, _notifier, _backtrace, _message, message_opts| message_opts[:pre_callback_called] = 1 }, + post_callback: proc { |_opts, _notifier, _backtrace, _message, message_opts| message_opts[:post_callback_called] = 1 } } # Initialize the rails application diff --git a/test/dummy/config/environments/production.rb b/test/dummy/config/environments/production.rb index e758d3d0..d276322f 100644 --- a/test/dummy/config/environments/production.rb +++ b/test/dummy/config/environments/production.rb @@ -11,7 +11,7 @@ config.action_controller.perform_caching = true # Specifies the header that your server uses for sending files - config.action_dispatch.x_sendfile_header = "X-Sendfile" + config.action_dispatch.x_sendfile_header = 'X-Sendfile' # For nginx: # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' diff --git a/test/dummy/config/environments/test.rb b/test/dummy/config/environments/test.rb index 40fe27d5..822f64a8 100644 --- a/test/dummy/config/environments/test.rb +++ b/test/dummy/config/environments/test.rb @@ -16,7 +16,7 @@ config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment - config.action_controller.allow_forgery_protection = false + config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the diff --git a/test/dummy/config/routes.rb b/test/dummy/config/routes.rb index 98630068..0ba13a15 100644 --- a/test/dummy/config/routes.rb +++ b/test/dummy/config/routes.rb @@ -1,3 +1,3 @@ Dummy::Application.routes.draw do - resources :posts, only: [:create, :show] + resources :posts, only: %i[create show] end diff --git a/test/dummy/db/schema.rb b/test/dummy/db/schema.rb index d4de93a0..da892226 100644 --- a/test/dummy/db/schema.rb +++ b/test/dummy/db/schema.rb @@ -1,4 +1,3 @@ -# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. @@ -11,14 +10,12 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20110729022608) do - - create_table "posts", force: true do |t| - t.string "title" - t.text "body" - t.string "secret" - t.datetime "created_at" - t.datetime "updated_at" +ActiveRecord::Schema.define(version: 20_110_729_022_608) do + create_table 'posts', force: true do |t| + t.string 'title' + t.text 'body' + t.string 'secret' + t.datetime 'created_at' + t.datetime 'updated_at' end - end diff --git a/test/dummy/script/rails b/test/dummy/script/rails index f8da2cff..3c234a25 100755 --- a/test/dummy/script/rails +++ b/test/dummy/script/rails @@ -1,6 +1,6 @@ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. -APP_PATH = File.expand_path('../../config/application', __FILE__) -require File.expand_path('../../config/boot', __FILE__) +APP_PATH = File.expand_path('../config/application', __dir__) +require File.expand_path('../config/boot', __dir__) require 'rails/commands' diff --git a/test/dummy/test/functional/posts_controller_test.rb b/test/dummy/test/functional/posts_controller_test.rb index 031ab4bf..5ba75eb9 100644 --- a/test/dummy/test/functional/posts_controller_test.rb +++ b/test/dummy/test/functional/posts_controller_test.rb @@ -5,125 +5,125 @@ class PostsControllerTest < ActionController::TestCase Time.stubs(:current).returns('Sat, 20 Apr 2013 20:58:55 UTC +00:00') @email_notifier = ExceptionNotifier.registered_exception_notifier(:email) begin - post :create, method: :post, params: { secret: "secret" } - rescue => e + post :create, method: :post, params: { secret: 'secret' } + rescue StandardError => e @exception = e - @mail = @email_notifier.create_email(@exception, { env: request.env, data: { message: 'My Custom Message' }}) + @mail = @email_notifier.create_email(@exception, env: request.env, data: { message: 'My Custom Message' }) end end - test "should have raised an exception" do + test 'should have raised an exception' do refute_nil @exception end - test "should have generated a notification email" do + test 'should have generated a notification email' do refute_nil @mail end - test "mail should be plain text and UTF-8 enconded by default" do - assert_equal @mail.content_type, "text/plain; charset=UTF-8" + test 'mail should be plain text and UTF-8 enconded by default' do + assert_equal @mail.content_type, 'text/plain; charset=UTF-8' end - test "mail should have a from address set" do - assert_equal @mail.from, ["dummynotifier@example.com"] + test 'mail should have a from address set' do + assert_equal @mail.from, ['dummynotifier@example.com'] end - test "mail should have a to address set" do - assert_equal @mail.to, ["dummyexceptions@example.com"] + test 'mail should have a to address set' do + assert_equal @mail.to, ['dummyexceptions@example.com'] end - test "mail subject should have the proper prefix" do - assert_includes @mail.subject, "[Dummy ERROR]" + test 'mail subject should have the proper prefix' do + assert_includes @mail.subject, '[Dummy ERROR]' end - test "mail subject should include descriptive error message" do + test 'mail subject should include descriptive error message' do assert_includes @mail.subject, "(NoMethodError) \"undefined method `nw'" end - test "mail should contain backtrace in body" do + test 'mail should contain backtrace in body' do assert_includes @mail.encoded, "`method_missing'\r\n app/controllers/posts_controller.rb:18:in `create'\r\n" end - test "mail should contain timestamp of exception in body" do + test 'mail should contain timestamp of exception in body' do assert_includes @mail.encoded, "Timestamp : #{Time.current}" end - test "mail should contain the newly defined section" do - assert_includes @mail.encoded, "* New text section for testing" + test 'mail should contain the newly defined section' do + assert_includes @mail.encoded, '* New text section for testing' end - test "mail should contain the custom message" do - assert_includes @mail.encoded, "My Custom Message" + test 'mail should contain the custom message' do + assert_includes @mail.encoded, 'My Custom Message' end - test "should filter sensible data" do - assert_includes @mail.encoded, "secret\"=>\"[FILTERED]" + test 'should filter sensible data' do + assert_includes @mail.encoded, 'secret"=>"[FILTERED]' end - test "mail should contain the custom header" do + test 'mail should contain the custom header' do assert_includes @mail.encoded, 'X-Custom-Header: foobar' end - test "mail should not contain any attachments" do + test 'mail should not contain any attachments' do assert_equal @mail.attachments, [] end - test "should not send notification if one of ignored exceptions" do + test 'should not send notification if one of ignored exceptions' do begin get :invalid - rescue => e + rescue StandardError => e @ignored_exception = e unless ExceptionNotifier.ignored_exceptions.include?(@ignored_exception.class.name) - ignored_mail = @email_notifier.create_email(@ignored_exception, { env: request.env }) + ignored_mail = @email_notifier.create_email(@ignored_exception, env: request.env) end end - assert_equal @ignored_exception.class.inspect, "ActionController::UrlGenerationError" + assert_equal @ignored_exception.class.inspect, 'ActionController::UrlGenerationError' assert_nil ignored_mail end - test "should filter session_id on secure requests" do + test 'should filter session_id on secure requests' do request.env['HTTPS'] = 'on' begin post :create, method: :post - rescue => e - @secured_mail = @email_notifier.create_email(e, { env: request.env }) + rescue StandardError => e + @secured_mail = @email_notifier.create_email(e, env: request.env) end assert request.ssl? assert_includes @secured_mail.encoded, "* session id: [FILTERED]\r\n *" end - test "should ignore exception if from unwanted crawler" do - request.env['HTTP_USER_AGENT'] = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" + test 'should ignore exception if from unwanted crawler' do + request.env['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' begin post :create, method: :post - rescue => e + rescue StandardError => e @exception = e custom_env = request.env custom_env['exception_notifier.options'] ||= {} - custom_env['exception_notifier.options'].merge!(ignore_crawlers: %w(Googlebot)) + custom_env['exception_notifier.options'][:ignore_crawlers] = %w[Googlebot] ignore_array = custom_env['exception_notifier.options'][:ignore_crawlers] unless ExceptionNotification::Rack.new(Dummy::Application, custom_env['exception_notifier.options']).send(:from_crawler, custom_env, ignore_array) - ignored_mail = @email_notifier.create_email(@exception, { env: custom_env }) + ignored_mail = @email_notifier.create_email(@exception, env: custom_env) end end assert_nil ignored_mail end - test "should send html email when selected html format" do + test 'should send html email when selected html format' do begin post :create, method: :post - rescue => e + rescue StandardError => e @exception = e custom_env = request.env custom_env['exception_notifier.options'] ||= {} - custom_env['exception_notifier.options'].merge!({ email_format: :html }) - @mail = @email_notifier.create_email(@exception, { env: custom_env }) + custom_env['exception_notifier.options'][:email_format] = :html + @mail = @email_notifier.create_email(@exception, env: custom_env) end - assert_includes @mail.content_type, "multipart/alternative" + assert_includes @mail.content_type, 'multipart/alternative' end end @@ -133,13 +133,13 @@ class PostsControllerTestWithoutVerboseSubject < ActionController::TestCase @email_notifier = ExceptionNotifier::EmailNotifier.new(verbose_subject: false) begin post :create, method: :post - rescue => e + rescue StandardError => e @exception = e - @mail = @email_notifier.create_email(@exception, { env: request.env }) + @mail = @email_notifier.create_email(@exception, env: request.env) end end - test "should not include exception message in subject" do + test 'should not include exception message in subject' do assert_includes @mail.subject, '[ERROR]' assert_includes @mail.subject, '(NoMethodError)' refute_includes @mail.subject, 'undefined method' @@ -152,13 +152,13 @@ class PostsControllerTestWithoutControllerAndActionNames < ActionController::Tes @email_notifier = ExceptionNotifier::EmailNotifier.new(include_controller_and_action_names_in_subject: false) begin post :create, method: :post - rescue => e + rescue StandardError => e @exception = e - @mail = @email_notifier.create_email(@exception, { env: request.env}) + @mail = @email_notifier.create_email(@exception, env: request.env) end end - test "should include controller and action names in subject" do + test 'should include controller and action names in subject' do assert_includes @mail.subject, '[ERROR]' assert_includes @mail.subject, '(NoMethodError)' refute_includes @mail.subject, 'posts#create' @@ -177,21 +177,21 @@ class PostsControllerTestWithSmtpSettings < ActionController::TestCase begin post :create, method: :post - rescue => e + rescue StandardError => e @exception = e - @mail = @email_notifier.create_email(@exception, { env: request.env }) + @mail = @email_notifier.create_email(@exception, env: request.env) end end - test "should have overridden smtp settings" do - assert_equal "Dummy user_name", @mail.delivery_method.settings[:user_name] - assert_equal "Dummy password", @mail.delivery_method.settings[:password] + test 'should have overridden smtp settings' do + assert_equal 'Dummy user_name', @mail.delivery_method.settings[:user_name] + assert_equal 'Dummy password', @mail.delivery_method.settings[:password] end - test "should have overridden smtp settings with background notification" do + test 'should have overridden smtp settings with background notification' do @mail = @email_notifier.create_email(@exception) - assert_equal "Dummy user_name", @mail.delivery_method.settings[:user_name] - assert_equal "Dummy password", @mail.delivery_method.settings[:password] + assert_equal 'Dummy user_name', @mail.delivery_method.settings[:user_name] + assert_equal 'Dummy password', @mail.delivery_method.settings[:password] end end @@ -201,39 +201,39 @@ class PostsControllerTestBackgroundNotification < ActionController::TestCase @email_notifier = ExceptionNotifier.registered_exception_notifier(:email) begin post :create, method: :post - rescue => exception + rescue StandardError => exception @mail = @email_notifier.create_email(exception) end end - test "mail should contain the specified section" do - assert_includes @mail.encoded, "* New background section for testing" + test 'mail should contain the specified section' do + assert_includes @mail.encoded, '* New background section for testing' end end class PostsControllerTestWithExceptionRecipientsAsProc < ActionController::TestCase tests PostsController setup do - exception_recipients = %w{first@example.com second@example.com} + exception_recipients = %w[first@example.com second@example.com] @email_notifier = ExceptionNotifier::EmailNotifier.new( - exception_recipients: -> { [ exception_recipients.shift ] } + exception_recipients: -> { [exception_recipients.shift] } ) @action = proc do begin post :create, method: :post - rescue => e + rescue StandardError => e @exception = e - @mail = @email_notifier.create_email(@exception, { env: request.env }) + @mail = @email_notifier.create_email(@exception, env: request.env) end end end - test "should lazily evaluate exception_recipients" do + test 'should lazily evaluate exception_recipients' do @action.call - assert_equal [ "first@example.com" ], @mail.to + assert_equal ['first@example.com'], @mail.to @action.call - assert_equal [ "second@example.com" ], @mail.to + assert_equal ['second@example.com'], @mail.to end end diff --git a/test/dummy/test/test_helper.rb b/test/dummy/test/test_helper.rb index 82985177..77bc8b9e 100644 --- a/test/dummy/test/test_helper.rb +++ b/test/dummy/test/test_helper.rb @@ -1,5 +1,5 @@ -ENV["RAILS_ENV"] = "test" -require File.expand_path('../../config/environment', __FILE__) +ENV['RAILS_ENV'] = 'test' +require File.expand_path('../config/environment', __dir__) require 'rails/test_help' class ActiveSupport::TestCase diff --git a/test/exception_notification/rack_test.rb b/test/exception_notification/rack_test.rb index 4482ff7a..7c7653c9 100644 --- a/test/exception_notification/rack_test.rb +++ b/test/exception_notification/rack_test.rb @@ -1,13 +1,12 @@ require 'test_helper' class RackTest < ActiveSupport::TestCase - setup do @pass_app = Object.new @pass_app.stubs(:call).returns([nil, { 'X-Cascade' => 'pass' }, nil]) @normal_app = Object.new - @normal_app.stubs(:call).returns([nil, { }, nil]) + @normal_app.stubs(:call).returns([nil, {}, nil]) end teardown do @@ -15,29 +14,29 @@ class RackTest < ActiveSupport::TestCase ExceptionNotifier.notification_trigger = nil end - test "should ignore \"X-Cascade\" header by default" do + test 'should ignore "X-Cascade" header by default' do ExceptionNotifier.expects(:notify_exception).never ExceptionNotification::Rack.new(@pass_app).call({}) end - test "should notify on \"X-Cascade\" = \"pass\" if ignore_cascade_pass option is false" do + test 'should notify on "X-Cascade" = "pass" if ignore_cascade_pass option is false' do ExceptionNotifier.expects(:notify_exception).once ExceptionNotification::Rack.new(@pass_app, ignore_cascade_pass: false).call({}) end - test "should assign error_grouping if error_grouping is specified" do + test 'should assign error_grouping if error_grouping is specified' do refute ExceptionNotifier.error_grouping ExceptionNotification::Rack.new(@normal_app, error_grouping: true).call({}) assert ExceptionNotifier.error_grouping end - test "should assign notification_trigger if notification_trigger is specified" do + test 'should assign notification_trigger if notification_trigger is specified' do assert_nil ExceptionNotifier.notification_trigger - ExceptionNotification::Rack.new(@normal_app, notification_trigger: lambda { |i| true }).call({}) + ExceptionNotification::Rack.new(@normal_app, notification_trigger: ->(_i) { true }).call({}) assert_respond_to ExceptionNotifier.notification_trigger, :call end - test "should set default cache to Rails cache" do + test 'should set default cache to Rails cache' do ExceptionNotification::Rack.new(@normal_app, error_grouping: true).call({}) assert_equal Rails.cache, ExceptionNotifier.error_grouping_cache end diff --git a/test/exception_notifier/campfire_notifier_test.rb b/test/exception_notifier/campfire_notifier_test.rb index 0a2bb646..2594f7cc 100644 --- a/test/exception_notifier/campfire_notifier_test.rb +++ b/test/exception_notifier/campfire_notifier_test.rb @@ -8,43 +8,42 @@ end class CampfireNotifierTest < ActiveSupport::TestCase - - test "should send campfire notification if properly configured" do + test 'should send campfire notification if properly configured' do ExceptionNotifier::CampfireNotifier.stubs(:new).returns(Object.new) - campfire = ExceptionNotifier::CampfireNotifier.new({ subdomain: 'test', token: 'test_token', room_name: 'test_room' }) + campfire = ExceptionNotifier::CampfireNotifier.new(subdomain: 'test', token: 'test_token', room_name: 'test_room') campfire.stubs(:call).returns(fake_notification) notif = campfire.call(fake_exception) assert !notif[:message].empty? assert_equal notif[:message][:type], 'PasteMessage' - assert_includes notif[:message][:body], "A new exception occurred:" - assert_includes notif[:message][:body], "divided by 0" - assert_includes notif[:message][:body], "/exception_notification/test/campfire_test.rb:45" + assert_includes notif[:message][:body], 'A new exception occurred:' + assert_includes notif[:message][:body], 'divided by 0' + assert_includes notif[:message][:body], '/exception_notification/test/campfire_test.rb:45' end - test "should send campfire notification without backtrace info if properly configured" do + test 'should send campfire notification without backtrace info if properly configured' do ExceptionNotifier::CampfireNotifier.stubs(:new).returns(Object.new) - campfire = ExceptionNotifier::CampfireNotifier.new({ subdomain: 'test', token: 'test_token', room_name: 'test_room' }) + campfire = ExceptionNotifier::CampfireNotifier.new(subdomain: 'test', token: 'test_token', room_name: 'test_room') campfire.stubs(:call).returns(fake_notification_without_backtrace) notif = campfire.call(fake_exception_without_backtrace) assert !notif[:message].empty? assert_equal notif[:message][:type], 'PasteMessage' - assert_includes notif[:message][:body], "A new exception occurred:" - assert_includes notif[:message][:body], "my custom error" + assert_includes notif[:message][:body], 'A new exception occurred:' + assert_includes notif[:message][:body], 'my custom error' end - test "should not send campfire notification if badly configured" do + test 'should not send campfire notification if badly configured' do wrong_params = { subdomain: 'test', token: 'bad_token', room_name: 'test_room' } - Tinder::Campfire.stubs(:new).with('test', { token: 'bad_token' }).returns(nil) + Tinder::Campfire.stubs(:new).with('test', token: 'bad_token').returns(nil) campfire = ExceptionNotifier::CampfireNotifier.new(wrong_params) assert_nil campfire.room assert_nil campfire.call(fake_exception) end - test "should not send campfire notification if config attr missing" do - wrong_params = { subdomain: 'test', room_name: 'test_room' } + test 'should not send campfire notification if config attr missing' do + wrong_params = { subdomain: 'test', room_name: 'test_room' } Tinder::Campfire.stubs(:new).with('test', {}).returns(nil) campfire = ExceptionNotifier::CampfireNotifier.new(wrong_params) @@ -52,35 +51,34 @@ class CampfireNotifierTest < ActiveSupport::TestCase assert_nil campfire.call(fake_exception) end - test "should send the new exception message if no :accumulated_errors_count option" do + test 'should send the new exception message if no :accumulated_errors_count option' do campfire = ExceptionNotifier::CampfireNotifier.new({}) campfire.stubs(:active?).returns(true) - campfire.expects(:send_notice).with{ |_, _, message| message.start_with?("A new exception occurred") }.once + campfire.expects(:send_notice).with { |_, _, message| message.start_with?('A new exception occurred') }.once campfire.call(fake_exception) end - test "shoud send the exception message if :accumulated_errors_count option greater than 1" do + test 'shoud send the exception message if :accumulated_errors_count option greater than 1' do campfire = ExceptionNotifier::CampfireNotifier.new({}) campfire.stubs(:active?).returns(true) - campfire.expects(:send_notice).with{ |_, _, message| message.start_with?("The exception occurred 3 times:") }.once + campfire.expects(:send_notice).with { |_, _, message| message.start_with?('The exception occurred 3 times:') }.once campfire.call(fake_exception, accumulated_errors_count: 3) end - test "should call pre/post_callback if specified" do - pre_callback_called, post_callback_called = 0,0 + test 'should call pre/post_callback if specified' do + pre_callback_called = 0 + post_callback_called = 0 Tinder::Campfire.stubs(:new).returns(Object.new) campfire = ExceptionNotifier::CampfireNotifier.new( - { - subdomain: 'test', - token: 'test_token', - room_name: 'test_room', - pre_callback: proc { |opts, notifier, backtrace, message, message_opts| - pre_callback_called += 1 - }, - post_callback: proc { |opts, notifier, backtrace, message, message_opts| - post_callback_called += 1 - } + subdomain: 'test', + token: 'test_token', + room_name: 'test_room', + pre_callback: proc { |_opts, _notifier, _backtrace, _message, _message_opts| + pre_callback_called += 1 + }, + post_callback: proc { |_opts, _notifier, _backtrace, _message, _message_opts| + post_callback_called += 1 } ) campfire.room = Object.new @@ -102,11 +100,9 @@ def fake_notification end def fake_exception - begin - 5/0 - rescue Exception => e - e - end + 5 / 0 + rescue Exception => e + e end def fake_notification_without_backtrace diff --git a/test/exception_notifier/datadog_notifier_test.rb b/test/exception_notifier/datadog_notifier_test.rb index cb920649..78cc7804 100644 --- a/test/exception_notifier/datadog_notifier_test.rb +++ b/test/exception_notifier/datadog_notifier_test.rb @@ -14,7 +14,7 @@ def setup @request = FakeRequest.new end - test "should send an event to datadog" do + test 'should send an event to datadog' do fake_event = Dogapi::Event.any_instance @client.expects(:emit_event).with(fake_event) @@ -22,12 +22,12 @@ def setup @notifier.call(@exception) end - test "should include exception class in event title" do + test 'should include exception class in event title' do event = @notifier.datadog_event(@exception) - assert_includes event.msg_title, "FakeException" + assert_includes event.msg_title, 'FakeException' end - test "should include prefix in event title and not append previous events" do + test 'should include prefix in event title and not append previous events' do options = { client: @client, title_prefix: "prefix" @@ -41,55 +41,53 @@ def setup assert_equal event2.msg_title, "prefix (DatadogNotifierTest::FakeException) \"Fake exception message\"" end - test "should include exception message in event title" do + test 'should include exception message in event title' do event = @notifier.datadog_event(@exception) - assert_includes event.msg_title, "Fake exception message" + assert_includes event.msg_title, 'Fake exception message' end - test "should include controller info in event title if controller information is available" do - event = @notifier.datadog_event(@exception, { - env: { - "action_controller.instance" => @controller, - "REQUEST_METHOD" => "GET", - "rack.input" => "", - } - }) - assert_includes event.msg_title, "Fake controller" - assert_includes event.msg_title, "Fake action" + test 'should include controller info in event title if controller information is available' do + event = @notifier.datadog_event(@exception, + env: { + 'action_controller.instance' => @controller, + 'REQUEST_METHOD' => 'GET', + 'rack.input' => '' + }) + assert_includes event.msg_title, 'Fake controller' + assert_includes event.msg_title, 'Fake action' end - test "should include backtrace info in event body" do + test 'should include backtrace info in event body' do event = @notifier.datadog_event(@exception) assert_includes event.msg_text, "backtrace line 1\nbacktrace line 2\nbacktrace line 3" end - test "should include request info in event body" do + test 'should include request info in event body' do ActionDispatch::Request.stubs(:new).returns(@request) - event = @notifier.datadog_event(@exception, { - env: { - "action_controller.instance" => @controller, - "REQUEST_METHOD" => "GET", - "rack.input" => "", - } - }) - assert_includes event.msg_text, "http://localhost:8080" - assert_includes event.msg_text, "GET" - assert_includes event.msg_text, "127.0.0.1" - assert_includes event.msg_text, "{\"param 1\"=>\"value 1\", \"param 2\"=>\"value 2\"}" + event = @notifier.datadog_event(@exception, + env: { + 'action_controller.instance' => @controller, + 'REQUEST_METHOD' => 'GET', + 'rack.input' => '' + }) + assert_includes event.msg_text, 'http://localhost:8080' + assert_includes event.msg_text, 'GET' + assert_includes event.msg_text, '127.0.0.1' + assert_includes event.msg_text, '{"param 1"=>"value 1", "param 2"=>"value 2"}' end - test "should include tags in event" do + test 'should include tags in event' do options = { client: @client, - tags: ["error", "production"] + tags: %w[error production] } notifier = ExceptionNotifier::DatadogNotifier.new(options) event = notifier.datadog_event(@exception) - assert_equal event.tags, ["error", "production"] + assert_equal event.tags, %w[error production] end - test "should include event title in event aggregation key" do + test 'should include event title in event aggregation key' do event = @notifier.datadog_event(@exception) assert_equal event.aggregation_key, [event.msg_title] end @@ -97,61 +95,59 @@ def setup private class FakeDatadogClient - def emit_event(event) - end + def emit_event(event); end end class FakeController def controller_name - "Fake controller" + 'Fake controller' end def action_name - "Fake action" + 'Fake action' end end class FakeException def backtrace [ - "backtrace line 1", - "backtrace line 2", - "backtrace line 3", - "backtrace line 4", - "backtrace line 5" + 'backtrace line 1', + 'backtrace line 2', + 'backtrace line 3', + 'backtrace line 4', + 'backtrace line 5' ] end def message - "Fake exception message" + 'Fake exception message' end end class FakeRequest def url - "http://localhost:8080" + 'http://localhost:8080' end def request_method - "GET" + 'GET' end def remote_ip - "127.0.0.1" + '127.0.0.1' end def filtered_parameters { - "param 1" => "value 1", - "param 2" => "value 2" + 'param 1' => 'value 1', + 'param 2' => 'value 2' } end def session { - "session_id" => "1234" + 'session_id' => '1234' } end end - end diff --git a/test/exception_notifier/email_notifier_test.rb b/test/exception_notifier/email_notifier_test.rb index 29752eff..c7665e36 100644 --- a/test/exception_notifier/email_notifier_test.rb +++ b/test/exception_notifier/email_notifier_test.rb @@ -6,114 +6,114 @@ class EmailNotifierTest < ActiveSupport::TestCase Time.stubs(:current).returns('Sat, 20 Apr 2013 20:58:55 UTC +00:00') @email_notifier = ExceptionNotifier.registered_exception_notifier(:email) begin - 1/0 - rescue => e + 1 / 0 + rescue StandardError => e @exception = e @mail = @email_notifier.create_email( @exception, - data: { job: 'DivideWorkerJob', payload: '1/0', message: 'My Custom Message'} + data: { job: 'DivideWorkerJob', payload: '1/0', message: 'My Custom Message' } ) end end - test "should call pre/post_callback if specified" do + test 'should call pre/post_callback if specified' do assert_equal @email_notifier.options[:pre_callback_called], 1 assert_equal @email_notifier.options[:post_callback_called], 1 end - test "should have default sender address overridden" do + test 'should have default sender address overridden' do assert_equal @email_notifier.sender_address, %("Dummy Notifier" ) end - test "should have default exception recipients overridden" do - assert_equal @email_notifier.exception_recipients, %w(dummyexceptions@example.com) + test 'should have default exception recipients overridden' do + assert_equal @email_notifier.exception_recipients, %w[dummyexceptions@example.com] end - test "should have default email prefix overridden" do - assert_equal @email_notifier.email_prefix, "[Dummy ERROR] " + test 'should have default email prefix overridden' do + assert_equal @email_notifier.email_prefix, '[Dummy ERROR] ' end - test "should have default email headers overridden" do - assert_equal @email_notifier.email_headers, { "X-Custom-Header" => "foobar"} + test 'should have default email headers overridden' do + assert_equal @email_notifier.email_headers, 'X-Custom-Header' => 'foobar' end - test "should have default sections overridden" do - for section in %w(new_section request session environment backtrace) + test 'should have default sections overridden' do + %w[new_section request session environment backtrace].each do |section| assert_includes @email_notifier.sections, section end end - test "should have default background sections" do - for section in %w(new_bkg_section backtrace data) + test 'should have default background sections' do + %w[new_bkg_section backtrace data].each do |section| assert_includes @email_notifier.background_sections, section end end - test "should have email format by default" do + test 'should have email format by default' do assert_equal @email_notifier.email_format, :text end - test "should have verbose subject by default" do + test 'should have verbose subject by default' do assert @email_notifier.verbose_subject end - test "should have normalize_subject false by default" do + test 'should have normalize_subject false by default' do refute @email_notifier.normalize_subject end - test "should have delivery_method nil by default" do + test 'should have delivery_method nil by default' do assert_nil @email_notifier.delivery_method end - test "should have mailer_settings nil by default" do + test 'should have mailer_settings nil by default' do assert_nil @email_notifier.mailer_settings end - test "should have mailer_parent by default" do + test 'should have mailer_parent by default' do assert_equal @email_notifier.mailer_parent, 'ActionMailer::Base' end - test "should have template_path by default" do + test 'should have template_path by default' do assert_equal @email_notifier.template_path, 'exception_notifier' end - test "should normalize multiple digits into one N" do + test 'should normalize multiple digits into one N' do assert_equal 'N foo N bar N baz N', - ExceptionNotifier::EmailNotifier.normalize_digits('1 foo 12 bar 123 baz 1234') + ExceptionNotifier::EmailNotifier.normalize_digits('1 foo 12 bar 123 baz 1234') end - test "mail should be plain text and UTF-8 enconded by default" do - assert_equal @mail.content_type, "text/plain; charset=UTF-8" + test 'mail should be plain text and UTF-8 enconded by default' do + assert_equal @mail.content_type, 'text/plain; charset=UTF-8' end - test "should have raised an exception" do + test 'should have raised an exception' do refute_nil @exception end - test "should have generated a notification email" do + test 'should have generated a notification email' do refute_nil @mail end - test "mail should have a from address set" do - assert_equal @mail.from, ["dummynotifier@example.com"] + test 'mail should have a from address set' do + assert_equal @mail.from, ['dummynotifier@example.com'] end - test "mail should have a to address set" do - assert_equal @mail.to, ["dummyexceptions@example.com"] + test 'mail should have a to address set' do + assert_equal @mail.to, ['dummyexceptions@example.com'] end - test "mail should have a descriptive subject" do + test 'mail should have a descriptive subject' do assert_match(/^\[Dummy ERROR\]\s+\(ZeroDivisionError\) "divided by 0"$/, @mail.subject) end - test "mail should say exception was raised in background at show timestamp" do + test 'mail should say exception was raised in background at show timestamp' do assert_includes @mail.encoded, "A ZeroDivisionError occurred in background at #{Time.current}" end test "mail should prefix exception class with 'an' instead of 'a' when it starts with a vowel" do begin raise ActiveRecord::RecordNotFound - rescue => e + rescue StandardError => e @vowel_exception = e @vowel_mail = @email_notifier.create_email(@vowel_exception) end @@ -121,48 +121,48 @@ class EmailNotifierTest < ActiveSupport::TestCase assert_includes @vowel_mail.encoded, "An ActiveRecord::RecordNotFound occurred in background at #{Time.current}" end - test "mail should contain backtrace in body" do - assert @mail.encoded.include?("test/exception_notifier/email_notifier_test.rb:9"), "\n#{@mail.inspect}" + test 'mail should contain backtrace in body' do + assert @mail.encoded.include?('test/exception_notifier/email_notifier_test.rb:9'), "\n#{@mail.inspect}" end - test "mail should contain data in body" do + test 'mail should contain data in body' do assert_includes @mail.encoded, '* data:' assert_includes @mail.encoded, ':payload=>"1/0"' assert_includes @mail.encoded, ':job=>"DivideWorkerJob"' - assert_includes @mail.encoded, "My Custom Message" + assert_includes @mail.encoded, 'My Custom Message' end - test "mail should not contain any attachments" do + test 'mail should not contain any attachments' do assert_equal @mail.attachments, [] end - test "should not send notification if one of ignored exceptions" do + test 'should not send notification if one of ignored exceptions' do begin raise ActiveRecord::RecordNotFound - rescue => e + rescue StandardError => e @ignored_exception = e unless ExceptionNotifier.ignored_exceptions.include?(@ignored_exception.class.name) ignored_mail = @email_notifier.create_email(@ignored_exception) end end - assert_equal @ignored_exception.class.inspect, "ActiveRecord::RecordNotFound" + assert_equal @ignored_exception.class.inspect, 'ActiveRecord::RecordNotFound' assert_nil ignored_mail end - test "should encode environment strings" do + test 'should encode environment strings' do email_notifier = ExceptionNotifier::EmailNotifier.new( - sender_address: "", - exception_recipients: %w{dummyexceptions@example.com}, + sender_address: '', + exception_recipients: %w[dummyexceptions@example.com], deliver_with: :deliver_now ) mail = email_notifier.create_email( @exception, env: { - "REQUEST_METHOD" => "GET", - "rack.input" => "", - "invalid_encoding" => "R\xC3\xA9sum\xC3\xA9".force_encoding(Encoding::ASCII), + 'REQUEST_METHOD' => 'GET', + 'rack.input' => '', + 'invalid_encoding' => "R\xC3\xA9sum\xC3\xA9".force_encoding(Encoding::ASCII) }, email_format: :text ) @@ -170,13 +170,13 @@ class EmailNotifierTest < ActiveSupport::TestCase assert_match(/invalid_encoding\s+: R__sum__/, mail.encoded) end - test "should send email using ActionMailer" do + test 'should send email using ActionMailer' do ActionMailer::Base.deliveries.clear email_notifier = ExceptionNotifier::EmailNotifier.new( email_prefix: '[Dummy ERROR] ', - sender_address: %{"Dummy Notifier" }, - exception_recipients: %w{dummyexceptions@example.com}, + sender_address: %("Dummy Notifier" ), + exception_recipients: %w[dummyexceptions@example.com], delivery_method: :test ) @@ -185,19 +185,19 @@ class EmailNotifierTest < ActiveSupport::TestCase assert_equal 1, ActionMailer::Base.deliveries.count end - test "should be able to specify ActionMailer::MessageDelivery method" do + test 'should be able to specify ActionMailer::MessageDelivery method' do ActionMailer::Base.deliveries.clear - if ActionMailer.version < Gem::Version.new("4.2") - deliver_with = :deliver - else - deliver_with = :deliver_now - end + deliver_with = if ActionMailer.version < Gem::Version.new('4.2') + :deliver + else + :deliver_now + end email_notifier = ExceptionNotifier::EmailNotifier.new( email_prefix: '[Dummy ERROR] ', - sender_address: %{"Dummy Notifier" }, - exception_recipients: %w{dummyexceptions@example.com}, + sender_address: %("Dummy Notifier" ), + exception_recipients: %w[dummyexceptions@example.com], deliver_with: deliver_with ) @@ -206,32 +206,32 @@ class EmailNotifierTest < ActiveSupport::TestCase assert_equal 1, ActionMailer::Base.deliveries.count end - test "should lazily evaluate exception_recipients" do - exception_recipients = %w{first@example.com second@example.com} + test 'should lazily evaluate exception_recipients' do + exception_recipients = %w[first@example.com second@example.com] email_notifier = ExceptionNotifier::EmailNotifier.new( email_prefix: '[Dummy ERROR] ', - sender_address: %{"Dummy Notifier" }, - exception_recipients: -> { [ exception_recipients.shift ] }, + sender_address: %("Dummy Notifier" ), + exception_recipients: -> { [exception_recipients.shift] }, delivery_method: :test ) mail = email_notifier.call(@exception) - assert_equal %w{first@example.com}, mail.to + assert_equal %w[first@example.com], mail.to mail = email_notifier.call(@exception) - assert_equal %w{second@example.com}, mail.to + assert_equal %w[second@example.com], mail.to end - test "should prepend accumulated_errors_count in email subject if accumulated_errors_count larger than 1" do + test 'should prepend accumulated_errors_count in email subject if accumulated_errors_count larger than 1' do ActionMailer::Base.deliveries.clear email_notifier = ExceptionNotifier::EmailNotifier.new( email_prefix: '[Dummy ERROR] ', - sender_address: %{"Dummy Notifier" }, - exception_recipients: %w{dummyexceptions@example.com}, + sender_address: %("Dummy Notifier" ), + exception_recipients: %w[dummyexceptions@example.com], delivery_method: :test ) - mail = email_notifier.call(@exception, { accumulated_errors_count: 3 }) - assert mail.subject.start_with?("[Dummy ERROR] (3 times) (ZeroDivisionError)") + mail = email_notifier.call(@exception, accumulated_errors_count: 3) + assert mail.subject.start_with?('[Dummy ERROR] (3 times) (ZeroDivisionError)') end end diff --git a/test/exception_notifier/google_chat_notifier_test.rb b/test/exception_notifier/google_chat_notifier_test.rb index 3da08add..ad39304f 100644 --- a/test/exception_notifier/google_chat_notifier_test.rb +++ b/test/exception_notifier/google_chat_notifier_test.rb @@ -68,9 +68,9 @@ def teardown exception = ArgumentError.new('foo') exception.set_backtrace([ - "app/controllers/my_controller.rb:53:in `my_controller_params'", - "app/controllers/my_controller.rb:34:in `update'" - ]) + "app/controllers/my_controller.rb:53:in `my_controller_params'", + "app/controllers/my_controller.rb:34:in `update'" + ]) notifier.call(exception) end @@ -92,11 +92,11 @@ def teardown exception = ArgumentError.new('foo') exception.set_backtrace([ - "app/controllers/my_controller.rb:99:in `specific_function'", - "app/controllers/my_controller.rb:70:in `specific_param'", - "app/controllers/my_controller.rb:53:in `my_controller_params'", - "app/controllers/my_controller.rb:34:in `update'" - ]) + "app/controllers/my_controller.rb:99:in `specific_function'", + "app/controllers/my_controller.rb:70:in `specific_param'", + "app/controllers/my_controller.rb:53:in `my_controller_params'", + "app/controllers/my_controller.rb:34:in `update'" + ]) notifier.call(exception) end @@ -126,9 +126,9 @@ def teardown exception = ArgumentError.new('foo') exception.set_backtrace([ - "app/controllers/my_controller.rb:53:in `my_controller_params'", - "app/controllers/my_controller.rb:34:in `update'" - ]) + "app/controllers/my_controller.rb:53:in `my_controller_params'", + "app/controllers/my_controller.rb:34:in `update'" + ]) notifier.call(exception, env: test_env) end @@ -160,7 +160,7 @@ def header [ '', 'Application: *dummy*', - "An *ArgumentError* occured.", + 'An *ArgumentError* occured.', '' ].join("\n") end diff --git a/test/exception_notifier/hipchat_notifier_test.rb b/test/exception_notifier/hipchat_notifier_test.rb index 2a47e7a1..c69d7ab0 100644 --- a/test/exception_notifier/hipchat_notifier_test.rb +++ b/test/exception_notifier/hipchat_notifier_test.rb @@ -8,22 +8,22 @@ end class HipchatNotifierTest < ActiveSupport::TestCase - - test "should send hipchat notification if properly configured" do + test 'should send hipchat notification if properly configured' do options = { api_token: 'good_token', room_name: 'room_name', - color: 'yellow', + color: 'yellow' } - HipChat::Room.any_instance.expects(:send).with('Exception', fake_body, { color: 'yellow' }) + HipChat::Room.any_instance.expects(:send).with('Exception', fake_body, color: 'yellow') hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end - test "should call pre/post_callback if specified" do - pre_callback_called, post_callback_called = 0, 0 + test 'should call pre/post_callback if specified' do + pre_callback_called = 0 + post_callback_called = 0 options = { api_token: 'good_token', room_name: 'room_name', @@ -40,63 +40,63 @@ class HipchatNotifierTest < ActiveSupport::TestCase assert_equal(1, post_callback_called) end - test "should send hipchat notification without backtrace info if properly configured" do + test 'should send hipchat notification without backtrace info if properly configured' do options = { api_token: 'good_token', room_name: 'room_name', - color: 'yellow', + color: 'yellow' } - HipChat::Room.any_instance.expects(:send).with('Exception', fake_body_without_backtrace, { color: 'yellow' }) + HipChat::Room.any_instance.expects(:send).with('Exception', fake_body_without_backtrace, color: 'yellow') hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception_without_backtrace) end - test "should allow custom from value if set" do + test 'should allow custom from value if set' do options = { api_token: 'good_token', room_name: 'room_name', - from: 'TrollFace', + from: 'TrollFace' } - HipChat::Room.any_instance.expects(:send).with('TrollFace', fake_body, { color: 'red' }) + HipChat::Room.any_instance.expects(:send).with('TrollFace', fake_body, color: 'red') hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end - test "should not send hipchat notification if badly configured" do + test 'should not send hipchat notification if badly configured' do wrong_params = { api_token: 'bad_token', room_name: 'test_room' } - HipChat::Client.stubs(:new).with('bad_token', { api_version: 'v1' }).returns(nil) + HipChat::Client.stubs(:new).with('bad_token', api_version: 'v1').returns(nil) hipchat = ExceptionNotifier::HipchatNotifier.new(wrong_params) assert_nil hipchat.room end - test "should not send hipchat notification if api_key is missing" do - wrong_params = { room_name: 'test_room' } + test 'should not send hipchat notification if api_key is missing' do + wrong_params = { room_name: 'test_room' } - HipChat::Client.stubs(:new).with(nil, {api_version: 'v1'}).returns(nil) + HipChat::Client.stubs(:new).with(nil, api_version: 'v1').returns(nil) hipchat = ExceptionNotifier::HipchatNotifier.new(wrong_params) assert_nil hipchat.room end - test "should not send hipchat notification if room_name is missing" do - wrong_params = { api_token: 'good_token' } + test 'should not send hipchat notification if room_name is missing' do + wrong_params = { api_token: 'good_token' } - HipChat::Client.stubs(:new).with('good_token', { api_version: 'v1' }).returns({}) + HipChat::Client.stubs(:new).with('good_token', api_version: 'v1').returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(wrong_params) assert_nil hipchat.room end - test "should send hipchat notification with message_template" do + test 'should send hipchat notification with message_template' do options = { api_token: 'good_token', room_name: 'room_name', @@ -104,86 +104,86 @@ class HipchatNotifierTest < ActiveSupport::TestCase message_template: ->(exception, _) { "This is custom message: '#{exception.message}'" } } - HipChat::Room.any_instance.expects(:send).with('Exception', "This is custom message: '#{fake_exception.message}'", { color: 'yellow' }) + HipChat::Room.any_instance.expects(:send).with('Exception', "This is custom message: '#{fake_exception.message}'", color: 'yellow') hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end - test "should send hipchat notification exclude accumulated errors count" do + test 'should send hipchat notification exclude accumulated errors count' do options = { api_token: 'good_token', room_name: 'room_name', color: 'yellow' } - HipChat::Room.any_instance.expects(:send).with{ |_, msg, _| msg.start_with?("A new exception occurred:") } + HipChat::Room.any_instance.expects(:send).with { |_, msg, _| msg.start_with?('A new exception occurred:') } hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end - test "should send hipchat notification include accumulated errors count" do + test 'should send hipchat notification include accumulated errors count' do options = { api_token: 'good_token', room_name: 'room_name', color: 'yellow' } - HipChat::Room.any_instance.expects(:send).with{ |_, msg, _| msg.start_with?("The exception occurred 3 times:") } + HipChat::Room.any_instance.expects(:send).with { |_, msg, _| msg.start_with?('The exception occurred 3 times:') } hipchat = ExceptionNotifier::HipchatNotifier.new(options) - hipchat.call(fake_exception, { accumulated_errors_count: 3 }) + hipchat.call(fake_exception, accumulated_errors_count: 3) end - test "should send hipchat notification with HTML-escaped meessage if using default message_template" do + test 'should send hipchat notification with HTML-escaped meessage if using default message_template' do options = { api_token: 'good_token', room_name: 'room_name', - color: 'yellow', + color: 'yellow' } exception = fake_exception_with_html_characters body = "A new exception occurred: '#{Rack::Utils.escape_html(exception.message)}' on '#{exception.backtrace.first}'" - HipChat::Room.any_instance.expects(:send).with('Exception', body, { color: 'yellow' }) + HipChat::Room.any_instance.expects(:send).with('Exception', body, color: 'yellow') hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(exception) end - test "should use APIv1 if api_version is not specified" do + test 'should use APIv1 if api_version is not specified' do options = { api_token: 'good_token', - room_name: 'room_name', + room_name: 'room_name' } - HipChat::Client.stubs(:new).with('good_token', { api_version: 'v1' }).returns({}) + HipChat::Client.stubs(:new).with('good_token', api_version: 'v1').returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end - test "should use APIv2 when specified" do + test 'should use APIv2 when specified' do options = { api_token: 'good_token', room_name: 'room_name', - api_version: 'v2', + api_version: 'v2' } - HipChat::Client.stubs(:new).with('good_token', { api_version: 'v2' }).returns({}) + HipChat::Client.stubs(:new).with('good_token', api_version: 'v2').returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end - test "should allow server_url value (for a self-hosted HipChat Server) if set" do + test 'should allow server_url value (for a self-hosted HipChat Server) if set' do options = { api_token: 'good_token', room_name: 'room_name', api_version: 'v2', - server_url: 'https://domain.com', + server_url: 'https://domain.com' } - HipChat::Client.stubs(:new).with('good_token', { api_version: 'v2', server_url: 'https://domain.com' }).returns({}) + HipChat::Client.stubs(:new).with('good_token', api_version: 'v2', server_url: 'https://domain.com').returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) @@ -196,19 +196,15 @@ def fake_body end def fake_exception - begin - 5/0 - rescue Exception => e - e - end + 5 / 0 + rescue Exception => e + e end def fake_exception_with_html_characters - begin - raise StandardError.new('an error with characters') - rescue Exception => e - e - end + raise StandardError, 'an error with characters' + rescue Exception => e + e end def fake_body_without_backtrace diff --git a/test/exception_notifier/irc_notifier_test.rb b/test/exception_notifier/irc_notifier_test.rb index 08983988..dacb989d 100644 --- a/test/exception_notifier/irc_notifier_test.rb +++ b/test/exception_notifier/irc_notifier_test.rb @@ -2,8 +2,7 @@ require 'carrier-pigeon' class IrcNotifierTest < ActiveSupport::TestCase - - test "should send irc notification if properly configured" do + test 'should send irc notification if properly configured' do options = { domain: 'irc.example.com' } @@ -16,24 +15,25 @@ class IrcNotifierTest < ActiveSupport::TestCase irc.call(fake_exception) end - test "should exclude errors count in message if :accumulated_errors_count nil" do + test 'should exclude errors count in message if :accumulated_errors_count nil' do irc = ExceptionNotifier::IrcNotifier.new({}) irc.stubs(:active?).returns(true) - irc.expects(:send_message).with{ |message| message.include?("divided by 0") }.once + irc.expects(:send_message).with { |message| message.include?('divided by 0') }.once irc.call(fake_exception) end - test "should include errors count in message if :accumulated_errors_count is 3" do + test 'should include errors count in message if :accumulated_errors_count is 3' do irc = ExceptionNotifier::IrcNotifier.new({}) irc.stubs(:active?).returns(true) - irc.expects(:send_message).with{ |message| message.include?("(3 times)'divided by 0'") }.once + irc.expects(:send_message).with { |message| message.include?("(3 times)'divided by 0'") }.once irc.call(fake_exception, accumulated_errors_count: 3) end - test "should call pre/post_callback if specified" do - pre_callback_called, post_callback_called = 0,0 + test 'should call pre/post_callback if specified' do + pre_callback_called = 0 + post_callback_called = 0 options = { domain: 'irc.example.com', @@ -51,7 +51,7 @@ class IrcNotifierTest < ActiveSupport::TestCase assert_equal(1, post_callback_called) end - test "should send irc notification without backtrace info if properly configured" do + test 'should send irc notification without backtrace info if properly configured' do options = { domain: 'irc.example.com' } @@ -64,7 +64,7 @@ class IrcNotifierTest < ActiveSupport::TestCase irc.call(fake_exception_without_backtrace) end - test "should properly construct URI from constituent parts" do + test 'should properly construct URI from constituent parts' do options = { nick: 'BadNewsBot', password: 'secret', @@ -73,16 +73,16 @@ class IrcNotifierTest < ActiveSupport::TestCase channel: '#exceptions' } - CarrierPigeon.expects(:send).with(has_entry(uri: "irc://BadNewsBot:secret@irc.example.com:9999/#exceptions")) + CarrierPigeon.expects(:send).with(has_entry(uri: 'irc://BadNewsBot:secret@irc.example.com:9999/#exceptions')) irc = ExceptionNotifier::IrcNotifier.new(options) irc.call(fake_exception) end - test "should properly add recipients if specified" do + test 'should properly add recipients if specified' do options = { domain: 'irc.example.com', - recipients: ['peter', 'michael', 'samir'] + recipients: %w[peter michael samir] } CarrierPigeon.expects(:send).with(has_key(:uri)) do |v| @@ -93,7 +93,7 @@ class IrcNotifierTest < ActiveSupport::TestCase irc.call(fake_exception) end - test "should properly set miscellaneous options" do + test 'should properly set miscellaneous options' do options = { domain: 'irc.example.com', ssl: true, @@ -103,10 +103,10 @@ class IrcNotifierTest < ActiveSupport::TestCase } CarrierPigeon.expects(:send).with(has_entries( - ssl: true, - join: true, - notice: true, - )) do |v| + ssl: true, + join: true, + notice: true + )) do |v| /\[test notification\]/.match(v[:message]) end @@ -114,8 +114,8 @@ class IrcNotifierTest < ActiveSupport::TestCase irc.call(fake_exception) end - test "should not send irc notification if badly configured" do - wrong_params = { domain: '##scriptkiddie.com###'} + test 'should not send irc notification if badly configured' do + wrong_params = { domain: '##scriptkiddie.com###' } irc = ExceptionNotifier::IrcNotifier.new(wrong_params) assert_nil irc.call(fake_exception) @@ -124,11 +124,9 @@ class IrcNotifierTest < ActiveSupport::TestCase private def fake_exception - begin - 5/0 - rescue Exception => e - e - end + 5 / 0 + rescue Exception => e + e end def fake_exception_without_backtrace diff --git a/test/exception_notifier/mattermost_notifier_test.rb b/test/exception_notifier/mattermost_notifier_test.rb index 76127cd1..f2404e23 100644 --- a/test/exception_notifier/mattermost_notifier_test.rb +++ b/test/exception_notifier/mattermost_notifier_test.rb @@ -2,18 +2,18 @@ require 'httparty' class MattermostNotifierTest < ActiveSupport::TestCase - test "should send notification if properly configured" do + test 'should send notification if properly configured' do options = { webhook_url: 'http://localhost:8000' } mattermost_notifier = ExceptionNotifier::MattermostNotifier.new mattermost_notifier.httparty = FakeHTTParty.new - options = mattermost_notifier.call ArgumentError.new("foo"), options + options = mattermost_notifier.call ArgumentError.new('foo'), options body = ActiveSupport::JSON.decode options[:body] - assert body.has_key? 'text' - assert body.has_key? 'username' + assert body.key? 'text' + assert body.key? 'username' text = body['text'].split("\n") assert_equal 4, text.size @@ -22,7 +22,7 @@ class MattermostNotifierTest < ActiveSupport::TestCase assert_equal '*foo*', text[3] end - test "should send notification with create issue link if specified" do + test 'should send notification with create issue link if specified' do options = { webhook_url: 'http://localhost:8000', git_url: 'github.com/aschen' @@ -30,7 +30,7 @@ class MattermostNotifierTest < ActiveSupport::TestCase mattermost_notifier = ExceptionNotifier::MattermostNotifier.new mattermost_notifier.httparty = FakeHTTParty.new - options = mattermost_notifier.call ArgumentError.new("foo"), options + options = mattermost_notifier.call ArgumentError.new('foo'), options body = ActiveSupport::JSON.decode options[:body] @@ -48,7 +48,7 @@ class MattermostNotifierTest < ActiveSupport::TestCase mattermost_notifier = ExceptionNotifier::MattermostNotifier.new mattermost_notifier.httparty = FakeHTTParty.new - options = mattermost_notifier.call ArgumentError.new("foo"), options + options = mattermost_notifier.call ArgumentError.new('foo'), options body = ActiveSupport::JSON.decode options[:body] @@ -69,34 +69,34 @@ class MattermostNotifierTest < ActiveSupport::TestCase mattermost_notifier = ExceptionNotifier::MattermostNotifier.new mattermost_notifier.httparty = FakeHTTParty.new - options = mattermost_notifier.call ArgumentError.new("foo"), options + options = mattermost_notifier.call ArgumentError.new('foo'), options - assert options.has_key? :basic_auth + assert options.key? :basic_auth assert 'clara', options[:basic_auth][:username] assert 'password', options[:basic_auth][:password] end test "should use 'An' for exceptions count if :accumulated_errors_count option is nil" do mattermost_notifier = ExceptionNotifier::MattermostNotifier.new - exception = ArgumentError.new("foo") + exception = ArgumentError.new('foo') mattermost_notifier.instance_variable_set(:@exception, exception) mattermost_notifier.instance_variable_set(:@options, {}) - assert_includes mattermost_notifier.send(:message_header), "An *ArgumentError* occured." + assert_includes mattermost_notifier.send(:message_header), 'An *ArgumentError* occured.' end - test "shoud use direct errors count if :accumulated_errors_count option is 5" do + test 'shoud use direct errors count if :accumulated_errors_count option is 5' do mattermost_notifier = ExceptionNotifier::MattermostNotifier.new - exception = ArgumentError.new("foo") + exception = ArgumentError.new('foo') mattermost_notifier.instance_variable_set(:@exception, exception) - mattermost_notifier.instance_variable_set(:@options, { accumulated_errors_count: 5 }) + mattermost_notifier.instance_variable_set(:@options, accumulated_errors_count: 5) - assert_includes mattermost_notifier.send(:message_header), "5 *ArgumentError* occured." + assert_includes mattermost_notifier.send(:message_header), '5 *ArgumentError* occured.' end end class FakeHTTParty - def post(url, options) - return options + def post(_url, options) + options end end diff --git a/test/exception_notifier/modules/error_grouping_test.rb b/test/exception_notifier/modules/error_grouping_test.rb index 0b4c994f..56270e07 100644 --- a/test/exception_notifier/modules/error_grouping_test.rb +++ b/test/exception_notifier/modules/error_grouping_test.rb @@ -1,18 +1,17 @@ require 'test_helper' class ErrorGroupTest < ActiveSupport::TestCase - setup do module TestModule include ExceptionNotifier::ErrorGrouping - @@error_grouping_cache = ActiveSupport::Cache::FileStore.new("test/dummy/tmp/non_default_location") + @@error_grouping_cache = ActiveSupport::Cache::FileStore.new('test/dummy/tmp/non_default_location') end - @exception = RuntimeError.new("ERROR") - @exception.stubs(:backtrace).returns(["/path/where/error/raised:1"]) + @exception = RuntimeError.new('ERROR') + @exception.stubs(:backtrace).returns(['/path/where/error/raised:1']) - @exception2 = RuntimeError.new("ERROR2") - @exception2.stubs(:backtrace).returns(["/path/where/error/found:2"]) + @exception2 = RuntimeError.new('ERROR2') + @exception2.stubs(:backtrace).returns(['/path/where/error/found:2']) end teardown do @@ -20,88 +19,88 @@ module TestModule TestModule.fallback_cache_store.clear end - test "should add additional option: error_grouping" do + test 'should add additional option: error_grouping' do assert_respond_to TestModule, :error_grouping assert_respond_to TestModule, :error_grouping= end - test "should set error_grouping to false default" do + test 'should set error_grouping to false default' do assert_equal false, TestModule.error_grouping end - test "should add additional option: error_grouping_cache" do + test 'should add additional option: error_grouping_cache' do assert_respond_to TestModule, :error_grouping_cache assert_respond_to TestModule, :error_grouping_cache= end - test "should add additional option: error_grouping_period" do + test 'should add additional option: error_grouping_period' do assert_respond_to TestModule, :error_grouping_period assert_respond_to TestModule, :error_grouping_period= end - test "shoud set error_grouping_period to 5.minutes default" do + test 'shoud set error_grouping_period to 5.minutes default' do assert_equal 300, TestModule.error_grouping_period end - test "should add additional option: notification_trigger" do + test 'should add additional option: notification_trigger' do assert_respond_to TestModule, :notification_trigger assert_respond_to TestModule, :notification_trigger= end - test "should return errors count nil when not same error for .error_count" do - assert_nil TestModule.error_count("something") + test 'should return errors count nil when not same error for .error_count' do + assert_nil TestModule.error_count('something') end - test "should return errors count when same error for .error_count" do - TestModule.error_grouping_cache.write("error_key", 13) - assert_equal 13, TestModule.error_count("error_key") + test 'should return errors count when same error for .error_count' do + TestModule.error_grouping_cache.write('error_key', 13) + assert_equal 13, TestModule.error_count('error_key') end - test "should fallback to memory store cache if specified cache store failed to read" do - TestModule.error_grouping_cache.stubs(:read).raises(RuntimeError.new "Failed to read") + test 'should fallback to memory store cache if specified cache store failed to read' do + TestModule.error_grouping_cache.stubs(:read).raises(RuntimeError.new('Failed to read')) original_fallback = TestModule.fallback_cache_store TestModule.expects(:fallback_cache_store).returns(original_fallback).at_least_once - assert_nil TestModule.error_count("something_to_read") + assert_nil TestModule.error_count('something_to_read') end - test "should save error with count for .save_error_count" do + test 'should save error with count for .save_error_count' do count = rand(1..10) - TestModule.save_error_count("error_key", count) - assert_equal count, TestModule.error_grouping_cache.read("error_key") + TestModule.save_error_count('error_key', count) + assert_equal count, TestModule.error_grouping_cache.read('error_key') end - test "should fallback to memory store cache if specified cache store failed to write" do - TestModule.error_grouping_cache.stubs(:write).raises(RuntimeError.new "Failed to write") + test 'should fallback to memory store cache if specified cache store failed to write' do + TestModule.error_grouping_cache.stubs(:write).raises(RuntimeError.new('Failed to write')) original_fallback = TestModule.fallback_cache_store TestModule.expects(:fallback_cache_store).returns(original_fallback).at_least_once - assert TestModule.save_error_count("something_to_cache", rand(1..10)) + assert TestModule.save_error_count('something_to_cache', rand(1..10)) end - test "should save accumulated_errors_count into options" do + test 'should save accumulated_errors_count into options' do options = {} TestModule.group_error!(@exception, options) assert_equal 1, options[:accumulated_errors_count] end - test "should not group error if different exception in .group_error!" do + test 'should not group error if different exception in .group_error!' do options1 = {} - TestModule.expects(:save_error_count).with{|key, count| key.is_a?(String) && count == 1}.times(4).returns(true) + TestModule.expects(:save_error_count).with { |key, count| key.is_a?(String) && count == 1 }.times(4).returns(true) TestModule.group_error!(@exception, options1) options2 = {} - TestModule.group_error!(NoMethodError.new("method not found"), options2) + TestModule.group_error!(NoMethodError.new('method not found'), options2) assert_equal 1, options1[:accumulated_errors_count] assert_equal 1, options2[:accumulated_errors_count] end - test "should not group error is same exception but different message or backtrace" do + test 'should not group error is same exception but different message or backtrace' do options1 = {} - TestModule.expects(:save_error_count).with{|key, count| key.is_a?(String) && count == 1}.times(4).returns(true) + TestModule.expects(:save_error_count).with { |key, count| key.is_a?(String) && count == 1 }.times(4).returns(true) TestModule.group_error!(@exception, options1) options2 = {} @@ -111,7 +110,7 @@ module TestModule assert_equal 1, options2[:accumulated_errors_count] end - test "should group error if same exception and message" do + test 'should group error if same exception and message' do options = {} 10.times do |i| @@ -122,7 +121,7 @@ module TestModule assert_equal 10, options[:accumulated_errors_count] end - test "should group error if same exception and backtrace" do + test 'should group error if same exception and backtrace' do options = {} 10.times do |i| @@ -133,7 +132,7 @@ module TestModule assert_equal 10, options[:accumulated_errors_count] end - test "should group error by that message have high priority" do + test 'should group error by that message have high priority' do message_based_key = "exception:#{Zlib.crc32("RuntimeError\nmessage:ERROR")}" backtrace_based_key = "exception:#{Zlib.crc32("RuntimeError\n/path/where/error/raised:1")}" @@ -146,7 +145,7 @@ module TestModule TestModule.group_error!(@exception, {}) end - test "use default formula if not specify notification_trigger in .send_notification?" do + test 'use default formula if not specify notification_trigger in .send_notification?' do TestModule.stubs(:notification_trigger).returns(nil) count = 16 @@ -155,12 +154,12 @@ module TestModule assert TestModule.send_notification?(@exception, count) end - test "use specified trigger in .send_notification?" do - trigger = Proc.new { |exception, count| count % 4 == 0 } + test 'use specified trigger in .send_notification?' do + trigger = proc { |_exception, count| count % 4 == 0 } TestModule.stubs(:notification_trigger).returns(trigger) count = 16 trigger.expects(:call).with(@exception, count).returns(true) assert TestModule.send_notification?(@exception, count) end -end \ No newline at end of file +end diff --git a/test/exception_notifier/sidekiq_test.rb b/test/exception_notifier/sidekiq_test.rb index 0e58c4ab..6674240b 100644 --- a/test/exception_notifier/sidekiq_test.rb +++ b/test/exception_notifier/sidekiq_test.rb @@ -1,11 +1,11 @@ -require "test_helper" +require 'test_helper' # To allow sidekiq error handlers to be registered, sidekiq must be in # "server mode". This mode is triggered by loading sidekiq/cli. Note this # has to be loaded before exception_notification/sidekiq. -require "sidekiq/cli" +require 'sidekiq/cli' -require "exception_notification/sidekiq" +require 'exception_notification/sidekiq' class MockSidekiqServer include ::Sidekiq::ExceptionHandler @@ -19,9 +19,9 @@ class SidekiqTest < ActiveSupport::TestCase Sidekiq::Logging.logger = nil end - test "should call notify_exception when sidekiq raises an error" do + test 'should call notify_exception when sidekiq raises an error' do server = MockSidekiqServer.new - message = Hash.new + message = {} exception = RuntimeError.new ExceptionNotifier.expects(:notify_exception).with( diff --git a/test/exception_notifier/slack_notifier_test.rb b/test/exception_notifier/slack_notifier_test.rb index a649076a..c4636674 100644 --- a/test/exception_notifier/slack_notifier_test.rb +++ b/test/exception_notifier/slack_notifier_test.rb @@ -2,7 +2,6 @@ require 'slack-notifier' class SlackNotifierTest < ActiveSupport::TestCase - def setup @exception = fake_exception @exception.stubs(:backtrace).returns(fake_backtrace) @@ -10,9 +9,9 @@ def setup Socket.stubs(:gethostname).returns('example.com') end - test "should send a slack notification if properly configured" do + test 'should send a slack notification if properly configured' do options = { - webhook_url: "http://slack.webhook.url" + webhook_url: 'http://slack.webhook.url' } Slack::Notifier.any_instance.expects(:ping).with('', fake_notification) @@ -21,9 +20,9 @@ def setup slack_notifier.call(@exception) end - test "should send a slack notification without backtrace info if properly configured" do + test 'should send a slack notification without backtrace info if properly configured' do options = { - webhook_url: "http://slack.webhook.url" + webhook_url: 'http://slack.webhook.url' } Slack::Notifier.any_instance.expects(:ping).with('', fake_notification(fake_exception_without_backtrace)) @@ -32,10 +31,10 @@ def setup slack_notifier.call(fake_exception_without_backtrace) end - test "should send the notification to the specified channel" do + test 'should send the notification to the specified channel' do options = { - webhook_url: "http://slack.webhook.url", - channel: "channel" + webhook_url: 'http://slack.webhook.url', + channel: 'channel' } Slack::Notifier.any_instance.expects(:ping).with('', fake_notification) @@ -47,10 +46,10 @@ def setup assert_equal channel, options[:channel] end - test "should send the notification to the specified username" do + test 'should send the notification to the specified username' do options = { - webhook_url: "http://slack.webhook.url", - username: "username" + webhook_url: 'http://slack.webhook.url', + username: 'username' } Slack::Notifier.any_instance.expects(:ping).with('', fake_notification) @@ -62,9 +61,9 @@ def setup assert_equal username, options[:username] end - test "should send the notification with specific backtrace lines" do + test 'should send the notification with specific backtrace lines' do options = { - webhook_url: "http://slack.webhook.url", + webhook_url: 'http://slack.webhook.url', backtrace_lines: 1 } @@ -74,10 +73,10 @@ def setup slack_notifier.call(@exception) end - test "should send the notification with additional fields" do - field = {title: "Branch", value: "master", short: true} + test 'should send the notification with additional fields' do + field = { title: 'Branch', value: 'master', short: true } options = { - webhook_url: "http://slack.webhook.url", + webhook_url: 'http://slack.webhook.url', additional_fields: [field] } @@ -90,17 +89,17 @@ def setup assert_equal additional_fields, options[:additional_fields] end - test "should pass the additional parameters to Slack::Notifier.ping" do + test 'should pass the additional parameters to Slack::Notifier.ping' do options = { - webhook_url: "http://slack.webhook.url", - username: "test", - custom_hook: "hook", + webhook_url: 'http://slack.webhook.url', + username: 'test', + custom_hook: 'hook', additional_parameters: { - icon_url: "icon", + icon_url: 'icon' } } - Slack::Notifier.any_instance.expects(:ping).with('', options[:additional_parameters].merge(fake_notification) ) + Slack::Notifier.any_instance.expects(:ping).with('', options[:additional_parameters].merge(fake_notification)) slack_notifier = ExceptionNotifier::SlackNotifier.new(options) slack_notifier.call(@exception) @@ -115,11 +114,11 @@ def setup assert_nil slack_notifier.call(@exception) end - test "should pass along environment data" do + test 'should pass along environment data' do options = { - webhook_url: "http://slack.webhook.url", - ignore_data_if: lambda {|k,v| - "#{k}" == 'key_to_be_ignored' || v.is_a?(Hash) + webhook_url: 'http://slack.webhook.url', + ignore_data_if: lambda { |k, v| + k.to_s == 'key_to_be_ignored' || v.is_a?(Hash) } } @@ -130,7 +129,7 @@ def setup data: { 'user_id' => 5, 'key_to_be_ignored' => 'whatever', - 'ignore_as_well' => { what: 'ever'} + 'ignore_as_well' => { what: 'ever' } } } @@ -141,29 +140,29 @@ def setup slack_notifier.call(@exception, notification_options) end - test "should call pre/post_callback proc if specified" do + test 'should call pre/post_callback proc if specified' do post_callback_called = 0 options = { - webhook_url: "http://slack.webhook.url", - username: "test", - custom_hook: "hook", - pre_callback: proc { |opts, notifier, backtrace, message, message_opts| - (message_opts[:attachments] = []) << { text: "#{backtrace.join("\n")}", color: 'danger' } + webhook_url: 'http://slack.webhook.url', + username: 'test', + custom_hook: 'hook', + pre_callback: proc { |_opts, _notifier, backtrace, _message, message_opts| + (message_opts[:attachments] = []) << { text: backtrace.join("\n").to_s, color: 'danger' } }, - post_callback: proc { |opts, notifier, backtrace, message, message_opts| + post_callback: proc { |_opts, _notifier, _backtrace, _message, _message_opts| post_callback_called = 1 }, additional_parameters: { - icon_url: "icon", + icon_url: 'icon' } } - Slack::Notifier.any_instance.expects(:ping).with('', { - icon_url: 'icon', - attachments: [{ - text: fake_backtrace.join("\n"), - color: 'danger' } - ]}) + Slack::Notifier.any_instance.expects(:ping).with('', + icon_url: 'icon', + attachments: [{ + text: fake_backtrace.join("\n"), + color: 'danger' + }]) slack_notifier = ExceptionNotifier::SlackNotifier.new(options) slack_notifier.call(@exception) @@ -173,11 +172,9 @@ def setup private def fake_exception - begin - 5/0 - rescue Exception => e - e - end + 5 / 0 + rescue Exception => e + e end def fake_exception_without_backtrace @@ -186,17 +183,17 @@ def fake_exception_without_backtrace def fake_backtrace [ - "backtrace line 1", - "backtrace line 2", - "backtrace line 3", - "backtrace line 4", - "backtrace line 5", - "backtrace line 6", + 'backtrace line 1', + 'backtrace line 2', + 'backtrace line 3', + 'backtrace line 4', + 'backtrace line 5', + 'backtrace line 6' ] end def fake_notification(exception = @exception, notification_options = {}, data_string = nil, expected_backtrace_lines = 10, additional_fields = []) - exception_name = "*#{exception.class.to_s =~ /^[aeiou]/i ? 'An' : 'A'}* `#{exception.class.to_s}`" + exception_name = "*#{exception.class.to_s =~ /^[aeiou]/i ? 'An' : 'A'}* `#{exception.class}`" if notification_options[:env].nil? text = "#{exception_name} *occured in background*" else @@ -211,16 +208,15 @@ def fake_notification(exception = @exception, notification_options = {}, data_st text += "\n" - fields = [ { title: 'Exception', value: exception.message} ] - fields.push({ title: 'Hostname', value: 'example.com' }) + fields = [{ title: 'Exception', value: exception.message }] + fields.push(title: 'Hostname', value: 'example.com') if exception.backtrace formatted_backtrace = "```#{exception.backtrace.first(expected_backtrace_lines).join("\n")}```" - fields.push({ title: 'Backtrace', value: formatted_backtrace }) + fields.push(title: 'Backtrace', value: formatted_backtrace) end - fields.push({ title: 'Data', value: "```#{data_string}```" }) if data_string + fields.push(title: 'Data', value: "```#{data_string}```") if data_string additional_fields.each { |f| fields.push(f) } - { attachments: [ color: 'danger', text: text, fields: fields, mrkdwn_in: %w(text fields) ] } + { attachments: [color: 'danger', text: text, fields: fields, mrkdwn_in: %w[text fields]] } end - end diff --git a/test/exception_notifier/sns_notifier_test.rb b/test/exception_notifier/sns_notifier_test.rb index 382aabef..a68813ab 100644 --- a/test/exception_notifier/sns_notifier_test.rb +++ b/test/exception_notifier/sns_notifier_test.rb @@ -12,7 +12,7 @@ def setup secret_access_key: 'my-secret_access_key', region: 'us-east', topic_arn: 'topicARN', - sns_prefix: '[App Exception]', + sns_prefix: '[App Exception]' } Socket.stubs(:gethostname).returns('example.com') end @@ -60,41 +60,38 @@ def setup test 'should send a sns notification in background' do Aws::SNS::Client.any_instance.expects(:publish).with( - { - topic_arn: "topicARN", + topic_arn: 'topicARN', message: "3 MyException occured in background\n"\ - "Exception: undefined method 'method=' for Empty\n"\ - "Hostname: example.com\n"\ - "Backtrace:\n#{fake_backtrace.join("\n")}\n", - subject: "[App Exception] - 3 MyException occurred" - }) + "Exception: undefined method 'method=' for Empty\n"\ + "Hostname: example.com\n"\ + "Backtrace:\n#{fake_backtrace.join("\n")}\n", + subject: '[App Exception] - 3 MyException occurred' + ) sns_notifier = ExceptionNotifier::SnsNotifier.new(@options) - sns_notifier.call(@exception, { accumulated_errors_count: 3 }) + sns_notifier.call(@exception, accumulated_errors_count: 3) end test 'should send a sns notification with controller#action information' do ExamplesController.any_instance.stubs(:action_name).returns('index') Aws::SNS::Client.any_instance.expects(:publish).with( - { - topic_arn: "topicARN", - message: "A MyException occurred while GET "\ - "was processed by examples#index\n"\ - "Exception: undefined method 'method=' for Empty\n"\ - "Hostname: example.com\n"\ - "Backtrace:\n#{fake_backtrace.join("\n")}\n", - subject: "[App Exception] - A MyException occurred" - }) + topic_arn: 'topicARN', + message: 'A MyException occurred while GET '\ + "was processed by examples#index\n"\ + "Exception: undefined method 'method=' for Empty\n"\ + "Hostname: example.com\n"\ + "Backtrace:\n#{fake_backtrace.join("\n")}\n", + subject: '[App Exception] - A MyException occurred' + ) sns_notifier = ExceptionNotifier::SnsNotifier.new(@options) sns_notifier.call(@exception, - env: { - 'REQUEST_METHOD' => 'GET', - 'REQUEST_URI' => '/examples', - 'action_controller.instance' => ExamplesController.new - } - ) + env: { + 'REQUEST_METHOD' => 'GET', + 'REQUEST_URI' => '/examples', + 'action_controller.instance' => ExamplesController.new + }) end private @@ -102,11 +99,9 @@ def setup class ExamplesController < ActionController::Base; end def fake_exception - begin - 1 / 0 - rescue Exception => e - e - end + 1 / 0 + rescue Exception => e + e end def fake_exception_without_backtrace diff --git a/test/exception_notifier/teams_notifier_test.rb b/test/exception_notifier/teams_notifier_test.rb index df98206a..d21b800b 100644 --- a/test/exception_notifier/teams_notifier_test.rb +++ b/test/exception_notifier/teams_notifier_test.rb @@ -2,19 +2,18 @@ require 'httparty' class TeamsNotifierTest < ActiveSupport::TestCase - - test "should send notification if properly configured" do + test 'should send notification if properly configured' do options = { webhook_url: 'http://localhost:8000' } teams_notifier = ExceptionNotifier::TeamsNotifier.new teams_notifier.httparty = FakeHTTParty.new - options = teams_notifier.call ArgumentError.new("foo"), options + options = teams_notifier.call ArgumentError.new('foo'), options body = ActiveSupport::JSON.decode options[:body] - assert body.has_key? 'title' - assert body.has_key? 'sections' + assert body.key? 'title' + assert body.key? 'sections' sections = body['sections'] header = sections[0] @@ -24,7 +23,7 @@ class TeamsNotifierTest < ActiveSupport::TestCase assert_equal 'foo', header['activitySubtitle'] end - test "should send notification with create gitlab issue link if specified" do + test 'should send notification with create gitlab issue link if specified' do options = { webhook_url: 'http://localhost:8000', git_url: 'github.com/aschen' @@ -32,7 +31,7 @@ class TeamsNotifierTest < ActiveSupport::TestCase teams_notifier = ExceptionNotifier::TeamsNotifier.new teams_notifier.httparty = FakeHTTParty.new - options = teams_notifier.call ArgumentError.new("foo"), options + options = teams_notifier.call ArgumentError.new('foo'), options body = ActiveSupport::JSON.decode options[:body] @@ -45,7 +44,7 @@ class TeamsNotifierTest < ActiveSupport::TestCase test 'should add other HTTParty options to params' do options = { webhook_url: 'http://localhost:8000', - username: "Test Bot", + username: 'Test Bot', avatar: 'http://site.com/icon.png', basic_auth: { username: 'clara', @@ -55,16 +54,16 @@ class TeamsNotifierTest < ActiveSupport::TestCase teams_notifier = ExceptionNotifier::TeamsNotifier.new teams_notifier.httparty = FakeHTTParty.new - options = teams_notifier.call ArgumentError.new("foo"), options + options = teams_notifier.call ArgumentError.new('foo'), options - assert options.has_key? :basic_auth + assert options.key? :basic_auth assert 'clara', options[:basic_auth][:username] assert 'password', options[:basic_auth][:password] end test "should use 'A' for exceptions count if :accumulated_errors_count option is nil" do teams_notifier = ExceptionNotifier::TeamsNotifier.new - exception = ArgumentError.new("foo") + exception = ArgumentError.new('foo') teams_notifier.instance_variable_set(:@exception, exception) teams_notifier.instance_variable_set(:@options, {}) @@ -73,11 +72,11 @@ class TeamsNotifierTest < ActiveSupport::TestCase assert_equal 'A *ArgumentError* occurred.', header['activityTitle'] end - test "should use direct errors count if :accumulated_errors_count option is 5" do + test 'should use direct errors count if :accumulated_errors_count option is 5' do teams_notifier = ExceptionNotifier::TeamsNotifier.new - exception = ArgumentError.new("foo") + exception = ArgumentError.new('foo') teams_notifier.instance_variable_set(:@exception, exception) - teams_notifier.instance_variable_set(:@options, { accumulated_errors_count: 5 }) + teams_notifier.instance_variable_set(:@options, accumulated_errors_count: 5) message_text = teams_notifier.send(:message_text) header = message_text['sections'][0] assert_equal '5 *ArgumentError* occurred.', header['activityTitle'] @@ -85,9 +84,7 @@ class TeamsNotifierTest < ActiveSupport::TestCase end class FakeHTTParty - - def post(url, options) - return options + def post(_url, options) + options end - end diff --git a/test/exception_notifier/webhook_notifier_test.rb b/test/exception_notifier/webhook_notifier_test.rb index 3990e085..010f0a52 100644 --- a/test/exception_notifier/webhook_notifier_test.rb +++ b/test/exception_notifier/webhook_notifier_test.rb @@ -2,42 +2,41 @@ require 'httparty' class WebhookNotifierTest < ActiveSupport::TestCase - - test "should send webhook notification if properly configured" do + test 'should send webhook notification if properly configured' do ExceptionNotifier::WebhookNotifier.stubs(:new).returns(Object.new) - webhook = ExceptionNotifier::WebhookNotifier.new({ url: 'http://localhost:8000' }) + webhook = ExceptionNotifier::WebhookNotifier.new(url: 'http://localhost:8000') webhook.stubs(:call).returns(fake_response) response = webhook.call(fake_exception) refute_nil response assert_equal response[:status], 200 - assert_equal response[:body][:exception][:error_class], "ZeroDivisionError" - assert_includes response[:body][:exception][:message], "divided by 0" - assert_includes response[:body][:exception][:backtrace], "/exception_notification/test/webhook_notifier_test.rb:48" + assert_equal response[:body][:exception][:error_class], 'ZeroDivisionError' + assert_includes response[:body][:exception][:message], 'divided by 0' + assert_includes response[:body][:exception][:backtrace], '/exception_notification/test/webhook_notifier_test.rb:48' - assert response[:body][:request][:cookies].has_key?(:cookie_item1) - assert_equal response[:body][:request][:url], "http://example.com/example" - assert_equal response[:body][:request][:ip_address], "192.168.1.1" - assert response[:body][:request][:environment].has_key?(:env_item1) - assert_equal response[:body][:request][:controller], "#" - assert response[:body][:request][:session].has_key?(:session_item1) - assert response[:body][:request][:parameters].has_key?(:controller) - assert response[:body][:data][:extra_data].has_key?(:data_item1) + assert response[:body][:request][:cookies].key?(:cookie_item1) + assert_equal response[:body][:request][:url], 'http://example.com/example' + assert_equal response[:body][:request][:ip_address], '192.168.1.1' + assert response[:body][:request][:environment].key?(:env_item1) + assert_equal response[:body][:request][:controller], '#' + assert response[:body][:request][:session].key?(:session_item1) + assert response[:body][:request][:parameters].key?(:controller) + assert response[:body][:data][:extra_data].key?(:data_item1) end - test "should send webhook notification with correct params data" do + test 'should send webhook notification with correct params data' do url = 'http://localhost:8000' fake_exception.stubs(:backtrace).returns('the backtrace') - webhook = ExceptionNotifier::WebhookNotifier.new({ url: url }) + webhook = ExceptionNotifier::WebhookNotifier.new(url: url) HTTParty.expects(:send).with(:post, url, fake_params) webhook.call(fake_exception) end - test "should call pre/post_callback if specified" do + test 'should call pre/post_callback if specified' do HTTParty.stubs(:send).returns(fake_response) - webhook = ExceptionNotifier::WebhookNotifier.new({ url: 'http://localhost:8000' }) + webhook = ExceptionNotifier::WebhookNotifier.new(url: 'http://localhost:8000') webhook.call(fake_exception) end @@ -62,7 +61,7 @@ def fake_response environment: { env_item1: 'envitem1', env_item2: 'envitem2' }, controller: '#', session: { session_item1: 'sessionitem1', session_item2: 'sessionitem2' }, - parameters: { action:'index', controller:'projects' } + parameters: { action: 'index', controller: 'projects' } } } } @@ -72,7 +71,7 @@ def fake_params { body: { server: Socket.gethostname, - process: $$, + process: $PROCESS_ID, rails_root: Rails.root, exception: { error_class: 'ZeroDivisionError', @@ -86,7 +85,7 @@ def fake_params def fake_exception @fake_exception ||= begin - 5/0 + 5 / 0 rescue Exception => e e end diff --git a/test/exception_notifier_test.rb b/test/exception_notifier_test.rb index 00d71c44..55c9f3df 100644 --- a/test/exception_notifier_test.rb +++ b/test/exception_notifier_test.rb @@ -1,44 +1,44 @@ require 'test_helper' -class ExceptionOne < StandardError;end -class ExceptionTwo < StandardError;end +class ExceptionOne < StandardError; end +class ExceptionTwo < StandardError; end class ExceptionNotifierTest < ActiveSupport::TestCase setup do @notifier_calls = 0 - @test_notifier = lambda { |exception, options| @notifier_calls += 1 } + @test_notifier = ->(_exception, _options) { @notifier_calls += 1 } end teardown do ExceptionNotifier.error_grouping = false ExceptionNotifier.notification_trigger = nil - ExceptionNotifier.class_eval("@@notifiers.delete_if { |k, _| k.to_s != \"email\"}") # reset notifiers + ExceptionNotifier.class_eval('@@notifiers.delete_if { |k, _| k.to_s != "email"}') # reset notifiers Rails.cache.clear end - test "should have default ignored exceptions" do + test 'should have default ignored exceptions' do assert_equal ExceptionNotifier.ignored_exceptions, - ['ActiveRecord::RecordNotFound', 'Mongoid::Errors::DocumentNotFound', 'AbstractController::ActionNotFound', - 'ActionController::RoutingError', 'ActionController::UnknownFormat', 'ActionController::UrlGenerationError'] + ['ActiveRecord::RecordNotFound', 'Mongoid::Errors::DocumentNotFound', 'AbstractController::ActionNotFound', + 'ActionController::RoutingError', 'ActionController::UnknownFormat', 'ActionController::UrlGenerationError'] end - test "should have email notifier registered" do + test 'should have email notifier registered' do assert_equal ExceptionNotifier.notifiers, [:email] end - test "should have a valid email notifier" do + test 'should have a valid email notifier' do @email_notifier = ExceptionNotifier.registered_exception_notifier(:email) refute_nil @email_notifier assert_equal @email_notifier.class, ExceptionNotifier::EmailNotifier assert_respond_to @email_notifier, :call end - test "should allow register/unregister another notifier" do + test 'should allow register/unregister another notifier' do called = false - proc_notifier = lambda { |exception, options| called = true } + proc_notifier = ->(_exception, _options) { called = true } ExceptionNotifier.register_exception_notifier(:proc, proc_notifier) - assert_equal ExceptionNotifier.notifiers.sort, [:email, :proc] + assert_equal ExceptionNotifier.notifiers.sort, %i[email proc] exception = StandardError.new @@ -49,27 +49,27 @@ class ExceptionNotifierTest < ActiveSupport::TestCase assert_equal ExceptionNotifier.notifiers, [:email] end - test "should allow select notifiers to send error to" do + test 'should allow select notifiers to send error to' do notifier1_calls = 0 - notifier1 = lambda { |exception, options| notifier1_calls += 1 } + notifier1 = ->(_exception, _options) { notifier1_calls += 1 } ExceptionNotifier.register_exception_notifier(:notifier1, notifier1) notifier2_calls = 0 - notifier2 = lambda { |exception, options| notifier2_calls += 1 } + notifier2 = ->(_exception, _options) { notifier2_calls += 1 } ExceptionNotifier.register_exception_notifier(:notifier2, notifier2) - assert_equal ExceptionNotifier.notifiers.sort, [:email, :notifier1, :notifier2] + assert_equal ExceptionNotifier.notifiers.sort, %i[email notifier1 notifier2] exception = StandardError.new ExceptionNotifier.notify_exception(exception) assert_equal notifier1_calls, 1 assert_equal notifier2_calls, 1 - ExceptionNotifier.notify_exception(exception, {notifiers: :notifier1}) + ExceptionNotifier.notify_exception(exception, notifiers: :notifier1) assert_equal notifier1_calls, 2 assert_equal notifier2_calls, 1 - ExceptionNotifier.notify_exception(exception, {notifiers: :notifier2}) + ExceptionNotifier.notify_exception(exception, notifiers: :notifier2) assert_equal notifier1_calls, 2 assert_equal notifier2_calls, 2 @@ -78,39 +78,39 @@ class ExceptionNotifierTest < ActiveSupport::TestCase assert_equal ExceptionNotifier.notifiers, [:email] end - test "should ignore exception if satisfies conditional ignore" do - env = "production" - ExceptionNotifier.ignore_if do |exception, options| - env != "production" + test 'should ignore exception if satisfies conditional ignore' do + env = 'production' + ExceptionNotifier.ignore_if do |_exception, _options| + env != 'production' end ExceptionNotifier.register_exception_notifier(:test, @test_notifier) exception = StandardError.new - ExceptionNotifier.notify_exception(exception, {notifiers: :test}) + ExceptionNotifier.notify_exception(exception, notifiers: :test) assert_equal @notifier_calls, 1 - env = "development" - ExceptionNotifier.notify_exception(exception, {notifiers: :test}) + env = 'development' + ExceptionNotifier.notify_exception(exception, notifiers: :test) assert_equal @notifier_calls, 1 ExceptionNotifier.clear_ignore_conditions! end - test "should not send notification if one of ignored exceptions" do + test 'should not send notification if one of ignored exceptions' do ExceptionNotifier.register_exception_notifier(:test, @test_notifier) exception = StandardError.new - ExceptionNotifier.notify_exception(exception, {notifiers: :test}) + ExceptionNotifier.notify_exception(exception, notifiers: :test) assert_equal @notifier_calls, 1 - ExceptionNotifier.notify_exception(exception, {notifiers: :test, ignore_exceptions: 'StandardError' }) + ExceptionNotifier.notify_exception(exception, notifiers: :test, ignore_exceptions: 'StandardError') assert_equal @notifier_calls, 1 end - test "should not send notification if subclass of one of ignored exceptions" do + test 'should not send notification if subclass of one of ignored exceptions' do ExceptionNotifier.register_exception_notifier(:test, @test_notifier) class StandardErrorSubclass < StandardError @@ -118,16 +118,16 @@ class StandardErrorSubclass < StandardError exception = StandardErrorSubclass.new - ExceptionNotifier.notify_exception(exception, {notifiers: :test}) + ExceptionNotifier.notify_exception(exception, notifiers: :test) assert_equal @notifier_calls, 1 - ExceptionNotifier.notify_exception(exception, {notifiers: :test, ignore_exceptions: 'StandardError' }) + ExceptionNotifier.notify_exception(exception, notifiers: :test, ignore_exceptions: 'StandardError') assert_equal @notifier_calls, 1 end - test "should call received block" do + test 'should call received block' do @block_called = false - notifier = lambda { |exception, options, &block| block.call } + notifier = ->(_exception, _options, &block) { block.call } ExceptionNotifier.register_exception_notifier(:test, notifier) exception = ExceptionOne.new @@ -139,7 +139,7 @@ class StandardErrorSubclass < StandardError assert @block_called end - test "should not call group_error! or send_notification? if error_grouping false" do + test 'should not call group_error! or send_notification? if error_grouping false' do exception = StandardError.new ExceptionNotifier.expects(:group_error!).never ExceptionNotifier.expects(:send_notification?).never @@ -147,7 +147,7 @@ class StandardErrorSubclass < StandardError ExceptionNotifier.notify_exception(exception) end - test "should call group_error! and send_notification? if error_grouping true" do + test 'should call group_error! and send_notification? if error_grouping true' do ExceptionNotifier.error_grouping = true exception = StandardError.new @@ -157,7 +157,7 @@ class StandardErrorSubclass < StandardError ExceptionNotifier.notify_exception(exception) end - test "should skip notification if send_notification? is false" do + test 'should skip notification if send_notification? is false' do ExceptionNotifier.error_grouping = true exception = StandardError.new @@ -167,7 +167,7 @@ class StandardErrorSubclass < StandardError refute ExceptionNotifier.notify_exception(exception) end - test "should send notification if send_notification? is true" do + test 'should send notification if send_notification? is true' do ExceptionNotifier.error_grouping = true exception = StandardError.new diff --git a/test/test_helper.rb b/test/test_helper.rb index 9b1f858c..7e24f042 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,18 +1,18 @@ # Configure Rails Environment -ENV["RAILS_ENV"] = "test" +ENV['RAILS_ENV'] = 'test' begin - require "coveralls" + require 'coveralls' Coveralls.wear! rescue LoadError - warn "warning: coveralls gem not found; skipping Coveralls" + warn 'warning: coveralls gem not found; skipping Coveralls' end -require File.expand_path("../dummy/config/environment.rb", __FILE__) -require "rails/test_help" -require File.expand_path("../dummy/test/test_helper.rb", __FILE__) +require File.expand_path('dummy/config/environment.rb', __dir__) +require 'rails/test_help' +require File.expand_path('dummy/test/test_helper.rb', __dir__) -require "mocha/setup" +require 'mocha/setup' Rails.backtrace_cleaner.remove_silencers! ExceptionNotifier.testing_mode! From 06ec82501cfe510798eae42dbebdb986ed3100c6 Mon Sep 17 00:00:00 2001 From: Fabian Larranaga Date: Tue, 18 Dec 2018 20:04:43 -0300 Subject: [PATCH 2/3] Add rubocop_todo.yml --- .rubocop.yml | 1 + .rubocop_todo.yml | 180 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 .rubocop.yml create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..cc32da4b --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1 @@ +inherit_from: .rubocop_todo.yml diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 00000000..566eec83 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,180 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2018-12-18 20:02:43 -0300 using RuboCop version 0.59.2. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 1 +# Configuration parameters: Include. +# Include: **/*.gemspec +Gemspec/RequiredRubyVersion: + Exclude: + - 'exception_notification.gemspec' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'lib/exception_notifier/campfire_notifier.rb' + - 'lib/exception_notifier/hipchat_notifier.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Layout/RescueEnsureAlignment: + Exclude: + - 'lib/exception_notifier/modules/error_grouping.rb' + - 'test/exception_notifier/webhook_notifier_test.rb' + +# Offense count: 2 +# Configuration parameters: AllowSafeAssignment. +Lint/AssignmentInCondition: + Exclude: + - 'lib/exception_notifier/modules/error_grouping.rb' + +# Offense count: 12 +Lint/RescueException: + Exclude: + - 'examples/sinatra/sinatra_app.rb' + - 'lib/exception_notification/rack.rb' + - 'lib/exception_notification/sidekiq.rb' + - 'lib/exception_notifier.rb' + - 'test/exception_notifier/campfire_notifier_test.rb' + - 'test/exception_notifier/hipchat_notifier_test.rb' + - 'test/exception_notifier/irc_notifier_test.rb' + - 'test/exception_notifier/slack_notifier_test.rb' + - 'test/exception_notifier/sns_notifier_test.rb' + - 'test/exception_notifier/webhook_notifier_test.rb' + +# Offense count: 2 +# Configuration parameters: ContextCreatingMethods, MethodCreatingMethods. +Lint/UselessAccessModifier: + Exclude: + - 'lib/exception_notifier/datadog_notifier.rb' + - 'test/exception_notifier/datadog_notifier_test.rb' + +# Offense count: 1 +Lint/UselessAssignment: + Exclude: + - 'lib/exception_notifier/sns_notifier.rb' + +# Offense count: 18 +Metrics/AbcSize: + Max: 97 + +# Offense count: 3 +# Configuration parameters: CountComments, ExcludedMethods. +# ExcludedMethods: refine +Metrics/BlockLength: + Max: 88 + +# Offense count: 10 +# Configuration parameters: CountComments. +Metrics/ClassLength: + Max: 186 + +# Offense count: 9 +Metrics/CyclomaticComplexity: + Max: 24 + +# Offense count: 28 +# Configuration parameters: CountComments, ExcludedMethods. +Metrics/MethodLength: + Max: 90 + +# Offense count: 7 +Metrics/PerceivedComplexity: + Max: 24 + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, EnforcedStyle. +# SupportedStyles: nested, compact +Style/ClassAndModuleChildren: + Exclude: + - 'test/dummy/test/test_helper.rb' + +# Offense count: 6 +Style/ClassVars: + Exclude: + - 'lib/exception_notifier.rb' + - 'test/exception_notifier/modules/error_grouping_test.rb' + +# Offense count: 28 +Style/Documentation: + Enabled: false + +# Offense count: 1 +Style/DoubleNegation: + Exclude: + - 'lib/exception_notifier/irc_notifier.rb' + +# Offense count: 1 +Style/EvalWithLocation: + Exclude: + - 'test/exception_notifier_test.rb' + +# Offense count: 6 +# Configuration parameters: MinBodyLength. +Style/GuardClause: + Exclude: + - 'lib/exception_notifier/campfire_notifier.rb' + - 'lib/exception_notifier/email_notifier.rb' + - 'lib/exception_notifier/google_chat_notifier.rb' + - 'lib/exception_notifier/irc_notifier.rb' + - 'lib/exception_notifier/slack_notifier.rb' + - 'lib/exception_notifier/sns_notifier.rb' + +# Offense count: 7 +# Cop supports --auto-correct. +Style/IfUnlessModifier: + Exclude: + - 'lib/exception_notification/rack.rb' + - 'lib/exception_notifier/datadog_notifier.rb' + - 'lib/exception_notifier/google_chat_notifier.rb' + - 'lib/exception_notifier/webhook_notifier.rb' + - 'test/dummy/test/functional/posts_controller_test.rb' + - 'test/exception_notifier/email_notifier_test.rb' + +# Offense count: 3 +Style/MethodMissingSuper: + Exclude: + - 'lib/exception_notifier/email_notifier.rb' + - 'lib/exception_notifier/mattermost_notifier.rb' + - 'lib/exception_notifier/teams_notifier.rb' + +# Offense count: 3 +Style/MissingRespondToMissing: + Exclude: + - 'lib/exception_notifier/email_notifier.rb' + - 'lib/exception_notifier/mattermost_notifier.rb' + - 'lib/exception_notifier/teams_notifier.rb' + +# Offense count: 1 +Style/MultilineBlockChain: + Exclude: + - 'lib/exception_notifier/email_notifier.rb' + +# Offense count: 2 +Style/NestedTernaryOperator: + Exclude: + - 'lib/exception_notifier/slack_notifier.rb' + - 'lib/exception_notifier/sns_notifier.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, EnforcedStyle, IgnoredMethods. +# SupportedStyles: predicate, comparison +Style/NumericPredicate: + Exclude: + - 'spec/**/*' + - 'test/exception_notifier/modules/error_grouping_test.rb' + +# Offense count: 253 +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Metrics/LineLength: + Max: 226 From f825b9f9bc03df69d2d283cc7829aba5cdc4b358 Mon Sep 17 00:00:00 2001 From: Fabian Larranaga Date: Wed, 23 Jan 2019 18:48:53 -0300 Subject: [PATCH 3/3] Sort missing dev dependencies & add rubocop target --- .rubocop.yml | 4 ++++ exception_notification.gemspec | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index cc32da4b..86fc25ea 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1 +1,5 @@ inherit_from: .rubocop_todo.yml + +AllCops: + TargetRubyVersion: 2.0 + DisplayCopNames: true diff --git a/exception_notification.gemspec b/exception_notification.gemspec index 154eeb03..23afd287 100644 --- a/exception_notification.gemspec +++ b/exception_notification.gemspec @@ -19,9 +19,6 @@ Gem::Specification.new do |s| s.add_dependency('actionmailer', '>= 4.0', '< 6') s.add_dependency('activesupport', '>= 4.0', '< 6') - s.add_development_dependency 'rails', '>= 4.0', '< 6' - s.add_development_dependency 'resque', '~> 1.8.0' - # Sidekiq 3.2.2 does not support Ruby 1.9. s.add_development_dependency 'appraisal', '~> 2.2.0' s.add_development_dependency 'aws-sdk-sns', '~> 1' s.add_development_dependency 'carrier-pigeon', '>= 0.7.0' @@ -31,6 +28,10 @@ Gem::Specification.new do |s| s.add_development_dependency 'httparty', '~> 0.10.2' s.add_development_dependency 'mock_redis', '~> 0.18.0' s.add_development_dependency 'mocha', '>= 0.13.0' + s.add_development_dependency 'rails', '>= 4.0', '< 6' + s.add_development_dependency 'resque', '~> 1.8.0' + s.add_development_dependency 'rubocop', '0.50.0' + # Sidekiq 3.2.2 does not support Ruby 1.9. s.add_development_dependency 'sidekiq', '~> 3.0.0', '< 3.2.2' s.add_development_dependency 'slack-notifier', '>= 1.0.0' s.add_development_dependency 'sqlite3', '>= 1.3.4'