From 05c99ae9d8982a591c36e74297449bb2b949cd5d Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Fri, 30 Mar 2018 22:43:41 +0300 Subject: [PATCH] Rubocop format with the Rails config --- .rubocop.yml | 162 ++++++++++++++++++ Gemfile | 20 ++- Rakefile | 26 +-- lib/web-console.rb | 2 +- lib/web_console.rb | 8 +- lib/web_console/context.rb | 12 +- lib/web_console/evaluator.rb | 2 +- lib/web_console/exception_mapper.rb | 20 +-- lib/web_console/extensions.rb | 2 +- lib/web_console/middleware.rb | 18 +- lib/web_console/railtie.rb | 26 +-- lib/web_console/request.rb | 4 +- lib/web_console/response.rb | 2 +- lib/web_console/tasks/extensions.rake | 26 +-- lib/web_console/tasks/templates.rake | 12 +- lib/web_console/template.rb | 2 +- lib/web_console/testing/erb_precompiler.rb | 6 +- lib/web_console/testing/fake_middleware.rb | 10 +- lib/web_console/testing/helper.rb | 2 +- lib/web_console/version.rb | 2 +- lib/web_console/view.rb | 6 +- lib/web_console/whiny_request.rb | 2 +- lib/web_console/whitelist.rb | 6 +- test/dummy/Rakefile | 4 +- test/dummy/bin/bundle | 6 +- test/dummy/bin/rails | 8 +- test/dummy/bin/rake | 6 +- test/dummy/config.ru | 4 +- test/dummy/config/application.rb | 4 +- test/dummy/config/boot.rb | 6 +- test/dummy/config/environment.rb | 2 +- .../dummy/config/initializers/secret_token.rb | 2 +- .../config/initializers/session_store.rb | 2 +- .../scenarios/bad_custom_error_scenario.rb | 1 - .../scenarios/basic_nested_scenario.rb | 6 +- .../support/scenarios/eval_nested_scenario.rb | 6 +- test/support/scenarios/reraised_scenario.rb | 16 +- test/test_helper.rb | 10 +- test/web_console/context_test.rb | 24 +-- test/web_console/evaluator_test.rb | 28 +-- test/web_console/exception_mapper_test.rb | 16 +- test/web_console/extensions_test.rb | 16 +- test/web_console/helper_test.rb | 24 +-- test/web_console/integration_test.rb | 26 +-- test/web_console/middleware_test.rb | 112 ++++++------ test/web_console/railtie_test.rb | 50 +++--- test/web_console/request_test.rb | 42 ++--- test/web_console/session_test.rb | 34 ++-- test/web_console/whiny_request_test.rb | 12 +- test/web_console/whitelist_test.rb | 34 ++-- web-console.gemspec | 10 +- 51 files changed, 533 insertions(+), 356 deletions(-) create mode 100644 .rubocop.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..3c765d5b --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,162 @@ +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Do not use braces for hash literals when they are the last argument of a +# method call. +Style/BracesAroundHashParameters: + Enabled: true + EnforcedStyle: context_dependent + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstParameterIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: true + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: rails + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: true + EnforcedStyle: always + Exclude: + - 'actionview/test/**/*.builder' + - 'actionview/test/**/*.ruby' + - 'actionpack/test/**/*.builder' + - 'actionpack/test/**/*.ruby' + - 'activestorage/db/migrate/**/*.rb' + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes + +# Detect hard tabs, no hard tabs. +Layout/Tab: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingBlankLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: true + +# Use quotes for string literals when they are enough. +Style/UnneededPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Lint/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true + +# Prefer Foo.method over Foo::method +Style/ColonMethodCall: + Enabled: true diff --git a/Gemfile b/Gemfile index 5707ff84..1bfb9046 100644 --- a/Gemfile +++ b/Gemfile @@ -1,20 +1,22 @@ -source 'https://rubygems.org' +# frozen_string_literal: true + +source "https://rubygems.org" gemspec -gem 'rails', github: 'rails/rails' -gem 'arel', github: 'rails/arel' -gem 'rack', github: 'rack/rack' +gem "rails", github: "rails/rails" +gem "arel", github: "rails/arel" +gem "rack", github: "rack/rack" group :development do platform :ruby do - gem 'byebug' + gem "byebug" end - gem 'puma' + gem "puma" end group :test do - gem 'rake' - gem 'mocha', require: false - gem 'simplecov', require: false + gem "rake" + gem "mocha", require: false + gem "simplecov", require: false end diff --git a/Rakefile b/Rakefile index 45177c79..30be3a94 100644 --- a/Rakefile +++ b/Rakefile @@ -1,26 +1,28 @@ +# frozen_string_literal: true + begin - require 'bundler/setup' + require "bundler/setup" rescue LoadError - puts 'You must `gem install bundler` and `bundle install` to run rake tasks' + puts "You must `gem install bundler` and `bundle install` to run rake tasks" end -require 'socket' -require 'rake/testtask' -require 'tmpdir' -require 'securerandom' -require 'json' -require 'web_console/testing/erb_precompiler' +require "socket" +require "rake/testtask" +require "tmpdir" +require "securerandom" +require "json" +require "web_console/testing/erb_precompiler" EXPANDED_CWD = File.expand_path(File.dirname(__FILE__)) Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.libs << 'test' - t.pattern = 'test/**/*_test.rb' + t.libs << "lib" + t.libs << "test" + t.pattern = "test/**/*_test.rb" t.verbose = false end -Dir['lib/web_console/tasks/**/*.rake'].each { |task| load task } +Dir["lib/web_console/tasks/**/*.rake"].each { |task| load task } Bundler::GemHelper.install_tasks diff --git a/lib/web-console.rb b/lib/web-console.rb index 09c95e48..09138cd5 100644 --- a/lib/web-console.rb +++ b/lib/web-console.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -require 'web_console' +require "web_console" diff --git a/lib/web_console.rb b/lib/web_console.rb index 823330cc..0ba155a4 100644 --- a/lib/web_console.rb +++ b/lib/web_console.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'active_support/dependencies/autoload' -require 'active_support/logger' +require "active_support/dependencies/autoload" +require "active_support/logger" module WebConsole extend ActiveSupport::Autoload @@ -18,7 +18,7 @@ module WebConsole autoload :Middleware autoload :Context - autoload_at 'web_console/errors' do + autoload_at "web_console/errors" do autoload :Error autoload :DoubleRenderError end @@ -28,4 +28,4 @@ def self.logger end end -require 'web_console/railtie' +require "web_console/railtie" diff --git a/lib/web_console/context.rb b/lib/web_console/context.rb index f9e57c0b..ead093b3 100644 --- a/lib/web_console/context.rb +++ b/lib/web_console/context.rb @@ -19,12 +19,12 @@ def extract(input = nil) private GLOBAL_OBJECTS = [ - 'instance_variables', - 'local_variables', - 'methods', - 'class_variables', - 'Object.constants', - 'global_variables' + "instance_variables", + "local_variables", + "methods", + "class_variables", + "Object.constants", + "global_variables" ] def global diff --git a/lib/web_console/evaluator.rb b/lib/web_console/evaluator.rb index e8a9fea4..26040127 100644 --- a/lib/web_console/evaluator.rb +++ b/lib/web_console/evaluator.rb @@ -10,7 +10,7 @@ class Evaluator # Cleanses exceptions raised inside #eval. cattr_reader :cleaner @@cleaner = ActiveSupport::BacktraceCleaner.new - @@cleaner.add_silencer { |line| line.start_with?(File.expand_path('..', __FILE__)) } + @@cleaner.add_silencer { |line| line.start_with?(File.expand_path("..", __FILE__)) } def initialize(binding = TOPLEVEL_BINDING) @binding = binding diff --git a/lib/web_console/exception_mapper.rb b/lib/web_console/exception_mapper.rb index 959af2cc..e09c2f4e 100644 --- a/lib/web_console/exception_mapper.rb +++ b/lib/web_console/exception_mapper.rb @@ -17,19 +17,19 @@ def [](index) private - def guess_binding_for_index(index) - file, line = @backtrace[index].to_s.split(':') - line = line.to_i + def guess_binding_for_index(index) + file, line = @backtrace[index].to_s.split(":") + line = line.to_i - @bindings.find do |binding| - binding.eval('__FILE__') == file && binding.eval('__LINE__') == line + @bindings.find do |binding| + binding.eval("__FILE__") == file && binding.eval("__LINE__") == line + end end - end - def guess_the_first_application_binding - @bindings.find do |binding| - binding.eval('__FILE__').to_s.start_with?(Rails.root.to_s) + def guess_the_first_application_binding + @bindings.find do |binding| + binding.eval("__FILE__").to_s.start_with?(Rails.root.to_s) + end end - end end end diff --git a/lib/web_console/extensions.rb b/lib/web_console/extensions.rb index fa79de25..8e54da06 100644 --- a/lib/web_console/extensions.rb +++ b/lib/web_console/extensions.rb @@ -26,7 +26,7 @@ module ActionDispatch class DebugExceptions def render_exception_with_web_console(request, exception) render_exception_without_web_console(request, exception).tap do - backtrace_cleaner = request.get_header('action_dispatch.backtrace_cleaner') + backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner") error = ExceptionWrapper.new(backtrace_cleaner, exception).exception # Get the original exception if ExceptionWrapper decides to follow it. diff --git a/lib/web_console/middleware.rb b/lib/web_console/middleware.rb index a09dd13b..e8f26746 100644 --- a/lib/web_console/middleware.rb +++ b/lib/web_console/middleware.rb @@ -1,13 +1,13 @@ # frozen_string_literal: true -require 'active_support/core_ext/string/strip' +require "active_support/core_ext/string/strip" module WebConsole class Middleware - TEMPLATES_PATH = File.expand_path('../templates', __FILE__) + TEMPLATES_PATH = File.expand_path("../templates", __FILE__) cattr_accessor :mount_point - @@mount_point = '/__web_console' + @@mount_point = "/__web_console" cattr_accessor :whiny_requests @@whiny_requests = true @@ -29,13 +29,13 @@ def call(env) status, headers, body = call_app(env) - if session = Session.from(Thread.current) and acceptable_content_type?(headers) + if (session = Session.from(Thread.current)) && acceptable_content_type?(headers) response = Response.new(body, status, headers) template = Template.new(env, session) response.headers["X-Web-Console-Session-Id"] = session.id response.headers["X-Web-Console-Mount-Point"] = mount_point - response.write(template.render('index')) + response.write(template.render("index")) response.finish else [ status, headers, body ] @@ -56,12 +56,12 @@ def call(env) private def acceptable_content_type?(headers) - Mime::Type.parse(headers['Content-Type'].to_s).first == Mime[:html] + Mime::Type.parse(headers["Content-Type"].to_s).first == Mime[:html] end def json_response(opts = {}) status = opts.fetch(:status, 200) - headers = { 'Content-Type' => 'application/json; charset = utf-8' } + headers = { "Content-Type" => "application/json; charset = utf-8" } body = yield.to_json Rack::Response.new(body, status, headers).finish @@ -123,13 +123,13 @@ def change_stack_trace(id, request) def respond_with_unavailable_session(id) json_response(status: 404) do - { output: format(I18n.t('errors.unavailable_session'), id: id)} + { output: format(I18n.t("errors.unavailable_session"), id: id) } end end def respond_with_unacceptable_request json_response(status: 406) do - { output: I18n.t('errors.unacceptable_request') } + { output: I18n.t("errors.unacceptable_request") } end end diff --git a/lib/web_console/railtie.rb b/lib/web_console/railtie.rb index f7063785..c2afe94d 100644 --- a/lib/web_console/railtie.rb +++ b/lib/web_console/railtie.rb @@ -1,18 +1,18 @@ # frozen_string_literal: true -require 'rails/railtie' +require "rails/railtie" module WebConsole class Railtie < ::Rails::Railtie config.web_console = ActiveSupport::OrderedOptions.new config.web_console.whitelisted_ips = %w( 127.0.0.1 ::1 ) - initializer 'web_console.initialize' do - require 'bindex' - require 'web_console/extensions' + initializer "web_console.initialize" do + require "bindex" + require "web_console/extensions" end - initializer 'web_console.development_only' do + initializer "web_console.development_only" do unless (config.web_console.development_only == false) || Rails.env.development? abort <<-END.strip_heredoc Web Console is activated in the #{Rails.env} environment. This is @@ -30,13 +30,13 @@ class Railtie < ::Rails::Railtie end end - initializer 'web_console.insert_middleware' do |app| + initializer "web_console.insert_middleware" do |app| app.middleware.insert_before ActionDispatch::DebugExceptions, Middleware end - initializer 'web_console.mount_point' do + initializer "web_console.mount_point" do if mount_point = config.web_console.mount_point - Middleware.mount_point = mount_point.chomp('/') + Middleware.mount_point = mount_point.chomp("/") end if root = Rails.application.config.relative_url_root @@ -44,26 +44,26 @@ class Railtie < ::Rails::Railtie end end - initializer 'web_console.template_paths' do + initializer "web_console.template_paths" do if template_paths = config.web_console.template_paths Template.template_paths.unshift(*Array(template_paths)) end end - initializer 'web_console.whitelisted_ips' do + initializer "web_console.whitelisted_ips" do if whitelisted_ips = config.web_console.whitelisted_ips Request.whitelisted_ips = Whitelist.new(whitelisted_ips) end end - initializer 'web_console.whiny_requests' do + initializer "web_console.whiny_requests" do if config.web_console.key?(:whiny_requests) Middleware.whiny_requests = config.web_console.whiny_requests end end - initializer 'i18n.load_path' do - config.i18n.load_path.concat(Dir[File.expand_path('../locales/*.yml', __FILE__)]) + initializer "i18n.load_path" do + config.i18n.load_path.concat(Dir[File.expand_path("../locales/*.yml", __FILE__)]) end end end diff --git a/lib/web_console/request.rb b/lib/web_console/request.rb index ca5e5b6e..305a9a1a 100644 --- a/lib/web_console/request.rb +++ b/lib/web_console/request.rb @@ -8,7 +8,7 @@ class Request < ActionDispatch::Request @@whitelisted_ips = Whitelist.new # Define a vendor MIME type. We can call it using Mime[:web_console_v2]. - Mime::Type.register 'application/vnd.web-console.v2', :web_console_v2 + Mime::Type.register "application/vnd.web-console.v2", :web_console_v2 # Returns whether a request came from a whitelisted IP. # @@ -22,7 +22,7 @@ def from_whitelisted_ip? def strict_remote_ip GetSecureIp.new(self, whitelisted_ips).to_s rescue ActionDispatch::RemoteIp::IpSpoofAttackError - '[Spoofed]' + "[Spoofed]" end # Returns whether the request is acceptable. diff --git a/lib/web_console/response.rb b/lib/web_console/response.rb index ffdd2d87..350b6d54 100644 --- a/lib/web_console/response.rb +++ b/lib/web_console/response.rb @@ -13,7 +13,7 @@ def write(content) body.close if body.respond_to?(:close) self.body = - if position = raw_body.rindex('') + if position = raw_body.rindex("") raw_body.dup.insert(position, content) else raw_body.dup << content diff --git a/lib/web_console/tasks/extensions.rake b/lib/web_console/tasks/extensions.rake index 9565cbfd..d4568dd1 100644 --- a/lib/web_console/tasks/extensions.rake +++ b/lib/web_console/tasks/extensions.rake @@ -1,25 +1,25 @@ # frozen_string_literal: true namespace :ext do - rootdir = Pathname('extensions') + rootdir = Pathname("extensions") - desc 'Build Chrome Extension' - task chrome: 'chrome:build' + desc "Build Chrome Extension" + task chrome: "chrome:build" namespace :chrome do - dist = Pathname('dist/crx') + dist = Pathname("dist/crx") extdir = rootdir.join(dist) - manifest_json = rootdir.join('chrome/manifest.json') + manifest_json = rootdir.join("chrome/manifest.json") directory extdir - task build: [ extdir, 'lib:templates' ] do + task build: [ extdir, "lib:templates" ] do cd rootdir do - cp_r [ 'img/', 'tmp/lib/' ], dist + cp_r [ "img/", "tmp/lib/" ], dist `cd chrome && git ls-files`.split("\n").each do |src| dest = dist.join(src) mkdir_p dest.dirname - cp Pathname('chrome').join(src), dest + cp Pathname("chrome").join(src), dest end end end @@ -36,7 +36,7 @@ namespace :ext do cd(extdir) { sh "zip -r ../crx-web-console-#{version}.zip ./" } end - desc 'Launch a browser with the chrome extension.' + desc "Launch a browser with the chrome extension." task run: [ :build ] do cd(rootdir) { sh "sh ./script/run_chrome.sh --load-extension=#{dist}" } end @@ -47,15 +47,15 @@ namespace :ext do end namespace :lib do - templates = Pathname('lib/web_console/templates') - tmplib = rootdir.join('tmp/lib/') - js_erb = FileList.new(templates.join('**/*.js.erb')) + templates = Pathname("lib/web_console/templates") + tmplib = rootdir.join("tmp/lib/") + js_erb = FileList.new(templates.join("**/*.js.erb")) dirs = js_erb.pathmap("%{^#{templates},#{tmplib}}d") task templates: dirs + js_erb.pathmap("%{^#{templates},#{tmplib}}X") dirs.each { |d| directory d } - rule '.js' => [ "%{^#{tmplib},#{templates}}X.js.erb" ] do |t| + rule ".js" => [ "%{^#{tmplib},#{templates}}X.js.erb" ] do |t| File.write(t.name, WebConsole::Testing::ERBPrecompiler.new(t.source).build) end end diff --git a/lib/web_console/tasks/templates.rake b/lib/web_console/tasks/templates.rake index 6526d30a..f51ae659 100644 --- a/lib/web_console/tasks/templates.rake +++ b/lib/web_console/tasks/templates.rake @@ -1,16 +1,16 @@ # frozen_string_literal: true namespace :templates do - desc 'Run tests for templates' + desc "Run tests for templates" task test: [ :daemonize, :npm, :rackup, :wait, :mocha, :kill, :exit ] task serve: [ :npm, :rackup ] - workdir = Pathname(EXPANDED_CWD).join('test/templates') + workdir = Pathname(EXPANDED_CWD).join("test/templates") pid = Pathname(Dir.tmpdir).join("web_console_test.pid") runner = URI.parse("http://#{ENV['IP'] || '127.0.0.1'}:#{ENV['PORT'] || 29292}/html/test_runner.html") rackup = "rackup --host #{runner.host} --port #{runner.port}" result = nil - browser = 'phantomjs' + browser = "phantomjs" def need_to_wait?(uri) Net::HTTP.start(uri.host, uri.port) { |http| http.get(uri.path) } @@ -22,13 +22,13 @@ namespace :templates do rackup += " -D --pid #{pid}" end - task :npm => [ :phantomjs ] do - Dir.chdir(workdir) { system 'npm install --silent' } + task npm: [ :phantomjs ] do + Dir.chdir(workdir) { system "npm install --silent" } end task :phantomjs do unless system("which #{browser} >/dev/null") - browser = './node_modules/.bin/phantomjs' + browser = "./node_modules/.bin/phantomjs" Dir.chdir(workdir) { system("test -f #{browser} || npm install --silent phantomjs-prebuilt") } end end diff --git a/lib/web_console/template.rb b/lib/web_console/template.rb index 3f60342c..6cf10c9f 100644 --- a/lib/web_console/template.rb +++ b/lib/web_console/template.rb @@ -8,7 +8,7 @@ module WebConsole class Template # Lets you customize the default templates folder location. cattr_accessor :template_paths - @@template_paths = [ File.expand_path('../templates', __FILE__) ] + @@template_paths = [ File.expand_path("../templates", __FILE__) ] def initialize(env, session) @env = env diff --git a/lib/web_console/testing/erb_precompiler.rb b/lib/web_console/testing/erb_precompiler.rb index 8e156bb0..88e337c0 100644 --- a/lib/web_console/testing/erb_precompiler.rb +++ b/lib/web_console/testing/erb_precompiler.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'web_console/testing/helper' -require 'web_console/testing/fake_middleware' +require "web_console/testing/helper" +require "web_console/testing/fake_middleware" module WebConsole module Testing @@ -10,7 +10,7 @@ class ERBPrecompiler def initialize(path) @erb = ERB.new(File.read(path)) @view = FakeMiddleware.new( - view_path: Helper.gem_root.join('lib/web_console/templates'), + view_path: Helper.gem_root.join("lib/web_console/templates"), ).view end diff --git a/lib/web_console/testing/fake_middleware.rb b/lib/web_console/testing/fake_middleware.rb index 4dcf2d39..eae2bafb 100644 --- a/lib/web_console/testing/fake_middleware.rb +++ b/lib/web_console/testing/fake_middleware.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true -require 'action_view' -require 'web_console' -require 'web_console/testing/helper' -Mime = { web_console_v2: 'fake' } +require "action_view" +require "web_console" +require "web_console/testing/helper" +Mime = { web_console_v2: "fake" } module WebConsole module Testing class FakeMiddleware - I18n.load_path.concat(Dir[Helper.gem_root.join('lib/web_console/locales/*.yml')]) + I18n.load_path.concat(Dir[Helper.gem_root.join("lib/web_console/locales/*.yml")]) DEFAULT_HEADERS = { "Content-Type" => "application/javascript" } diff --git a/lib/web_console/testing/helper.rb b/lib/web_console/testing/helper.rb index ba6f57c9..12831dae 100644 --- a/lib/web_console/testing/helper.rb +++ b/lib/web_console/testing/helper.rb @@ -4,7 +4,7 @@ module WebConsole module Testing module Helper def self.gem_root - Pathname(File.expand_path('../../../../', __FILE__)) + Pathname(File.expand_path("../../../../", __FILE__)) end end end diff --git a/lib/web_console/version.rb b/lib/web_console/version.rb index a7a628cd..e43928ca 100644 --- a/lib/web_console/version.rb +++ b/lib/web_console/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module WebConsole - VERSION = '3.5.1' + VERSION = "3.5.1" end diff --git a/lib/web_console/view.rb b/lib/web_console/view.rb index 96e6ddd0..15b6fba4 100644 --- a/lib/web_console/view.rb +++ b/lib/web_console/view.rb @@ -17,7 +17,7 @@ def only_on_error_page(*args) # leaking globals, unless you explicitly want to. def render_javascript(template) assign(template: template) - render(template: template, layout: 'layouts/javascript') + render(template: template, layout: "layouts/javascript") end # Render inlined string to be used inside of JavaScript code. @@ -25,7 +25,7 @@ def render_javascript(template) # The inlined string is returned as an actual JavaScript string. You # don't need to wrap the result yourself. def render_inlined_string(template) - render(template: template, layout: 'layouts/inlined_string') + render(template: template, layout: "layouts/inlined_string") end # Custom ActionView::Base#render wrapper which silences all the log @@ -33,7 +33,7 @@ def render_inlined_string(template) # # Helps to keep the Rails logs clean during errors. def render(*) - if logger = WebConsole.logger and logger.respond_to?(:silence) + if (logger = WebConsole.logger) && logger.respond_to?(:silence) WebConsole.logger.silence { super } else super diff --git a/lib/web_console/whiny_request.rb b/lib/web_console/whiny_request.rb index 1ef33a52..c5a8e936 100644 --- a/lib/web_console/whiny_request.rb +++ b/lib/web_console/whiny_request.rb @@ -23,7 +23,7 @@ def whine_unless(condition) end def logger - env['action_dispatch.logger'] || WebConsole.logger + env["action_dispatch.logger"] || WebConsole.logger end def request diff --git a/lib/web_console/whitelist.rb b/lib/web_console/whitelist.rb index f14b228f..25e45c74 100644 --- a/lib/web_console/whitelist.rb +++ b/lib/web_console/whitelist.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'ipaddr' +require "ipaddr" module WebConsole # Whitelist of allowed networks that can access Web Console. @@ -22,7 +22,7 @@ def include?(network) end def to_s - @networks.map(&method(:human_readable_ipaddr)).join(', ') + @networks.map(&method(:human_readable_ipaddr)).join(", ") end private @@ -40,7 +40,7 @@ def coerce_network_to_ipaddr(network) end def human_readable_ipaddr(ipaddr) - ipaddr.to_range.to_s.split('..').uniq.join('/') + ipaddr.to_range.to_s.split("..").uniq.join("/") end end end diff --git a/test/dummy/Rakefile b/test/dummy/Rakefile index 4135d7a4..68b4197d 100644 --- a/test/dummy/Rakefile +++ b/test/dummy/Rakefile @@ -1,6 +1,8 @@ +# frozen_string_literal: true + # 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", __FILE__) Dummy::Application.load_tasks diff --git a/test/dummy/bin/bundle b/test/dummy/bin/bundle index 66e9889e..277e1282 100755 --- a/test/dummy/bin/bundle +++ b/test/dummy/bin/bundle @@ -1,3 +1,5 @@ #!/usr/bin/env ruby -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) -load Gem.bin_path('bundler', 'bundle') +# frozen_string_literal: true + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", __FILE__) +load Gem.bin_path("bundler", "bundle") diff --git a/test/dummy/bin/rails b/test/dummy/bin/rails index 728cd85a..5f1f9b46 100755 --- a/test/dummy/bin/rails +++ b/test/dummy/bin/rails @@ -1,4 +1,6 @@ #!/usr/bin/env ruby -APP_PATH = File.expand_path('../../config/application', __FILE__) -require_relative '../config/boot' -require 'rails/commands' +# frozen_string_literal: true + +APP_PATH = File.expand_path("../../config/application", __FILE__) +require_relative "../config/boot" +require "rails/commands" diff --git a/test/dummy/bin/rake b/test/dummy/bin/rake index 17240489..e436ea54 100755 --- a/test/dummy/bin/rake +++ b/test/dummy/bin/rake @@ -1,4 +1,6 @@ #!/usr/bin/env ruby -require_relative '../config/boot' -require 'rake' +# frozen_string_literal: true + +require_relative "../config/boot" +require "rake" Rake.application.run diff --git a/test/dummy/config.ru b/test/dummy/config.ru index 5bc2a619..5d904bb1 100644 --- a/test/dummy/config.ru +++ b/test/dummy/config.ru @@ -1,4 +1,6 @@ +# frozen_string_literal: true + # 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 Rails.application diff --git a/test/dummy/config/application.rb b/test/dummy/config/application.rb index a885ff3c..b2c09022 100644 --- a/test/dummy/config/application.rb +++ b/test/dummy/config/application.rb @@ -1,13 +1,13 @@ # frozen_string_literal: true -require File.expand_path('../boot', __FILE__) +require File.expand_path("../boot", __FILE__) require "active_model/railtie" require "action_controller/railtie" require "action_view/railtie" Bundler.require(*Rails.groups) -require 'web_console' +require "web_console" module Dummy class Application < Rails::Application diff --git a/test/dummy/config/boot.rb b/test/dummy/config/boot.rb index 18536532..3e9ee5b2 100644 --- a/test/dummy/config/boot.rb +++ b/test/dummy/config/boot.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../../../Gemfile", __FILE__) -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) -$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__) +require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) +$LOAD_PATH.unshift File.expand_path("../../../../lib", __FILE__) diff --git a/test/dummy/config/environment.rb b/test/dummy/config/environment.rb index d1dc305a..46ff5d9c 100644 --- a/test/dummy/config/environment.rb +++ b/test/dummy/config/environment.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Load the rails application. -require File.expand_path('../application', __FILE__) +require File.expand_path("../application", __FILE__) # Initialize the rails application. Dummy::Application.initialize! diff --git a/test/dummy/config/initializers/secret_token.rb b/test/dummy/config/initializers/secret_token.rb index 35005673..4c9273d5 100644 --- a/test/dummy/config/initializers/secret_token.rb +++ b/test/dummy/config/initializers/secret_token.rb @@ -11,4 +11,4 @@ # Make sure your secret_key_base is kept private # if you're sharing your code publicly. -Dummy::Application.config.secret_key_base = '97a4619f221e596a6987a3e85838e6c65f225096496e0b01a52f4901e26339755682845a1c315969bb33ae8ebe1e3bedc698ec75ad4eb0c4c3dc9bd2338b1adf' +Dummy::Application.config.secret_key_base = "97a4619f221e596a6987a3e85838e6c65f225096496e0b01a52f4901e26339755682845a1c315969bb33ae8ebe1e3bedc698ec75ad4eb0c4c3dc9bd2338b1adf" diff --git a/test/dummy/config/initializers/session_store.rb b/test/dummy/config/initializers/session_store.rb index ba27628a..fa158b8d 100644 --- a/test/dummy/config/initializers/session_store.rb +++ b/test/dummy/config/initializers/session_store.rb @@ -2,4 +2,4 @@ # Be sure to restart your server when you modify this file. -Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' +Dummy::Application.config.session_store :cookie_store, key: "_dummy_session" diff --git a/test/support/scenarios/bad_custom_error_scenario.rb b/test/support/scenarios/bad_custom_error_scenario.rb index 624f7a15..db330cc0 100644 --- a/test/support/scenarios/bad_custom_error_scenario.rb +++ b/test/support/scenarios/bad_custom_error_scenario.rb @@ -16,4 +16,3 @@ def call end end end - diff --git a/test/support/scenarios/basic_nested_scenario.rb b/test/support/scenarios/basic_nested_scenario.rb index e8f718d2..5c1c17c0 100644 --- a/test/support/scenarios/basic_nested_scenario.rb +++ b/test/support/scenarios/basic_nested_scenario.rb @@ -10,8 +10,8 @@ def call private - def raise_an_error - raise - end + def raise_an_error + raise + end end end diff --git a/test/support/scenarios/eval_nested_scenario.rb b/test/support/scenarios/eval_nested_scenario.rb index 2ab0485d..b9c15e66 100644 --- a/test/support/scenarios/eval_nested_scenario.rb +++ b/test/support/scenarios/eval_nested_scenario.rb @@ -10,8 +10,8 @@ def call private - def raise_an_error_in_eval - eval 'raise', binding, __FILE__, __LINE__ - end + def raise_an_error_in_eval + eval "raise", binding, __FILE__, __LINE__ + end end end diff --git a/test/support/scenarios/reraised_scenario.rb b/test/support/scenarios/reraised_scenario.rb index 41defaf7..9d04b925 100644 --- a/test/support/scenarios/reraised_scenario.rb +++ b/test/support/scenarios/reraised_scenario.rb @@ -10,14 +10,14 @@ def call private - def raise_an_error_in_eval - method_that_raises - rescue => exc - raise exc - end + def raise_an_error_in_eval + method_that_raises + rescue => exc + raise exc + end - def method_that_raises - raise - end + def method_that_raises + raise + end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 32c5d43c..b7da21f3 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true case RUBY_ENGINE -when 'ruby', 'rbx' - require 'simplecov' - SimpleCov.start 'rails' +when "ruby", "rbx" + require "simplecov" + SimpleCov.start "rails" end # Configure Rails Environment @@ -63,7 +63,7 @@ def capture(stream) yield stream_io.rewind - return captured_stream.read + captured_stream.read ensure captured_stream.close captured_stream.unlink @@ -77,7 +77,7 @@ def capture(stream) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) end -require 'mocha/mini_test' +require "mocha/mini_test" module External def self.exception diff --git a/test/web_console/context_test.rb b/test/web_console/context_test.rb index 8e60037c..8d21fdcd 100644 --- a/test/web_console/context_test.rb +++ b/test/web_console/context_test.rb @@ -1,34 +1,34 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class ContextTest < ActiveSupport::TestCase - test '#extract(empty) includes local variables' do - local_var = 'local' + test "#extract(empty) includes local variables" do + local_var = "local" assert context(binding).include?(:local_var) end - test '#extract(empty) includes instance variables' do - @instance_var = 'instance' + test "#extract(empty) includes instance variables" do + @instance_var = "instance" assert context(binding).include?(:@instance_var) end - test '#extract(empty) includes global variables' do - $global_var = 'global' + test "#extract(empty) includes global variables" do + $global_var = "global" assert context(binding).include?(:$global_var) end - test '#extract(obj) returns methods' do - assert context(binding, 'Rails').include?('Rails.root') + test "#extract(obj) returns methods" do + assert context(binding, "Rails").include?("Rails.root") end - test '#extract(obj) returns constants' do - assert context(binding, 'WebConsole').include?('WebConsole::Middleware') + test "#extract(obj) returns constants" do + assert context(binding, "WebConsole").include?("WebConsole::Middleware") end private - def context(b, o = '') + def context(b, o = "") Context.new(b).extract(o).flatten end end diff --git a/test/web_console/evaluator_test.rb b/test/web_console/evaluator_test.rb index 17161d48..c5b603c8 100644 --- a/test/web_console/evaluator_test.rb +++ b/test/web_console/evaluator_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class EvaluatorTest < ActiveSupport::TestCase @@ -24,21 +24,21 @@ def backtrace @repl2 = Evaluator.new end - test 'sending input returns the result as output' do - assert_equal "=> 42\n", @repl.eval('foo = 42') + test "sending input returns the result as output" do + assert_equal "=> 42\n", @repl.eval("foo = 42") end - test 'preserves the session in the binding' do - assert_equal "=> 42\n", @repl.eval('foo = 42') - assert_equal "=> 50\n", @repl.eval('foo + 8') + test "preserves the session in the binding" do + assert_equal "=> 42\n", @repl.eval("foo = 42") + assert_equal "=> 50\n", @repl.eval("foo + 8") end - test 'session preservation requires same bindings' do - assert_equal "=> 42\n", @repl1.eval('foo = 42') - assert_equal "=> 42\n", @repl2.eval('foo') + test "session preservation requires same bindings" do + assert_equal "=> 42\n", @repl1.eval("foo = 42") + assert_equal "=> 42\n", @repl2.eval("foo") end - test 'formats exceptions similarly to IRB' do + test "formats exceptions similarly to IRB" do repl = Evaluator.new(binding) assert_equal <<-END.strip_heredoc, repl.eval("raise TestError, 'panic'") @@ -48,7 +48,7 @@ def backtrace END end - test 'no backtrace is shown if exception backtrace is blank' do + test "no backtrace is shown if exception backtrace is blank" do repl = Evaluator.new(binding) assert_equal <<-END.strip_heredoc, repl.eval("raise BadlyDefinedError") @@ -56,12 +56,12 @@ def backtrace END end - test 'Evaluator callers are cleaned up of unneeded backtraces', only: :ruby do + test "Evaluator callers are cleaned up of unneeded backtraces", only: :ruby do # Those have to be on the same line to get the same trace. repl, trace = Evaluator.new(binding), current_trace - assert_equal <<-END.strip_heredoc, repl.eval("raise") - RuntimeError: + assert_equal <<-END.strip_heredoc, repl.eval("raise 'oops'") + RuntimeError: oops \tfrom #{trace} END end diff --git a/test/web_console/exception_mapper_test.rb b/test/web_console/exception_mapper_test.rb index 5f0aec61..85da22c8 100644 --- a/test/web_console/exception_mapper_test.rb +++ b/test/web_console/exception_mapper_test.rb @@ -1,29 +1,29 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class ExcetionMapperTest < ActiveSupport::TestCase - test '#first tries to find the first application binding' do + test "#first tries to find the first application binding" do Rails.stubs(:root).returns Pathname(__FILE__).parent mapper = ExceptionMapper.new(External.exception) - assert_equal __FILE__, mapper.first.eval('__FILE__') + assert_equal __FILE__, mapper.first.eval("__FILE__") end - test '.[] tries match the binding for trace index' do + test ".[] tries match the binding for trace index" do exception = External.exception mapper = ExceptionMapper.new(exception) last_index = exception.backtrace.count - 1 - file, line = exception.backtrace.last.split(':') + file, line = exception.backtrace.last.split(":") - assert_equal file, mapper[last_index].eval('__FILE__') - assert_equal line.to_i, mapper[last_index].eval('__LINE__') + assert_equal file, mapper[last_index].eval("__FILE__") + assert_equal line.to_i, mapper[last_index].eval("__LINE__") end - test '.[] fall backs to index if no trace can be found' do + test ".[] fall backs to index if no trace can be found" do exception = External.exception mapper = ExceptionMapper.new(exception) diff --git a/test/web_console/extensions_test.rb b/test/web_console/extensions_test.rb index 3425555d..f52ed4ce 100644 --- a/test/web_console/extensions_test.rb +++ b/test/web_console/extensions_test.rb @@ -1,30 +1,30 @@ # frozen_string_literal: true -require 'test_helper' -require 'web_console/extensions' +require "test_helper" +require "web_console/extensions" module ActionDispatch class DebugExceptionsTest < ActionDispatch::IntegrationTest class Application def call(env) - ActionView::Base.new.render(inline: '<% @ivar = 42 %> <%= nil.raise %> <%= nil.raise %> true, - 'action_dispatch.show_exceptions' => true, - 'action_dispatch.logger' => Logger.new(StringIO.new) + "action_dispatch.show_detailed_exceptions" => true, + "action_dispatch.show_exceptions" => true, + "action_dispatch.logger" => Logger.new(StringIO.new) } - assert_equal 42, Thread.current[:__web_console_exception].bindings.first.eval('@ivar') + assert_equal 42, Thread.current[:__web_console_exception].bindings.first.eval("@ivar") end end end diff --git a/test/web_console/helper_test.rb b/test/web_console/helper_test.rb index e6007d57..a2bb4b18 100644 --- a/test/web_console/helper_test.rb +++ b/test/web_console/helper_test.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class HelperTest < ActionDispatch::IntegrationTest class BaseApplication def call(env) - [ status, headers, body ] + [ status, headers, body ] end private @@ -20,7 +20,7 @@ def status end def headers - { 'Content-Type' => "#{Mime[:html]}; charset=utf-8" } + { "Content-Type" => "#{Mime[:html]}; charset=utf-8" } end def body @@ -62,30 +62,30 @@ def call(env) Thread.current[:__web_console_exception] = nil Thread.current[:__web_console_binding] = nil - Request.stubs(:whitelisted_ips).returns(IPAddr.new('0.0.0.0/0')) + Request.stubs(:whitelisted_ips).returns(IPAddr.new("0.0.0.0/0")) @app = Middleware.new(SingleConsoleApplication.new) end - test 'renders a console into a view' do - get '/', params: nil, headers: { 'CONTENT_TYPE' => 'text/html' } + test "renders a console into a view" do + get "/", params: nil, headers: { "CONTENT_TYPE" => "text/html" } - assert_select '#console' + assert_select "#console" end - test 'raises an error when trying to spawn a console more than once' do + test "raises an error when trying to spawn a console more than once" do @app = Middleware.new(MultipleConsolesApplication.new) assert_raises(DoubleRenderError) do - get '/', params: nil, headers: { 'CONTENT_TYPE' => 'text/html' } + get "/", params: nil, headers: { "CONTENT_TYPE" => "text/html" } end end test "doesn't hijack current view" do - get '/', params: nil, headers: { 'CONTENT_TYPE' => 'text/html' } + get "/", params: nil, headers: { "CONTENT_TYPE" => "text/html" } - assert_select '#hello-world' - assert_select '#console' + assert_select "#hello-world" + assert_select "#console" end end end diff --git a/test/web_console/integration_test.rb b/test/web_console/integration_test.rb index 9ad553a6..b854837b 100644 --- a/test/web_console/integration_test.rb +++ b/test/web_console/integration_test.rb @@ -1,46 +1,46 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class IntegrationTest < ActiveSupport::TestCase - test 'Exception#bindings returns all the bindings of where the error originated' do + test "Exception#bindings returns all the bindings of where the error originated" do exc = FlatScenario.new.call - assert_equal 6, exc.bindings.first.eval('__LINE__') + assert_equal 6, exc.bindings.first.eval("__LINE__") end - test 'Exception#bindings returns all the bindings for a custom error' do + test "Exception#bindings returns all the bindings for a custom error" do exc = CustomErrorScenario.new.call - assert_equal 8, exc.bindings.first.eval('__LINE__') + assert_equal 8, exc.bindings.first.eval("__LINE__") end - test 'Exception#bindings returns all the bindings for a bad custom error' do + test "Exception#bindings returns all the bindings for a bad custom error" do exc = BadCustomErrorScenario.new.call - assert_equal 13, exc.bindings.first.eval('__LINE__') + assert_equal 13, exc.bindings.first.eval("__LINE__") end - test 'Exception#bindings goes down the stack' do + test "Exception#bindings goes down the stack" do exc = BasicNestedScenario.new.call - assert_equal 14, exc.bindings.first.eval('__LINE__') + assert_equal 14, exc.bindings.first.eval("__LINE__") end - test 'Exception#bindings inside of an eval' do + test "Exception#bindings inside of an eval" do exc = EvalNestedScenario.new.call - assert_equal 14, exc.bindings.first.eval('__LINE__') + assert_equal 14, exc.bindings.first.eval("__LINE__") end test "re-raising doesn't lose Exception#bindings information" do exc = ReraisedScenario.new.call - assert_equal 6, exc.bindings.first.eval('__LINE__') + assert_equal 6, exc.bindings.first.eval("__LINE__") end - test 'Exception#bindings is empty when exception is still not raised' do + test "Exception#bindings is empty when exception is still not raised" do exc = RuntimeError.new assert_equal [], exc.bindings diff --git a/test/web_console/middleware_test.rb b/test/web_console/middleware_test.rb index 2e80b1dc..df3166c4 100644 --- a/test/web_console/middleware_test.rb +++ b/test/web_console/middleware_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class MiddlewareTest < ActionDispatch::IntegrationTest @@ -34,7 +34,7 @@ def status def headers if @response_content_type - { 'Content-Type' => "#{@response_content_type}; charset=utf-8" } + { "Content-Type" => "#{@response_content_type}; charset=utf-8" } else {} end @@ -45,77 +45,77 @@ def headers Thread.current[:__web_console_exception] = nil Thread.current[:__web_console_binding] = nil Rails.stubs(:root).returns Pathname(__FILE__).parent - Request.stubs(:whitelisted_ips).returns(IPAddr.new('0.0.0.0/0')) + Request.stubs(:whitelisted_ips).returns(IPAddr.new("0.0.0.0/0")) - Middleware.mount_point = '' + Middleware.mount_point = "" @app = Middleware.new(Application.new) end - test 'render console in an html application from web_console.binding' do + test "render console in an html application from web_console.binding" do Thread.current[:__web_console_binding] = binding - get '/', params: nil + get "/", params: nil - assert_select '#console' + assert_select "#console" end - test 'render console in an html application from web_console.exception' do + test "render console in an html application from web_console.exception" do Thread.current[:__web_console_exception] = raise_exception - get '/', params: nil + get "/", params: nil - assert_select 'body > #console' + assert_select "body > #console" end - test 'render error_page.js from web_console.exception' do + test "render error_page.js from web_console.exception" do Thread.current[:__web_console_exception] = raise_exception - get '/', params: nil + get "/", params: nil - assert_select 'body > script[data-template=error_page]' + assert_select "body > script[data-template=error_page]" end - test 'render console if response format is HTML' do + test "render console if response format is HTML" do Thread.current[:__web_console_binding] = binding @app = Middleware.new(Application.new(response_content_type: Mime[:html])) - get '/', params: nil + get "/", params: nil - assert_select '#console' + assert_select "#console" end - test 'it closes original body if rendering console' do + test "it closes original body if rendering console" do Thread.current[:__web_console_binding] = binding - inner_app = Application.new(response_content_type: Mime[:html]); + inner_app = Application.new(response_content_type: Mime[:html]) @app = Middleware.new(inner_app) - get '/', params: nil + get "/", params: nil assert(inner_app.body.closed?, "body should be closed") end - test 'does not render console if response format is empty' do + test "does not render console if response format is empty" do Thread.current[:__web_console_binding] = binding @app = Middleware.new(Application.new(response_content_type: nil)) - get '/', params: nil + get "/", params: nil - assert_select '#console', 0 + assert_select "#console", 0 end - test 'does not render console if response format is not HTML' do + test "does not render console if response format is not HTML" do Thread.current[:__web_console_binding] = binding @app = Middleware.new(Application.new(response_content_type: Mime[:json])) - get '/', params: nil + get "/", params: nil - assert_select '#console', 0 + assert_select "#console", 0 end - test 'returns X-Web-Console-Session-Id as response header' do + test "returns X-Web-Console-Session-Id as response header" do Thread.current[:__web_console_binding] = binding - get '/', params: nil + get "/", params: nil session_id = response.headers["X-Web-Console-Session-Id"] @@ -126,77 +126,77 @@ def headers Thread.current[:__web_console_binding] = binding @app = Middleware.new(Application.new(response_content_type: Mime[:json])) - get '/', params: nil + get "/", params: nil - assert_select '#console', 0 + assert_select "#console", 0 end test "doesn't render console from non whitelisted IP" do Thread.current[:__web_console_binding] = binding - Request.stubs(:whitelisted_ips).returns(IPAddr.new('127.0.0.1')) + Request.stubs(:whitelisted_ips).returns(IPAddr.new("127.0.0.1")) silence(:stderr) do - get '/', params: nil, headers: { 'REMOTE_ADDR' => '1.1.1.1' } + get "/", params: nil, headers: { "REMOTE_ADDR" => "1.1.1.1" } end - assert_select '#console', 0 + assert_select "#console", 0 end test "doesn't render console without a web_console.binding or web_console.exception" do - get '/', params: nil + get "/", params: nil - assert_select '#console', 0 + assert_select "#console", 0 end - test 'can evaluate code and return it as a JSON' do + test "can evaluate code and return it as a JSON" do session, line = Session.new([binding]), __LINE__ Session.stubs(:from).returns(session) - get '/', params: nil - put "/repl_sessions/#{session.id}", xhr: true, params: { input: '__LINE__' } + get "/", params: nil + put "/repl_sessions/#{session.id}", xhr: true, params: { input: "__LINE__" } assert_equal("=> #{line}\n", JSON.parse(response.body)["output"]) end - test 'can switch bindings on error pages' do + test "can switch bindings on error pages" do session = Session.new(raise_exception.bindings) Session.stubs(:from).returns(session) - get '/', params: nil + get "/", params: nil post "/repl_sessions/#{session.id}/trace", xhr: true, params: { frame_id: 1 } assert_equal({ ok: true }.to_json, response.body) end - test 'can be changed mount point' do - Middleware.mount_point = '/customized/path' + test "can be changed mount point" do + Middleware.mount_point = "/customized/path" session, line = Session.new([binding]), __LINE__ - put "/customized/path/repl_sessions/#{session.id}", params: { input: '__LINE__' }, xhr: true + put "/customized/path/repl_sessions/#{session.id}", params: { input: "__LINE__" }, xhr: true assert_equal("=> #{line}\n", JSON.parse(response.body)["output"]) end - test 'can return context information by passing a context param' do - hello = 'world' + test "can return context information by passing a context param" do + hello = "world" session = Session.new([binding]) Session.stubs(:from).returns(session) - get '/' - put "/repl_sessions/#{session.id}", xhr: true, params: { context: '' } + get "/" + put "/repl_sessions/#{session.id}", xhr: true, params: { context: "" } assert_includes(JSON.parse(response.body)["context"], local_variables.map(&:to_s)) end - test 'unavailable sessions respond to the user with a message' do - put '/repl_sessions/no_such_session', xhr: true, params: { input: '__LINE__' } + test "unavailable sessions respond to the user with a message" do + put "/repl_sessions/no_such_session", xhr: true, params: { input: "__LINE__" } assert_equal(404, response.status) end - test 'unavailable sessions can occur on binding switch' do + test "unavailable sessions can occur on binding switch" do post "/repl_sessions/no_such_session/trace", xhr: true, params: { frame_id: 1 } assert_equal(404, response.status) @@ -204,26 +204,26 @@ def headers test "doesn't accept request for old version and return 406" do put "/repl_sessions/no_such_session", xhr: true, params: { input: "__LINE__" }, - headers: {"HTTP_ACCEPT" => "application/vnd.web-console.v0"} + headers: { "HTTP_ACCEPT" => "application/vnd.web-console.v0" } assert_equal(406, response.status) end - test 'reraises application errors' do + test "reraises application errors" do @app = proc { raise } - assert_raises(RuntimeError) { get '/' } + assert_raises(RuntimeError) { get "/" } end - test 'logs internal errors with Rails.logger' do + test "logs internal errors with Rails.logger" do io = StringIO.new logger = ActiveSupport::Logger.new(io) old_logger, Rails.logger = Rails.logger, logger begin - @app.stubs(:call_app).raises('whoops') + @app.stubs(:call_app).raises("whoops") - get '/' + get "/" rescue RuntimeError output = io.rewind && io.read lines = output.lines @@ -249,7 +249,7 @@ def post(http_method, path, *args) def update_path_args(path) unless path[:headers] - path.merge!(headers: { 'HTTP_ACCEPT' => Mime[:web_console_v2] }) + path.merge!(headers: { "HTTP_ACCEPT" => Mime[:web_console_v2] }) end end diff --git a/test/web_console/railtie_test.rb b/test/web_console/railtie_test.rb index c04083e1..17aef6b2 100644 --- a/test/web_console/railtie_test.rb +++ b/test/web_console/railtie_test.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class RailtieTest < ActiveSupport::TestCase setup do Railtie.any_instance.stubs(:abort) - Middleware.mount_point = '/__web_console' + Middleware.mount_point = "/__web_console" end - test 'config.whitelisted_ips sets whitelisted networks' do + test "config.whitelisted_ips sets whitelisted networks" do new_uninitialized_app do |app| app.config.web_console.whitelisted_ips = %w( 172.16.0.0/12 192.168.0.0/16 ) app.initialize! @@ -21,20 +21,20 @@ class RailtieTest < ActiveSupport::TestCase end end - test 'config.whitelisted_ips always includes localhost' do + test "config.whitelisted_ips always includes localhost" do new_uninitialized_app do |app| - app.config.web_console.whitelisted_ips = '8.8.8.8' + app.config.web_console.whitelisted_ips = "8.8.8.8" app.initialize! - assert_includes Request.whitelisted_ips, '127.0.0.1' - assert_includes Request.whitelisted_ips, '::1' - assert_includes Request.whitelisted_ips, '8.8.8.8' + assert_includes Request.whitelisted_ips, "127.0.0.1" + assert_includes Request.whitelisted_ips, "::1" + assert_includes Request.whitelisted_ips, "8.8.8.8" end end - test 'config.template_paths prepend paths if it exists' do + test "config.template_paths prepend paths if it exists" do new_uninitialized_app do |app| - dirname = File.expand_path('..', __FILE__) + dirname = File.expand_path("..", __FILE__) app.config.web_console.template_paths = dirname app.initialize! @@ -43,35 +43,35 @@ class RailtieTest < ActiveSupport::TestCase end end - test 'config.mount_point changes the mount point of Middleware' do + test "config.mount_point changes the mount point of Middleware" do new_uninitialized_app do |app| - app.config.web_console.mount_point = '/customized/path' + app.config.web_console.mount_point = "/customized/path" app.initialize! - assert_equal '/customized/path', Middleware.mount_point + assert_equal "/customized/path", Middleware.mount_point end end - test 'config.mount_point supports the relative url root' do + test "config.mount_point supports the relative url root" do new_uninitialized_app do |app| - app.config.relative_url_root = '/relative/path' + app.config.relative_url_root = "/relative/path" app.initialize! - assert_equal '/relative/path/__web_console', Middleware.mount_point + assert_equal "/relative/path/__web_console", Middleware.mount_point end end - test 'config.mount_point inserts after the relative url root' do + test "config.mount_point inserts after the relative url root" do new_uninitialized_app do |app| - app.config.web_console.mount_point = '/customized/path' - app.config.relative_url_root = '/relative/path' + app.config.web_console.mount_point = "/customized/path" + app.config.relative_url_root = "/relative/path" app.initialize! - assert_equal '/relative/path/customized/path', Middleware.mount_point + assert_equal "/relative/path/customized/path", Middleware.mount_point end end - test 'config.whiny_request removes extra logging' do + test "config.whiny_request removes extra logging" do new_uninitialized_app do |app| app.config.web_console.whiny_requests = false app.initialize! @@ -80,7 +80,7 @@ class RailtieTest < ActiveSupport::TestCase end end - test 'config.development_only prevents usage outside of development' do + test "config.development_only prevents usage outside of development" do Railtie.any_instance.expects(:abort) new_uninitialized_app do |app| @@ -90,7 +90,7 @@ class RailtieTest < ActiveSupport::TestCase end end - test 'config.development_only can be used to allow non-development usage' do + test "config.development_only can be used to allow non-development usage" do Rails.env.stubs(:development?).returns(true) new_uninitialized_app do |app| @@ -102,7 +102,7 @@ class RailtieTest < ActiveSupport::TestCase private - def new_uninitialized_app(root = File.expand_path('../../dummy', __FILE__)) + def new_uninitialized_app(root = File.expand_path("../../dummy", __FILE__)) old_app = Rails.application FileUtils.mkdir_p(root) @@ -112,7 +112,7 @@ def new_uninitialized_app(root = File.expand_path('../../dummy', __FILE__)) app = Class.new(Rails::Application) app.config.web_console = ActiveSupport::OrderedOptions.new app.config.eager_load = false - app.config.time_zone = 'UTC' + app.config.time_zone = "UTC" app.config.middleware ||= Rails::Configuration::MiddlewareStackProxy.new app.config.active_support.deprecation = :notify diff --git a/test/web_console/request_test.rb b/test/web_console/request_test.rb index efc66bb0..cf03b5c2 100644 --- a/test/web_console/request_test.rb +++ b/test/web_console/request_test.rb @@ -1,63 +1,63 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class RequestTest < ActiveSupport::TestCase setup do - Request.stubs(:whitelisted_ips).returns(IPAddr.new('127.0.0.1')) + Request.stubs(:whitelisted_ips).returns(IPAddr.new("127.0.0.1")) end - test '#from_whitelisted_ip? is falsy for blacklisted IPs' do - req = request('http://example.com', 'REMOTE_ADDR' => '0.0.0.0') + test "#from_whitelisted_ip? is falsy for blacklisted IPs" do + req = request("http://example.com", "REMOTE_ADDR" => "0.0.0.0") assert_not req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is truthy for whitelisted IPs' do - req = request('http://example.com', 'REMOTE_ADDR' => '127.0.0.1') + test "#from_whitelisted_ip? is truthy for whitelisted IPs" do + req = request("http://example.com", "REMOTE_ADDR" => "127.0.0.1") assert req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is truthy for whitelisted IPs via whitelisted proxies' do - req = request('http://example.com', 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '127.0.0.0') + test "#from_whitelisted_ip? is truthy for whitelisted IPs via whitelisted proxies" do + req = request("http://example.com", "REMOTE_ADDR" => "127.0.0.1", "HTTP_X_FORWARDED_FOR" => "127.0.0.0") assert req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is falsy for blacklisted IPs via whitelisted proxies' do - req = request('http://example.com', 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '0.0.0.0') + test "#from_whitelisted_ip? is falsy for blacklisted IPs via whitelisted proxies" do + req = request("http://example.com", "REMOTE_ADDR" => "127.0.0.1", "HTTP_X_FORWARDED_FOR" => "0.0.0.0") assert_not req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is falsy for lying blacklisted IPs via whitelisted proxies' do - req = request('http://example.com', 'REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '10.0.0.0, 127.0.0.0') + test "#from_whitelisted_ip? is falsy for lying blacklisted IPs via whitelisted proxies" do + req = request("http://example.com", "REMOTE_ADDR" => "127.0.0.1", "HTTP_X_FORWARDED_FOR" => "10.0.0.0, 127.0.0.0") assert_not req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is falsy for whitelisted IPs via blacklisted proxies' do - req = request('http://example.com', 'REMOTE_ADDR' => '10.0.0.0', 'HTTP_X_FORWARDED_FOR' => '127.0.0.0') + test "#from_whitelisted_ip? is falsy for whitelisted IPs via blacklisted proxies" do + req = request("http://example.com", "REMOTE_ADDR" => "10.0.0.0", "HTTP_X_FORWARDED_FOR" => "127.0.0.0") assert_not req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is falsy for spoofed IPs' do - req = request('http://example.com', 'HTTP_CLIENT_IP' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '127.0.0.0') + test "#from_whitelisted_ip? is falsy for spoofed IPs" do + req = request("http://example.com", "HTTP_CLIENT_IP" => "127.0.0.1", "HTTP_X_FORWARDED_FOR" => "127.0.0.0") assert_not req.from_whitelisted_ip? end - test '#acceptable? is truthy for current version' do - req = xhr('http://example.com', 'HTTP_ACCEPT' => "#{Mime[:web_console_v2]}") + test "#acceptable? is truthy for current version" do + req = xhr("http://example.com", "HTTP_ACCEPT" => "#{Mime[:web_console_v2]}") assert req.acceptable? end - test '#acceptable? is falsy for request without vendor mime type' do - req = xhr('http://example.com', 'HTTP_ACCEPT' => 'text/plain; charset=utf-8') + test "#acceptable? is falsy for request without vendor mime type" do + req = xhr("http://example.com", "HTTP_ACCEPT" => "text/plain; charset=utf-8") assert_not req.acceptable? end @@ -73,7 +73,7 @@ def mock_env(*args) end def xhr(*args) - args[1]['HTTP_X_REQUESTED_WITH'] ||= 'XMLHttpRequest' + args[1]["HTTP_X_REQUESTED_WITH"] ||= "XMLHttpRequest" request(*args) end end diff --git a/test/web_console/session_test.rb b/test/web_console/session_test.rb index 30e41671..1de474ff 100644 --- a/test/web_console/session_test.rb +++ b/test/web_console/session_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class SessionTest < ActiveSupport::TestCase @@ -23,24 +23,24 @@ def initialize(line) @session = Session.new([binding]) end - test 'returns nil when a session is not found' do + test "returns nil when a session is not found" do assert_nil Session.find("nonexistent session") end - test 'find returns a persisted object' do + test "find returns a persisted object" do assert_equal @session, Session.find(@session.id) end - test 'can evaluate code in the currently selected binding' do - assert_equal "=> 42\n", @session.eval('40 + 2') + test "can evaluate code in the currently selected binding" do + assert_equal "=> 42\n", @session.eval("40 + 2") end - test 'use first binding if no application bindings' do + test "use first binding if no application bindings" do binding = Object.new.instance_eval do def eval(string) case string - when '__FILE__' then framework - when 'called?' then 'yes' + when "__FILE__" then framework + when "called?" then "yes" end end @@ -48,42 +48,42 @@ def eval(string) end session = Session.new([binding]) - assert_equal session.eval('called?'), "=> \"yes\"\n" + assert_equal session.eval("called?"), "=> \"yes\"\n" end - test '#from can create session from a single binding' do + test "#from can create session from a single binding" do saved_line, saved_binding = __LINE__, binding Thread.current[:__web_console_binding] = saved_binding session = Session.from(__web_console_binding: saved_binding) - assert_equal "=> #{saved_line}\n", session.eval('__LINE__') + assert_equal "=> #{saved_line}\n", session.eval("__LINE__") end - test '#from can create session from an exception' do + test "#from can create session from an exception" do exc = LineAwareError.raise session = Session.from(__web_console_exception: exc) - assert_equal "=> #{exc.line}\n", session.eval('__LINE__') + assert_equal "=> #{exc.line}\n", session.eval("__LINE__") end - test '#from can switch to bindings' do + test "#from can switch to bindings" do exc, saved_line = LineAwareError.raise, __LINE__ session = Session.from(__web_console_exception: exc) session.switch_binding_to(1) - assert_equal "=> #{saved_line}\n", session.eval('__LINE__') + assert_equal "=> #{saved_line}\n", session.eval("__LINE__") end - test '#from prioritizes exceptions over bindings' do + test "#from prioritizes exceptions over bindings" do exc, saved_line = LineAwareError.raise, __LINE__ session = Session.from(__web_console_exception: exc, __web_console_binding: binding) session.switch_binding_to(1) - assert_equal "=> #{saved_line}\n", session.eval('__LINE__') + assert_equal "=> #{saved_line}\n", session.eval("__LINE__") end end end diff --git a/test/web_console/whiny_request_test.rb b/test/web_console/whiny_request_test.rb index d95862d1..6d28ed1e 100644 --- a/test/web_console/whiny_request_test.rb +++ b/test/web_console/whiny_request_test.rb @@ -1,20 +1,20 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class WhinyRequestTest < ActiveSupport::TestCase - test '#from_whitelisted_ip? logs out to stderr' do - Request.stubs(:whitelisted_ips).returns(IPAddr.new('127.0.0.1')) + test "#from_whitelisted_ip? logs out to stderr" do + Request.stubs(:whitelisted_ips).returns(IPAddr.new("127.0.0.1")) WebConsole.logger.expects(:info) - req = request('http://example.com', 'REMOTE_ADDR' => '0.0.0.0') + req = request("http://example.com", "REMOTE_ADDR" => "0.0.0.0") assert_not req.from_whitelisted_ip? end - test '#from_whitelisted_ip? is falsy for spoofed IPs' do + test "#from_whitelisted_ip? is falsy for spoofed IPs" do WebConsole.logger.expects(:info) - req = request('http://example.com', 'HTTP_CLIENT_IP' => '127.0.0.1', 'HTTP_X_FORWARDED_FOR' => '127.0.0.0') + req = request("http://example.com", "HTTP_CLIENT_IP" => "127.0.0.1", "HTTP_X_FORWARDED_FOR" => "127.0.0.0") assert_not req.from_whitelisted_ip? end diff --git a/test/web_console/whitelist_test.rb b/test/web_console/whitelist_test.rb index b04e0194..a41da6ce 100644 --- a/test/web_console/whitelist_test.rb +++ b/test/web_console/whitelist_test.rb @@ -1,31 +1,31 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module WebConsole class WhitelistTest < ActiveSupport::TestCase - test 'localhost is always whitelisted' do - whitelisted_ips = whitelist('8.8.8.8') + test "localhost is always whitelisted" do + whitelisted_ips = whitelist("8.8.8.8") - assert_includes whitelisted_ips, '127.0.0.1' - assert_includes whitelisted_ips, '::1' + assert_includes whitelisted_ips, "127.0.0.1" + assert_includes whitelisted_ips, "::1" end - test 'can whitelist single IPs' do - whitelisted_ips = whitelist('8.8.8.8') + test "can whitelist single IPs" do + whitelisted_ips = whitelist("8.8.8.8") - assert_includes whitelisted_ips, '8.8.8.8' + assert_includes whitelisted_ips, "8.8.8.8" end - test 'can whitelist whole networks' do - whitelisted_ips = whitelist('172.16.0.0/12') + test "can whitelist whole networks" do + whitelisted_ips = whitelist("172.16.0.0/12") 1.upto(255).each do |n| assert_includes whitelisted_ips, "172.16.0.#{n}" end end - test 'can whitelist multiple networks' do + test "can whitelist multiple networks" do whitelisted_ips = whitelist %w(172.16.0.0/12 192.168.0.0/16) 1.upto(255).each do |n| @@ -33,15 +33,15 @@ class WhitelistTest < ActiveSupport::TestCase assert_includes whitelisted_ips, "192.168.0.#{n}" end end - - test 'ignore an unix socket' do - whitelisted_ips = whitelist('8.8.8.8') - assert_not_includes whitelisted_ips, 'unix:' + test "ignore an unix socket" do + whitelisted_ips = whitelist("8.8.8.8") + + assert_not_includes whitelisted_ips, "unix:" end - test 'can be represented in a human readable form' do - assert_includes whitelist.to_s, '127.0.0.0/127.255.255.255, ::1' + test "can be represented in a human readable form" do + assert_includes whitelist.to_s, "127.0.0.0/127.255.255.255, ::1" end private diff --git a/web-console.gemspec b/web-console.gemspec index aca40ea0..b7f80841 100644 --- a/web-console.gemspec +++ b/web-console.gemspec @@ -1,3 +1,5 @@ +# frozen_string_literal: true + $:.push File.expand_path("../lib", __FILE__) require "web_console/version" @@ -9,16 +11,16 @@ Gem::Specification.new do |s| s.email = ["charlie@charliesomerville.com", "gsamokovarov@gmail.com", "guilleiguaran@gmail.com", "daoduyducduong@gmail.com"] s.homepage = "https://github.com/rails/web-console" s.summary = "A debugging tool for your Ruby on Rails applications." - s.license = 'MIT' + s.license = "MIT" - s.files = Dir["lib/**/*", "MIT-LICENSE", "Rakefile", "README.markdown", "CHANGELOG.markdown"] + s.files = Dir["lib/**/*", "MIT-LICENSE", "Rakefile", "README.markdown", "CHANGELOG.markdown"] - s.required_ruby_version = '>= 2.2.2' + s.required_ruby_version = ">= 2.2.2" rails_version = ">= 5.0" s.add_dependency "railties", rails_version s.add_dependency "activemodel", rails_version s.add_dependency "actionview", rails_version - s.add_dependency "bindex", '>= 0.4.0' + s.add_dependency "bindex", ">= 0.4.0" end