From afadabb40a5cabdff8fc91faafb1af8c7be47c0d Mon Sep 17 00:00:00 2001 From: Adrianna Chang Date: Fri, 19 Mar 2021 11:20:51 -0400 Subject: [PATCH] Use double quoted strings (#376) --- .rubocop.yml | 2 +- Gemfile | 22 +-- Rakefile | 32 +-- .../application_controller.rb | 4 +- .../maintenance_tasks/application_helper.rb | 4 +- app/helpers/maintenance_tasks/tasks_helper.rb | 28 +-- app/jobs/maintenance_tasks/task_job.rb | 4 +- .../maintenance_tasks/csv_collection.rb | 2 +- app/models/maintenance_tasks/run.rb | 4 +- app/models/maintenance_tasks/runner.rb | 4 +- app/models/maintenance_tasks/runs_page.rb | 2 +- app/models/maintenance_tasks/task_data.rb | 4 +- .../maintenance_tasks/run_status_validator.rb | 22 +-- bin/rails | 12 +- config/routes.rb | 8 +- exe/maintenance_tasks | 4 +- .../maintenance_tasks/install_generator.rb | 8 +- .../maintenance_tasks/task_generator.rb | 20 +- lib/maintenance_tasks.rb | 22 +-- lib/maintenance_tasks/cli.rb | 6 +- lib/maintenance_tasks/engine.rb | 6 +- maintenance_tasks.gemspec | 36 ++-- test/application_system_test_case.rb | 12 +- test/documentation_test.rb | 8 +- test/dummy/Rakefile | 2 +- .../dummy/app/controllers/posts_controller.rb | 6 +- test/dummy/app/jobs/custom_task_job.rb | 4 +- test/dummy/app/mailers/application_mailer.rb | 4 +- .../dummy/app/tasks/maintenance/error_task.rb | 2 +- .../tasks/maintenance/import_posts_task.rb | 2 +- test/dummy/bin/rails | 6 +- test/dummy/bin/rake | 4 +- test/dummy/bin/setup | 16 +- test/dummy/config.ru | 2 +- test/dummy/config/application.rb | 14 +- test/dummy/config/boot.rb | 6 +- test/dummy/config/environment.rb | 2 +- test/dummy/config/environments/development.rb | 6 +- test/dummy/config/environments/production.rb | 6 +- test/dummy/config/environments/test.rb | 4 +- test/dummy/config/initializers/assets.rb | 2 +- .../initializers/backtrace_silencers.rb | 2 +- test/dummy/config/puma.rb | 10 +- test/dummy/config/routes.rb | 4 +- test/dummy/config/spring.rb | 8 +- ...te_active_storage_tables.active_storage.rb | 4 +- test/dummy/db/seeds.rb | 2 +- .../application_helper_test.rb | 4 +- .../maintenance_tasks/tasks_helper_test.rb | 58 +++--- test/jobs/maintenance_tasks/task_job_test.rb | 104 +++++----- .../install_generator_test.rb | 20 +- .../maintenance_tasks/task_generator_test.rb | 48 ++--- test/lib/maintenance_tasks/cli_test.rb | 38 ++-- test/lib/maintenance_tasks_test.rb | 8 +- .../models/maintenance_tasks/progress_test.rb | 32 +-- test/models/maintenance_tasks/run_test.rb | 120 +++++------ test/models/maintenance_tasks/runner_test.rb | 48 ++--- .../maintenance_tasks/runs_page_test.rb | 14 +- .../maintenance_tasks/task_data_test.rb | 126 ++++++------ test/models/maintenance_tasks/ticker_test.rb | 8 +- test/system/maintenance_tasks/runs_test.rb | 186 +++++++++--------- test/system/maintenance_tasks/tasks_test.rb | 60 +++--- test/tasks/maintenance_tasks/csv_task_test.rb | 14 +- test/tasks/maintenance_tasks/task_test.rb | 50 ++--- test/test_helper.rb | 16 +- .../run_status_validator_test.rb | 68 +++---- 66 files changed, 708 insertions(+), 708 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 187a0333..14ca2e2a 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -24,7 +24,7 @@ Style/DocumentationMethod: - lib/**/*.rb Style/StringLiterals: - EnforcedStyle: single_quotes + EnforcedStyle: double_quotes Style/SymbolArray: EnforcedStyle: brackets diff --git a/Gemfile b/Gemfile index c857d165..4c3d7a4b 100644 --- a/Gemfile +++ b/Gemfile @@ -1,16 +1,16 @@ # frozen_string_literal: true -source 'https://rubygems.org' +source "https://rubygems.org" gemspec -gem 'capybara' -gem 'mocha' -gem 'pry-byebug' -gem 'puma' -gem 'rails' -gem 'rubocop-shopify' -gem 'selenium-webdriver' -gem 'sqlite3' -gem 'webdrivers', require: false -gem 'yard' +gem "capybara" +gem "mocha" +gem "pry-byebug" +gem "puma" +gem "rails" +gem "rubocop-shopify" +gem "selenium-webdriver" +gem "sqlite3" +gem "webdrivers", require: false +gem "yard" diff --git a/Rakefile b/Rakefile index 1cd33b59..72236961 100644 --- a/Rakefile +++ b/Rakefile @@ -1,29 +1,29 @@ # 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 'rdoc/task' +require "rdoc/task" RDoc::Task.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'MaintenanceTasks' - rdoc.options << '--line-numbers' - rdoc.rdoc_files.include('README.md') - rdoc.rdoc_files.include('lib/**/*.rb') + rdoc.rdoc_dir = "rdoc" + rdoc.title = "MaintenanceTasks" + rdoc.options << "--line-numbers" + rdoc.rdoc_files.include("README.md") + rdoc.rdoc_files.include("lib/**/*.rb") end -APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) -load('rails/tasks/engine.rake') +APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__) +load("rails/tasks/engine.rake") -load('rails/tasks/statistics.rake') +load("rails/tasks/statistics.rake") -require 'bundler/gem_tasks' +require "bundler/gem_tasks" -require 'rubocop/rake_task' +require "rubocop/rake_task" RuboCop::RakeTask.new -task(test: 'app:test') -task('test:system' => 'app:test:system') -task(default: ['db:test:prepare', 'test', 'test:system', 'rubocop']) +task(test: "app:test") +task("test:system" => "app:test:system") +task(default: ["db:test:prepare", "test", "test:system", "rubocop"]) diff --git a/app/controllers/maintenance_tasks/application_controller.rb b/app/controllers/maintenance_tasks/application_controller.rb index 56b9e02a..dbe91b44 100644 --- a/app/controllers/maintenance_tasks/application_controller.rb +++ b/app/controllers/maintenance_tasks/application_controller.rb @@ -5,7 +5,7 @@ module MaintenanceTasks # # Can be extended to add different authentication and authorization code. class ApplicationController < ActionController::Base - BULMA_CDN = 'https://cdn.jsdelivr.net' + BULMA_CDN = "https://cdn.jsdelivr.net" content_security_policy do |policy| policy.style_src(BULMA_CDN) @@ -15,7 +15,7 @@ class ApplicationController < ActionController::Base before_action do request.content_security_policy_nonce_generator ||= ->(_request) { SecureRandom.base64(16) } - request.content_security_policy_nonce_directives = ['style-src'] + request.content_security_policy_nonce_directives = ["style-src"] end protect_from_forgery with: :exception diff --git a/app/helpers/maintenance_tasks/application_helper.rb b/app/helpers/maintenance_tasks/application_helper.rb index 352e88b4..f3813932 100644 --- a/app/helpers/maintenance_tasks/application_helper.rb +++ b/app/helpers/maintenance_tasks/application_helper.rb @@ -13,8 +13,8 @@ module ApplicationHelper # @param datetime [ActiveSupport::TimeWithZone] the time to be presented. # @return [String] the HTML to render with the relative datetime in words. def time_ago(datetime) - time_tag(datetime, title: datetime.utc.iso8601, class: 'is-clickable') do - time_ago_in_words(datetime) + ' ago' + time_tag(datetime, title: datetime.utc.iso8601, class: "is-clickable") do + time_ago_in_words(datetime) + " ago" end end end diff --git a/app/helpers/maintenance_tasks/tasks_helper.rb b/app/helpers/maintenance_tasks/tasks_helper.rb index fa0a2a20..a0c8307d 100644 --- a/app/helpers/maintenance_tasks/tasks_helper.rb +++ b/app/helpers/maintenance_tasks/tasks_helper.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'ripper' +require "ripper" module MaintenanceTasks # Helpers for formatting data in the maintenance_tasks views. @@ -8,16 +8,16 @@ module MaintenanceTasks # @api private module TasksHelper STATUS_COLOURS = { - 'new' => ['is-primary'], - 'enqueued' => ['is-primary is-light'], - 'running' => ['is-info'], - 'interrupted' => ['is-info', 'is-light'], - 'pausing' => ['is-warning', 'is-light'], - 'paused' => ['is-warning'], - 'succeeded' => ['is-success'], - 'cancelling' => ['is-light'], - 'cancelled' => ['is-dark'], - 'errored' => ['is-danger'], + "new" => ["is-primary"], + "enqueued" => ["is-primary is-light"], + "running" => ["is-info"], + "interrupted" => ["is-info", "is-light"], + "pausing" => ["is-warning", "is-light"], + "paused" => ["is-warning"], + "succeeded" => ["is-success"], + "cancelling" => ["is-light"], + "cancelled" => ["is-dark"], + "errored" => ["is-danger"], } # Formats a run backtrace. @@ -48,7 +48,7 @@ def progress(run) value: progress.value, max: progress.max, title: progress.title, - class: ['progress'] + STATUS_COLOURS.fetch(run.status) + class: ["progress"] + STATUS_COLOURS.fetch(run.status) ) end @@ -59,7 +59,7 @@ def progress(run) # @return [String] the span element containing the status, with the # appropriate tag class attached. def status_tag(status) - tag.span(status.capitalize, class: ['tag'] + STATUS_COLOURS.fetch(status)) + tag.span(status.capitalize, class: ["tag"] + STATUS_COLOURS.fetch(status)) end # Returns the distance between now and the Run's expected completion time, @@ -100,7 +100,7 @@ def highlight_code(code) when :on_nl, :on_sp, :on_ignored_nl content else - tag.span(content, class: type.to_s.sub('on_', 'ruby-').dasherize) + tag.span(content, class: type.to_s.sub("on_", "ruby-").dasherize) end end safe_join(tokens) diff --git a/app/jobs/maintenance_tasks/task_job.rb b/app/jobs/maintenance_tasks/task_job.rb index 373a48ee..30b4c391 100644 --- a/app/jobs/maintenance_tasks/task_job.rb +++ b/app/jobs/maintenance_tasks/task_job.rb @@ -19,7 +19,7 @@ class << self # Overrides ActiveJob::Exceptions.retry_on to declare it unsupported. # The use of rescue_from prevents retry_on from being usable. def retry_on(*, **) - raise NotImplementedError, 'retry_on is not supported' + raise NotImplementedError, "retry_on is not supported" end end @@ -38,7 +38,7 @@ def build_enumerator(_run, cursor:) JobIteration::CsvEnumerator.new(collection).rows(cursor: cursor) else raise ArgumentError, "#{@task.class.name}#collection must be either "\ - 'an Active Record Relation, Array, or CSV.' + "an Active Record Relation, Array, or CSV." end end diff --git a/app/models/maintenance_tasks/csv_collection.rb b/app/models/maintenance_tasks/csv_collection.rb index 2b2339ce..05c240bb 100644 --- a/app/models/maintenance_tasks/csv_collection.rb +++ b/app/models/maintenance_tasks/csv_collection.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'csv' +require "csv" module MaintenanceTasks # Module that is included into Task classes by Task.csv_collection for diff --git a/app/models/maintenance_tasks/run.rb b/app/models/maintenance_tasks/run.rb index 6d8af229..6d29d4ce 100644 --- a/app/models/maintenance_tasks/run.rb +++ b/app/models/maintenance_tasks/run.rb @@ -192,9 +192,9 @@ def stuck? # if the Run does not meet the above criteria. def csv_attachment_presence if Task.named(task_name) < CsvCollection && !csv_file.attached? - errors.add(:csv_file, 'must be attached to CSV Task.') + errors.add(:csv_file, "must be attached to CSV Task.") elsif !(Task.named(task_name) < CsvCollection) && csv_file.present? - errors.add(:csv_file, 'should not be attached to non-CSV Task.') + errors.add(:csv_file, "should not be attached to non-CSV Task.") end rescue Task::NotFoundError nil diff --git a/app/models/maintenance_tasks/runner.rb b/app/models/maintenance_tasks/runner.rb index f2c3a499..8a68d1e8 100644 --- a/app/models/maintenance_tasks/runner.rb +++ b/app/models/maintenance_tasks/runner.rb @@ -8,7 +8,7 @@ module Runner # @deprecated Use {Runner} directly instead. def new ActiveSupport::Deprecation.warn( - 'Use Runner.run instead of Runner.new.run' + "Use Runner.run instead of Runner.new.run" ) self end @@ -57,7 +57,7 @@ def run(name:, csv_file: nil) def enqueue(run) unless MaintenanceTasks.job.constantize.perform_later(run) raise "The job to perform #{run.task_name} could not be enqueued. "\ - 'Enqueuing has been prevented by a callback.' + "Enqueuing has been prevented by a callback." end rescue => error run.persist_error(error) diff --git a/app/models/maintenance_tasks/runs_page.rb b/app/models/maintenance_tasks/runs_page.rb index 18019530..b8ce4d37 100644 --- a/app/models/maintenance_tasks/runs_page.rb +++ b/app/models/maintenance_tasks/runs_page.rb @@ -28,7 +28,7 @@ def initialize(runs, cursor) def records @records ||= begin runs_after_cursor = if @cursor.present? - @runs.where('id < ?', @cursor) + @runs.where("id < ?", @cursor) else @runs end diff --git a/app/models/maintenance_tasks/task_data.rb b/app/models/maintenance_tasks/task_data.rb index 4d0bb3a7..3daf39dc 100644 --- a/app/models/maintenance_tasks/task_data.rb +++ b/app/models/maintenance_tasks/task_data.rb @@ -41,7 +41,7 @@ def available_tasks task_names = Task.available_tasks.map(&:name) available_task_runs = Run.where(task_name: task_names) last_runs = Run.where( - id: available_task_runs.select('MAX(id) as id').group(:task_name) + id: available_task_runs.select("MAX(id) as id").group(:task_name) ) task_names.map do |task_name| @@ -111,7 +111,7 @@ def deleted? # # @return [String] the Task status. def status - last_run&.status || 'new' + last_run&.status || "new" end # Retrieves the Task's category, which is one of active, new, or completed. diff --git a/app/validators/maintenance_tasks/run_status_validator.rb b/app/validators/maintenance_tasks/run_status_validator.rb index 60c60808..143561d8 100644 --- a/app/validators/maintenance_tasks/run_status_validator.rb +++ b/app/validators/maintenance_tasks/run_status_validator.rb @@ -13,7 +13,7 @@ class RunStatusValidator < ActiveModel::Validator # before starting. # enqueued -> errored occurs when the task job fails to be enqueued, or # if the Task is deleted before is starts running. - 'enqueued' => ['running', 'pausing', 'cancelling', 'errored'], + "enqueued" => ["running", "pausing", "cancelling", "errored"], # pausing -> paused occurs when the task actually halts performing and # occupies a status of paused. # pausing -> cancelling occurs when the user cancels a task immediately @@ -24,14 +24,14 @@ class RunStatusValidator < ActiveModel::Validator # nothing in its collection to process. # pausing -> errored occurs when the job raises an exception after the # user has paused it. - 'pausing' => ['paused', 'cancelling', 'succeeded', 'errored'], + "pausing" => ["paused", "cancelling", "succeeded", "errored"], # cancelling -> cancelled occurs when the task actually halts performing # and occupies a status of cancelled. # cancelling -> succeeded occurs when the task completes immediately after # being cancelled. See description for pausing -> succeeded. # cancelling -> errored occurs when the job raises an exception after the # user has cancelled it. - 'cancelling' => ['cancelled', 'succeeded', 'errored'], + "cancelling" => ["cancelled", "succeeded", "errored"], # running -> succeeded occurs when the task completes successfully. # running -> pausing occurs when a user pauses the task as # it's performing. @@ -40,17 +40,17 @@ class RunStatusValidator < ActiveModel::Validator # running -> interrupted occurs when the job infra shuts down the task as # it's performing. # running -> errored occurs when the job raises an exception when running. - 'running' => [ - 'succeeded', - 'pausing', - 'cancelling', - 'interrupted', - 'errored', + "running" => [ + "succeeded", + "pausing", + "cancelling", + "interrupted", + "errored", ], # paused -> enqueued occurs when the task is resumed after being paused. # paused -> cancelling when the user cancels the task after it is paused. # paused -> cancelled when the user cancels the task after it is paused. - 'paused' => ['enqueued', 'cancelling', 'cancelled'], + "paused" => ["enqueued", "cancelling", "cancelled"], # interrupted -> running occurs when the task is resumed after being # interrupted by the job infrastructure. # interrupted -> pausing occurs when the task is paused by the user while @@ -59,7 +59,7 @@ class RunStatusValidator < ActiveModel::Validator # while it is interrupted. # interrupted -> errored occurs when the task is deleted while it is # interrupted. - 'interrupted' => ['running', 'pausing', 'cancelling', 'errored'], + "interrupted" => ["running", "pausing", "cancelling", "errored"], } # Validate whether a transition from one Run status diff --git a/bin/rails b/bin/rails index 69af770e..590669d9 100755 --- a/bin/rails +++ b/bin/rails @@ -3,12 +3,12 @@ # This command will automatically be run when you run "rails" with Rails gems # installed from the root of your application. -ENGINE_ROOT = File.expand_path('..', __dir__) -ENGINE_PATH = File.expand_path('../lib/maintenance_tasks/engine', __dir__) -APP_PATH = File.expand_path('../test/dummy/config/application', __dir__) +ENGINE_ROOT = File.expand_path("..", __dir__) +ENGINE_PATH = File.expand_path("../lib/maintenance_tasks/engine", __dir__) +APP_PATH = File.expand_path("../test/dummy/config/application", __dir__) # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) +require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) -require 'rails/engine/commands' +require "rails/engine/commands" diff --git a/config/routes.rb b/config/routes.rb index fb5a936a..789f9b0a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -2,16 +2,16 @@ MaintenanceTasks::Engine.routes.draw do resources :tasks, only: [:index, :show], format: false do member do - put 'run' + put "run" end resources :runs, only: [], format: false do member do - put 'pause' - put 'cancel' + put "pause" + put "cancel" end end end - root to: 'tasks#index' + root to: "tasks#index" end diff --git a/exe/maintenance_tasks b/exe/maintenance_tasks index 6dcb4d7f..72e10b48 100755 --- a/exe/maintenance_tasks +++ b/exe/maintenance_tasks @@ -2,11 +2,11 @@ # frozen_string_literal: true -require File.expand_path('config/application', Dir.pwd) +require File.expand_path("config/application", Dir.pwd) Rails.application.require_environment! -require 'maintenance_tasks/cli' +require "maintenance_tasks/cli" module MaintenanceTasks CLI.start(ARGV) diff --git a/lib/generators/maintenance_tasks/install_generator.rb b/lib/generators/maintenance_tasks/install_generator.rb index 5defc05b..07e0ff21 100644 --- a/lib/generators/maintenance_tasks/install_generator.rb +++ b/lib/generators/maintenance_tasks/install_generator.rb @@ -5,17 +5,17 @@ module MaintenanceTasks # # @api private class InstallGenerator < Rails::Generators::Base - source_root File.expand_path('templates', __dir__) + source_root File.expand_path("templates", __dir__) # Mounts the engine in the host application's config/routes.rb def mount_engine - route("mount MaintenanceTasks::Engine => '/maintenance_tasks'") + route("mount MaintenanceTasks::Engine => \"/maintenance_tasks\"") end # Copies engine migrations to host application and migrates the database def install_migrations - rake('maintenance_tasks:install:migrations') - rake('db:migrate') + rake("maintenance_tasks:install:migrations") + rake("db:migrate") end end end diff --git a/lib/generators/maintenance_tasks/task_generator.rb b/lib/generators/maintenance_tasks/task_generator.rb index d80b1a43..aa0ef9d2 100644 --- a/lib/generators/maintenance_tasks/task_generator.rb +++ b/lib/generators/maintenance_tasks/task_generator.rb @@ -5,14 +5,14 @@ module MaintenanceTasks # # @api private class TaskGenerator < Rails::Generators::NamedBase - source_root File.expand_path('templates', __dir__) - desc 'This generator creates a task file at app/tasks and a corresponding '\ - 'test.' + source_root File.expand_path("templates", __dir__) + desc "This generator creates a task file at app/tasks and a corresponding "\ + "test." class_option :csv, type: :boolean, default: false, - desc: 'Generate a CSV Task.' + desc: "Generate a CSV Task." - check_class_collision suffix: 'Task' + check_class_collision suffix: "Task" # Creates the Task file. def create_task_file @@ -22,9 +22,9 @@ def create_task_file "#{file_name}_task.rb" ) if options[:csv] - template('csv_task.rb', template_file) + template("csv_task.rb", template_file) else - template('task.rb', template_file) + template("task.rb", template_file) end end @@ -49,7 +49,7 @@ def create_task_test_file class_path, "#{file_name}_task_test.rb" ) - template('task_test.rb', template_file) + template("task_test.rb", template_file) end def create_task_spec_file @@ -58,11 +58,11 @@ def create_task_spec_file class_path, "#{file_name}_task_spec.rb" ) - template('task_spec.rb', template_file) + template("task_spec.rb", template_file) end def file_name - super.sub(/_task\z/i, '') + super.sub(/_task\z/i, "") end def tasks_module diff --git a/lib/maintenance_tasks.rb b/lib/maintenance_tasks.rb index 590e92b3..db720d43 100644 --- a/lib/maintenance_tasks.rb +++ b/lib/maintenance_tasks.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true -require 'action_controller' -require 'action_view' -require 'active_job' -require 'active_record' +require "action_controller" +require "action_view" +require "active_job" +require "active_record" -require 'job-iteration' -require 'maintenance_tasks/engine' +require "job-iteration" +require "maintenance_tasks/engine" # Force the TaskJob class to load so we can verify upstream compatibility with # the JobIteration gem -require_relative '../app/jobs/maintenance_tasks/task_job' +require_relative "../app/jobs/maintenance_tasks/task_job" # The engine's namespace module. It provides isolation between the host # application's code and the engine-specific code. Top-level engine constants @@ -17,13 +17,13 @@ module MaintenanceTasks # The module to namespace Tasks in, as a String. Defaults to 'Maintenance'. # @param [String] the tasks_module value. - mattr_accessor :tasks_module, default: 'Maintenance' + mattr_accessor :tasks_module, default: "Maintenance" # Defines the job to be used to perform Tasks. This job must be either # `MaintenanceTasks::TaskJob` or a class that inherits from it. # # @param [String] the name of the job class. - mattr_accessor :job, default: 'MaintenanceTasks::TaskJob' + mattr_accessor :job, default: "MaintenanceTasks::TaskJob" # After each iteration, the progress of the task may be updated. This duration # in seconds limits these updates, skipping if the duration since the last @@ -50,8 +50,8 @@ def self.error_handler def self.error_handler=(error_handler) unless error_handler.arity == 3 ActiveSupport::Deprecation.warn( - 'MaintenanceTasks.error_handler should be a lambda that takes three '\ - 'arguments: error, task_context, and errored_element.' + "MaintenanceTasks.error_handler should be a lambda that takes three "\ + "arguments: error, task_context, and errored_element." ) @error_handler = ->(error, _task_context, _errored_element) do error_handler.call(error) diff --git a/lib/maintenance_tasks/cli.rb b/lib/maintenance_tasks/cli.rb index 1aac42b4..35cf1ecb 100644 --- a/lib/maintenance_tasks/cli.rb +++ b/lib/maintenance_tasks/cli.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'thor' +require "thor" module MaintenanceTasks # Defines the command line interface commands exposed by Maintenance Tasks in @@ -13,7 +13,7 @@ def exit_on_failure? end end - desc 'perform [TASK NAME]', 'Runs the given Maintenance Task' + desc "perform [TASK NAME]", "Runs the given Maintenance Task" long_desc <<-LONGDESC `maintenance_tasks perform` will run the Maintenance Task specified by the @@ -25,7 +25,7 @@ def exit_on_failure? LONGDESC # Specify the CSV file to process for CSV Tasks - option :csv, desc: 'Supply a CSV file to be processed by a CSV Task, '\ + option :csv, desc: "Supply a CSV file to be processed by a CSV Task, "\ '--csv "path/to/csv/file.csv"' # Command to run a Task. diff --git a/lib/maintenance_tasks/engine.rb b/lib/maintenance_tasks/engine.rb index 75641a85..15e98c3f 100644 --- a/lib/maintenance_tasks/engine.rb +++ b/lib/maintenance_tasks/engine.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true -require 'active_record/railtie' +require "active_record/railtie" module MaintenanceTasks # The engine's main class, which defines its namespace. The engine is mounted @@ -7,7 +7,7 @@ module MaintenanceTasks class Engine < ::Rails::Engine isolate_namespace MaintenanceTasks - initializer 'eager_load_for_classic_autoloader' do + initializer "eager_load_for_classic_autoloader" do eager_load! unless Rails.autoloaders.zeitwerk_enabled? end @@ -25,7 +25,7 @@ class Engine < ::Rails::Engine end config.action_dispatch.rescue_responses.merge!( - 'MaintenanceTasks::Task::NotFoundError' => :not_found, + "MaintenanceTasks::Task::NotFoundError" => :not_found, ) end end diff --git a/maintenance_tasks.gemspec b/maintenance_tasks.gemspec index e040abd8..6ef05cb2 100644 --- a/maintenance_tasks.gemspec +++ b/maintenance_tasks.gemspec @@ -1,30 +1,30 @@ # frozen_string_literal: true Gem::Specification.new do |spec| - spec.name = 'maintenance_tasks' - spec.version = '1.1.2' - spec.author = 'Shopify Engineering' - spec.email = 'gems@shopify.com' - spec.homepage = 'https://github.com/Shopify/maintenance_tasks' - spec.summary = 'A Rails engine for queuing and managing maintenance tasks' + spec.name = "maintenance_tasks" + spec.version = "1.1.2" + spec.author = "Shopify Engineering" + spec.email = "gems@shopify.com" + spec.homepage = "https://github.com/Shopify/maintenance_tasks" + spec.summary = "A Rails engine for queuing and managing maintenance tasks" spec.metadata = { - 'source_code_uri' => + "source_code_uri" => "https://github.com/Shopify/maintenance_tasks/tree/v#{spec.version}", - 'allowed_push_host' => 'https://rubygems.org', + "allowed_push_host" => "https://rubygems.org", } - spec.files = Dir['{app,config,db,lib}/**/*', 'Rakefile', 'README.md'] - spec.bindir = 'exe' - spec.executables = ['maintenance_tasks'] + spec.files = Dir["{app,config,db,lib}/**/*", "Rakefile", "README.md"] + spec.bindir = "exe" + spec.executables = ["maintenance_tasks"] - spec.post_install_message = 'Thank you for installing Maintenance Tasks '\ + spec.post_install_message = "Thank you for installing Maintenance Tasks "\ "#{spec.version}. To complete, please run:\n\nrails generate "\ - 'maintenance_tasks:install' + "maintenance_tasks:install" - spec.add_dependency('actionpack', '>= 6.0') - spec.add_dependency('activejob', '>= 6.0') - spec.add_dependency('activerecord', '>= 6.0') - spec.add_dependency('job-iteration', '~> 1.1') - spec.add_dependency('railties', '>= 6.0') + spec.add_dependency("actionpack", ">= 6.0") + spec.add_dependency("activejob", ">= 6.0") + spec.add_dependency("activerecord", ">= 6.0") + spec.add_dependency("job-iteration", "~> 1.1") + spec.add_dependency("railties", ">= 6.0") end diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb index 34085f1a..4240335f 100644 --- a/test/application_system_test_case.rb +++ b/test/application_system_test_case.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true -require 'test_helper' -require 'webdrivers/chromedriver' -require 'action_dispatch/system_testing/server' +require "test_helper" +require "webdrivers/chromedriver" +require "action_dispatch/system_testing/server" ActionDispatch::SystemTesting::Server.silence_puma = true @@ -10,10 +10,10 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase include ActiveJob::TestHelper driven_by :selenium, using: :headless_chrome do |options| - options.add_argument('--disable-dev-shm-usage') + options.add_argument("--disable-dev-shm-usage") options.add_preference( :download, - default_directory: 'test/dummy/tmp/downloads' + default_directory: "test/dummy/tmp/downloads" ) end @@ -25,6 +25,6 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase teardown do assert_empty page.driver.browser.manage.logs.get(:browser) Maintenance::UpdatePostsTask.fast_task = true - FileUtils.rm_rf('test/dummy/tmp/downloads') + FileUtils.rm_rf("test/dummy/tmp/downloads") end end diff --git a/test/documentation_test.rb b/test/documentation_test.rb index b05f362c..93da8a2a 100644 --- a/test/documentation_test.rb +++ b/test/documentation_test.rb @@ -1,10 +1,10 @@ # frozen_string_literal: true -require 'active_support' -require 'active_support/test_case' -require 'yard' +require "active_support" +require "active_support/test_case" +require "yard" class DocumentationTest < ActiveSupport::TestCase - test 'documentation is correctly written' do + test "documentation is correctly written" do assert_empty %x(bundle exec yard --no-save --no-output --no-stats) end end diff --git a/test/dummy/Rakefile b/test/dummy/Rakefile index 6d1041e3..c4f95238 100644 --- a/test/dummy/Rakefile +++ b/test/dummy/Rakefile @@ -1,5 +1,5 @@ # frozen_string_literal: true -require_relative 'config/application' +require_relative "config/application" Rails.application.load_tasks diff --git a/test/dummy/app/controllers/posts_controller.rb b/test/dummy/app/controllers/posts_controller.rb index f2323e3a..d0926ae0 100644 --- a/test/dummy/app/controllers/posts_controller.rb +++ b/test/dummy/app/controllers/posts_controller.rb @@ -20,7 +20,7 @@ def create @post = Post.new(post_params) if @post.save - redirect_to(@post, notice: 'Post was successfully created.') + redirect_to(@post, notice: "Post was successfully created.") else render(:new) end @@ -28,7 +28,7 @@ def create def update if @post.update(post_params) - redirect_to(@post, notice: 'Post was successfully updated.') + redirect_to(@post, notice: "Post was successfully updated.") else render(:edit) end @@ -36,7 +36,7 @@ def update def destroy @post.destroy - redirect_to(posts_url, notice: 'Post was successfully destroyed.') + redirect_to(posts_url, notice: "Post was successfully destroyed.") end private diff --git a/test/dummy/app/jobs/custom_task_job.rb b/test/dummy/app/jobs/custom_task_job.rb index 9a5f9664..551c6682 100644 --- a/test/dummy/app/jobs/custom_task_job.rb +++ b/test/dummy/app/jobs/custom_task_job.rb @@ -3,7 +3,7 @@ class CustomTaskJob < MaintenanceTasks::TaskJob before_enqueue do |job| run = job.arguments.first - raise 'Error enqueuing' if run.task_name == 'Maintenance::EnqueueErrorTask' - throw :abort if run.task_name == 'Maintenance::CancelledEnqueueTask' + raise "Error enqueuing" if run.task_name == "Maintenance::EnqueueErrorTask" + throw :abort if run.task_name == "Maintenance::CancelledEnqueueTask" end end diff --git a/test/dummy/app/mailers/application_mailer.rb b/test/dummy/app/mailers/application_mailer.rb index 24289009..45b2abda 100644 --- a/test/dummy/app/mailers/application_mailer.rb +++ b/test/dummy/app/mailers/application_mailer.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class ApplicationMailer < ActionMailer::Base - default from: 'from@example.com' - layout 'mailer' + default from: "from@example.com" + layout "mailer" end diff --git a/test/dummy/app/tasks/maintenance/error_task.rb b/test/dummy/app/tasks/maintenance/error_task.rb index b9e20ef1..730cea7f 100644 --- a/test/dummy/app/tasks/maintenance/error_task.rb +++ b/test/dummy/app/tasks/maintenance/error_task.rb @@ -6,7 +6,7 @@ def collection end def process(input) - raise ArgumentError, 'Something went wrong' if input == 2 + raise ArgumentError, "Something went wrong" if input == 2 end end end diff --git a/test/dummy/app/tasks/maintenance/import_posts_task.rb b/test/dummy/app/tasks/maintenance/import_posts_task.rb index f2bc571d..9d7b6eac 100644 --- a/test/dummy/app/tasks/maintenance/import_posts_task.rb +++ b/test/dummy/app/tasks/maintenance/import_posts_task.rb @@ -4,7 +4,7 @@ class ImportPostsTask < MaintenanceTasks::Task csv_collection def process(row) - Post.create!(title: row['title'], content: row['content']) + Post.create!(title: row["title"], content: row["content"]) end end end diff --git a/test/dummy/bin/rails b/test/dummy/bin/rails index dd027b40..cbfe38b1 100755 --- a/test/dummy/bin/rails +++ b/test/dummy/bin/rails @@ -1,5 +1,5 @@ #!/usr/bin/env ruby # frozen_string_literal: true -APP_PATH = File.expand_path('../config/application', __dir__) -require_relative '../config/boot' -require 'rails/commands' +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/test/dummy/bin/rake b/test/dummy/bin/rake index 609af747..d648cf02 100755 --- a/test/dummy/bin/rake +++ b/test/dummy/bin/rake @@ -1,5 +1,5 @@ #!/usr/bin/env ruby # frozen_string_literal: true -require_relative '../config/boot' -require 'rake' +require_relative "../config/boot" +require "rake" Rake.application.run diff --git a/test/dummy/bin/setup b/test/dummy/bin/setup index cc587463..f9ae3cb4 100755 --- a/test/dummy/bin/setup +++ b/test/dummy/bin/setup @@ -1,9 +1,9 @@ #!/usr/bin/env ruby # frozen_string_literal: true -require 'fileutils' +require "fileutils" # path to your application root. -APP_ROOT = File.expand_path('..', __dir__) +APP_ROOT = File.expand_path("..", __dir__) def system!(*args) system(*args) || abort("\n== Command #{args} failed ==") @@ -16,9 +16,9 @@ FileUtils.chdir(APP_ROOT) do # expectable outcome. # Add necessary setup steps to this file. - puts '== Installing dependencies ==' - system! 'gem install bundler --conservative' - system('bundle check') || system!('bundle install') + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") # puts "\n== Copying sample files ==" # unless File.exist?('config/database.yml') @@ -26,11 +26,11 @@ FileUtils.chdir(APP_ROOT) do # end puts "\n== Preparing database ==" - system! 'bin/rails db:prepare' + system! "bin/rails db:prepare" puts "\n== Removing old logs and tempfiles ==" - system! 'bin/rails log:clear tmp:clear' + system! "bin/rails log:clear tmp:clear" puts "\n== Restarting application server ==" - system! 'bin/rails restart' + system! "bin/rails restart" end diff --git a/test/dummy/config.ru b/test/dummy/config.ru index 1a864952..81cd2904 100644 --- a/test/dummy/config.ru +++ b/test/dummy/config.ru @@ -1,7 +1,7 @@ # frozen_string_literal: true # This file is used by Rack-based servers to start the application. -require_relative 'config/environment' +require_relative "config/environment" run(Rails.application) Rails.application.load_server diff --git a/test/dummy/config/application.rb b/test/dummy/config/application.rb index 138a47d3..3d3e97b3 100644 --- a/test/dummy/config/application.rb +++ b/test/dummy/config/application.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true -require_relative 'boot' +require_relative "boot" verbose = $VERBOSE $VERBOSE = false -require 'action_mailbox/engine' +require "action_mailbox/engine" $VERBOSE = verbose -require 'rails/all' +require "rails/all" Bundler.require(*Rails.groups) -require 'maintenance_tasks' +require "maintenance_tasks" module Dummy class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults(6.1) - if ENV['CLASSIC_AUTOLOADER'].present? - puts '=> Using classic autoloader' + if ENV["CLASSIC_AUTOLOADER"].present? + puts "=> Using classic autoloader" config.autoloader = :classic end config.to_prepare do - MaintenanceTasks.job = 'CustomTaskJob' + MaintenanceTasks.job = "CustomTaskJob" end # Only include the helper module which match the name of the controller. diff --git a/test/dummy/config/boot.rb b/test/dummy/config/boot.rb index 72fab4ce..4b7e9f81 100644 --- a/test/dummy/config/boot.rb +++ b/test/dummy/config/boot.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../../Gemfile", __dir__) -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) -$LOAD_PATH.unshift(File.expand_path('../../../lib', __dir__)) +require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) +$LOAD_PATH.unshift(File.expand_path("../../../lib", __dir__)) diff --git a/test/dummy/config/environment.rb b/test/dummy/config/environment.rb index 12ea62f8..a21c0c58 100644 --- a/test/dummy/config/environment.rb +++ b/test/dummy/config/environment.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true # Load the Rails application. -require_relative 'application' +require_relative "application" # Initialize the Rails application. Rails.application.initialize! diff --git a/test/dummy/config/environments/development.rb b/test/dummy/config/environments/development.rb index a3a17c61..ae34435a 100644 --- a/test/dummy/config/environments/development.rb +++ b/test/dummy/config/environments/development.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true -require 'active_support/core_ext/integer/time' +require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in @@ -18,13 +18,13 @@ # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. - if Rails.root.join('tmp', 'caching-dev.txt').exist? + if Rails.root.join("tmp", "caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{2.days.to_i}", + "Cache-Control" => "public, max-age=#{2.days.to_i}", } else config.action_controller.perform_caching = false diff --git a/test/dummy/config/environments/production.rb b/test/dummy/config/environments/production.rb index 01930fbf..20c79000 100644 --- a/test/dummy/config/environments/production.rb +++ b/test/dummy/config/environments/production.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true -require 'active_support/core_ext/integer/time' +require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in @@ -25,7 +25,7 @@ # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. - config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass @@ -99,7 +99,7 @@ # Syslog::Logger.new 'app-name' # ) - if ENV['RAILS_LOG_TO_STDOUT'].present? + if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) diff --git a/test/dummy/config/environments/test.rb b/test/dummy/config/environments/test.rb index b6fde784..f948d1ba 100644 --- a/test/dummy/config/environments/test.rb +++ b/test/dummy/config/environments/test.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true -require 'active_support/core_ext/integer/time' +require "active_support/core_ext/integer/time" # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that @@ -20,7 +20,7 @@ # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{1.hour.to_i}", + "Cache-Control" => "public, max-age=#{1.hour.to_i}", } # Show full error reports and disable caching. diff --git a/test/dummy/config/initializers/assets.rb b/test/dummy/config/initializers/assets.rb index f7deda5e..3bb606b2 100644 --- a/test/dummy/config/initializers/assets.rb +++ b/test/dummy/config/initializers/assets.rb @@ -2,7 +2,7 @@ # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = '1.0' +Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path diff --git a/test/dummy/config/initializers/backtrace_silencers.rb b/test/dummy/config/initializers/backtrace_silencers.rb index b228b301..7bcc81bb 100644 --- a/test/dummy/config/initializers/backtrace_silencers.rb +++ b/test/dummy/config/initializers/backtrace_silencers.rb @@ -8,4 +8,4 @@ # You can also remove all the silencers if you're trying to debug a problem # that might stem from framework code by setting BACKTRACE=1 before calling # your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". -Rails.backtrace_cleaner.remove_silencers! if ENV['BACKTRACE'] +Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] diff --git a/test/dummy/config/puma.rb b/test/dummy/config/puma.rb index 7cb0e8aa..19acbd80 100644 --- a/test/dummy/config/puma.rb +++ b/test/dummy/config/puma.rb @@ -5,21 +5,21 @@ # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # -max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } -min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } threads(min_threads_count, max_threads_count) # Specifies the `port` that Puma will listen on to receive requests; # default is 3000. # -port(ENV.fetch('PORT') { 3000 }) +port(ENV.fetch("PORT") { 3000 }) # Specifies the `environment` that Puma will run in. # -environment(ENV.fetch('RAILS_ENV') { 'development' }) +environment(ENV.fetch("RAILS_ENV") { "development" }) # Specifies the `pidfile` that Puma will use. -pidfile(ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' }) +pidfile(ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }) # Specifies the number of `workers` to boot in clustered mode. # Workers are forked web server processes. If using threads and workers together diff --git a/test/dummy/config/routes.rb b/test/dummy/config/routes.rb index 7d96dd92..d39117e8 100644 --- a/test/dummy/config/routes.rb +++ b/test/dummy/config/routes.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true Rails.application.routes.draw do - mount MaintenanceTasks::Engine => '/maintenance_tasks' + mount MaintenanceTasks::Engine => "/maintenance_tasks" resources :posts - root to: 'posts#index' + root to: "posts#index" end diff --git a/test/dummy/config/spring.rb b/test/dummy/config/spring.rb index 9a455793..3b898aff 100644 --- a/test/dummy/config/spring.rb +++ b/test/dummy/config/spring.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true Spring.watch( - '.ruby-version', - '.rbenv-vars', - 'tmp/restart.txt', - 'tmp/caching-dev.txt' + ".ruby-version", + ".rbenv-vars", + "tmp/restart.txt", + "tmp/caching-dev.txt" ) diff --git a/test/dummy/db/migrate/20210112141723_create_active_storage_tables.active_storage.rb b/test/dummy/db/migrate/20210112141723_create_active_storage_tables.active_storage.rb index 18661282..48cced06 100644 --- a/test/dummy/db/migrate/20210112141723_create_active_storage_tables.active_storage.rb +++ b/test/dummy/db/migrate/20210112141723_create_active_storage_tables.active_storage.rb @@ -24,7 +24,7 @@ def change t.index( [:record_type, :record_id, :name, :blob_id], - name: 'index_active_storage_attachments_uniqueness', unique: true + name: "index_active_storage_attachments_uniqueness", unique: true ) t.foreign_key(:active_storage_blobs, column: :blob_id) end @@ -35,7 +35,7 @@ def change t.index( [:blob_id, :variation_digest], - name: 'index_active_storage_variant_records_uniqueness', + name: "index_active_storage_variant_records_uniqueness", unique: true ) t.foreign_key(:active_storage_blobs, column: :blob_id) diff --git a/test/dummy/db/seeds.rb b/test/dummy/db/seeds.rb index 3b457a31..a963d5b9 100644 --- a/test/dummy/db/seeds.rb +++ b/test/dummy/db/seeds.rb @@ -6,7 +6,7 @@ module MaintenanceTasks 10.times do Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", started_at: Time.now, tick_count: 10, tick_total: 10, diff --git a/test/helpers/maintenance_tasks/application_helper_test.rb b/test/helpers/maintenance_tasks/application_helper_test.rb index 60afa2f5..ef8c8963 100644 --- a/test/helpers/maintenance_tasks/application_helper_test.rb +++ b/test/helpers/maintenance_tasks/application_helper_test.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class ApplicationHelperTest < ActionView::TestCase - test '#time_ago returns a time element with the given datetime worded as relative to now and ISO 8601 UTC time in title attribute' do + test "#time_ago returns a time element with the given datetime worded as relative to now and ISO 8601 UTC time in title attribute" do travel_to Time.zone.local(2020, 1, 9, 9, 41, 44) time = Time.zone.local(2020, 01, 01, 01, 00, 00) diff --git a/test/helpers/maintenance_tasks/tasks_helper_test.rb b/test/helpers/maintenance_tasks/tasks_helper_test.rb index fdc369a5..1899d010 100644 --- a/test/helpers/maintenance_tasks/tasks_helper_test.rb +++ b/test/helpers/maintenance_tasks/tasks_helper_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class TasksHelperTest < ActionView::TestCase @@ -8,23 +8,23 @@ class TasksHelperTest < ActionView::TestCase @run = Run.new end - test '#format_backtrace converts the backtrace to a formatted string' do + test "#format_backtrace converts the backtrace to a formatted string" do backtrace = [ "app/jobs/maintenance/error_task.rb:13:in `foo'", "app/jobs/maintenance/error_task.rb:9:in `process'", ] - expected_trace = 'app/jobs/maintenance/error_task.rb:13:in `foo'' \ - '
app/jobs/maintenance/error_task.rb:9:in `process'' + expected_trace = "app/jobs/maintenance/error_task.rb:13:in `foo'" \ + "
app/jobs/maintenance/error_task.rb:9:in `process'" assert_equal expected_trace, format_backtrace(backtrace) end - test '#progress renders a when Run has started' do + test "#progress renders a when Run has started" do @run.started_at = Time.now Progress.expects(:new).with(@run).returns( - mock(value: 42, max: 84, title: 'Almost there!') + mock(value: 42, max: 84, title: "Almost there!") ) expected = ' with no value when the Progress value is nil' do + test "#progress returns a with no value when the Progress value is nil" do @run.started_at = Time.now Progress.expects(:new).with(@run).returns( - mock(value: nil, max: 84, title: 'Almost there!') + mock(value: nil, max: 84, title: "Almost there!") ) expected = '' assert_equal expected, progress(@run) end - test '#status_tag renders a span with the appropriate tag based on status' do + test "#status_tag renders a span with the appropriate tag based on status" do expected = 'Pausing' - assert_equal expected, status_tag('pausing') + assert_equal expected, status_tag("pausing") end test "#estimated_time_to_completion returns the Run's estimated_completion_time in words" do @run.expects(estimated_completion_time: Time.now + 2.minutes) - assert_equal '2 minutes', estimated_time_to_completion(@run) + assert_equal "2 minutes", estimated_time_to_completion(@run) end - test '#estimated_time_to_completion returns nil if the Run has no estimated_completion_time' do + test "#estimated_time_to_completion returns nil if the Run has no estimated_completion_time" do assert_nil estimated_time_to_completion(@run) end - test '#time_running_in_words reports the approximate time running of the given Run' do + test "#time_running_in_words reports the approximate time running of the given Run" do @run.time_running = 182.5 - assert_equal '3 minutes', time_running_in_words(@run) + assert_equal "3 minutes", time_running_in_words(@run) end - test '#highlight_code returns a HTML safe string' do - assert_predicate highlight_code('self'), :html_safe? + test "#highlight_code returns a HTML safe string" do + assert_predicate highlight_code("self"), :html_safe? end - test '#highlight_code wraps syntax in span' do - assert_equal 'self', highlight_code('self') - assert_equal 'CSV', highlight_code('CSV') - assert_equal '42', highlight_code('42') - assert_equal '4.2', highlight_code('4.2') - assert_equal '@foo', highlight_code('@foo') + test "#highlight_code wraps syntax in span" do + assert_equal 'self', highlight_code("self") + assert_equal 'CSV', highlight_code("CSV") + assert_equal '42', highlight_code("42") + assert_equal '4.2', highlight_code("4.2") + assert_equal '@foo', highlight_code("@foo") end - test '#highlight_code does not wrap whitespace' do + test "#highlight_code does not wrap whitespace" do assert_equal '1' + "\n"\ '2', highlight_code("1\n2") - assert_equal '1' + ' '\ - '2', highlight_code('1 2') + assert_equal '1' + " "\ + '2', highlight_code("1 2") assert_equal "\n", highlight_code("\n") end - test '#csv_file_download_path generates a download link to the CSV attachment for a Run' do - run = Run.new(task_name: 'Maintenance::ImportPostsTask') - csv = Rack::Test::UploadedFile.new(file_fixture('sample.csv'), 'text/csv') + test "#csv_file_download_path generates a download link to the CSV attachment for a Run" do + run = Run.new(task_name: "Maintenance::ImportPostsTask") + csv = Rack::Test::UploadedFile.new(file_fixture("sample.csv"), "text/csv") run.csv_file.attach(csv) assert_match %r{rails\/active_storage\/blobs\/redirect\/\S+\/sample.csv}, diff --git a/test/jobs/maintenance_tasks/task_job_test.rb b/test/jobs/maintenance_tasks/task_job_test.rb index c7e0d53b..ad4f665f 100644 --- a/test/jobs/maintenance_tasks/task_job_test.rb +++ b/test/jobs/maintenance_tasks/task_job_test.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true -require 'test_helper' -require 'job-iteration' +require "test_helper" +require "job-iteration" module MaintenanceTasks class TaskJobTest < ActiveJob::TestCase setup do - @run = Run.create!(task_name: 'Maintenance::TestTask') + @run = Run.create!(task_name: "Maintenance::TestTask") end - test '.perform_now exits job when Run is paused, and updates Run status from pausing to paused' do + test ".perform_now exits job when Run is paused, and updates Run status from pausing to paused" do Maintenance::TestTask.any_instance.expects(:process).once.with do @run.pausing! end @@ -19,7 +19,7 @@ class TaskJobTest < ActiveJob::TestCase assert_no_enqueued_jobs end - test '.perform_now exits job when Run is cancelled, and updates Run status from cancelling to cancelled' do + test ".perform_now exits job when Run is cancelled, and updates Run status from cancelling to cancelled" do Maintenance::TestTask.any_instance.expects(:process).once.with do @run.cancelling! end @@ -30,7 +30,7 @@ class TaskJobTest < ActiveJob::TestCase assert_no_enqueued_jobs end - test '.perform_now persists ended_at when the Run is cancelled' do + test ".perform_now persists ended_at when the Run is cancelled" do freeze_time Maintenance::TestTask.any_instance.expects(:process).once.with do @run.cancelling! @@ -41,7 +41,7 @@ class TaskJobTest < ActiveJob::TestCase assert_equal Time.now, @run.reload.ended_at end - test '.perform_now skips iterations when Run is paused' do + test ".perform_now skips iterations when Run is paused" do @run.pausing! Maintenance::TestTask.any_instance.expects(:process).never @@ -52,7 +52,7 @@ class TaskJobTest < ActiveJob::TestCase assert_no_enqueued_jobs end - test '.perform_now skips iterations when Run is cancelled' do + test ".perform_now skips iterations when Run is cancelled" do @run.cancelling! Maintenance::TestTask.any_instance.expects(:process).never @@ -63,7 +63,7 @@ class TaskJobTest < ActiveJob::TestCase assert_no_enqueued_jobs end - test '.perform_now updates tick_count' do + test ".perform_now updates tick_count" do Maintenance::TestTask.any_instance.expects(:process).twice TaskJob.perform_now(@run) @@ -71,7 +71,7 @@ class TaskJobTest < ActiveJob::TestCase assert_equal 2, @run.reload.tick_count end - test '.perform_now updates tick_count when job is interrupted' do + test ".perform_now updates tick_count when job is interrupted" do JobIteration.stubs(interruption_adapter: -> { true }) Maintenance::TestTask.any_instance.expects(:process).once @@ -80,7 +80,7 @@ class TaskJobTest < ActiveJob::TestCase assert_equal 1, @run.reload.tick_count end - test '.perform_now persists started_at and updates tick_total when the job starts' do + test ".perform_now persists started_at and updates tick_total when the job starts" do freeze_time Maintenance::TestTask.any_instance.expects(:process).once.with do @run.cancelling! @@ -92,7 +92,7 @@ class TaskJobTest < ActiveJob::TestCase assert_equal 2, @run.tick_total end - test '.perform_now updates Run to running and persists job_id when job starts performing' do + test ".perform_now updates Run to running and persists job_id when job starts performing" do Maintenance::TestTask.any_instance.expects(:process).twice.with do assert_predicate @run.reload, :running? end @@ -103,7 +103,7 @@ class TaskJobTest < ActiveJob::TestCase assert_equal job.job_id, @run.reload.job_id end - test '.perform_now updates Run to succeeded and persists ended_at when job finishes successfully' do + test ".perform_now updates Run to succeeded and persists ended_at when job finishes successfully" do freeze_time Maintenance::TestTask.any_instance.expects(:process).twice TaskJob.perform_now(@run) @@ -112,7 +112,7 @@ class TaskJobTest < ActiveJob::TestCase assert_predicate @run, :succeeded? end - test '.perform_now updates Run to interrupted when job is interrupted' do + test ".perform_now updates Run to interrupted when job is interrupted" do JobIteration.stubs(interruption_adapter: -> { true }) Maintenance::TestTask.any_instance.expects(:process).once @@ -121,20 +121,20 @@ class TaskJobTest < ActiveJob::TestCase assert_predicate @run.reload, :interrupted? end - test '.perform_now re-enqueues the job when interrupted' do + test ".perform_now re-enqueues the job when interrupted" do JobIteration.stubs(interruption_adapter: -> { true }) Maintenance::TestTask.any_instance.expects(:process).once assert_enqueued_with(job: TaskJob) { TaskJob.perform_now(@run) } end - test '.perform_now updates Run to errored and persists ended_at when exception is raised' do + test ".perform_now updates Run to errored and persists ended_at when exception is raised" do freeze_time - run = Run.create!(task_name: 'Maintenance::ErrorTask') + run = Run.create!(task_name: "Maintenance::ErrorTask") run.expects(:persist_error).with do |exception| assert_kind_of ArgumentError, exception - assert_equal 'Something went wrong', exception.message + assert_equal "Something went wrong", exception.message expected = "app/tasks/maintenance/error_task.rb:9:in `process'" assert_match expected, exception.backtrace.first end @@ -142,29 +142,29 @@ class TaskJobTest < ActiveJob::TestCase TaskJob.perform_now(run) end - test '.perform_now handles when the Task cannot be found' do - run = Run.new(task_name: 'Maintenance::DeletedTask') + test ".perform_now handles when the Task cannot be found" do + run = Run.new(task_name: "Maintenance::DeletedTask") run.save(validate: false) TaskJob.perform_now(run) - assert_equal 'MaintenanceTasks::Task::NotFoundError', run.error_class - assert_equal 'Task Maintenance::DeletedTask not found.', run.error_message + assert_equal "MaintenanceTasks::Task::NotFoundError", run.error_class + assert_equal "Task Maintenance::DeletedTask not found.", run.error_message end - test '.perform_now handles when the Task cannot be found when resuming after interruption' do - run = Run.new(task_name: 'Maintenance::DeletedTask') + test ".perform_now handles when the Task cannot be found when resuming after interruption" do + run = Run.new(task_name: "Maintenance::DeletedTask") run.save(validate: false) run.running! # the Task existed when the run started run.interrupted! # but not after interruption TaskJob.perform_now(run) - assert_equal 'MaintenanceTasks::Task::NotFoundError', run.error_class - assert_equal 'Task Maintenance::DeletedTask not found.', run.error_message + assert_equal "MaintenanceTasks::Task::NotFoundError", run.error_class + assert_equal "Task Maintenance::DeletedTask not found.", run.error_message end - test '.perform_now delays reenqueuing the job after interruption until all callbacks are finished' do + test ".perform_now delays reenqueuing the job after interruption until all callbacks are finished" do JobIteration.stubs(interruption_adapter: -> { true }) AnotherTaskJob = Class.new(TaskJob) do @@ -182,13 +182,13 @@ class << self assert_enqueued_jobs 1 end - test '.perform_now does not enqueue another job if Run errors' do - run = Run.create!(task_name: 'Maintenance::ErrorTask') + test ".perform_now does not enqueue another job if Run errors" do + run = Run.create!(task_name: "Maintenance::ErrorTask") assert_no_enqueued_jobs { TaskJob.perform_now(run) } end - test '.perform_now updates tick_count when job is errored' do + test ".perform_now updates tick_count when job is errored" do Maintenance::TestTask.any_instance.expects(:process).twice .returns(nil) .raises(ArgumentError) @@ -198,7 +198,7 @@ class << self assert_equal 1, @run.reload.tick_count end - test '.perform_now persists cursor when job shuts down' do + test ".perform_now persists cursor when job shuts down" do Maintenance::TestTask.any_instance.expects(:process).once.with do @run.pausing! end @@ -208,7 +208,7 @@ class << self assert_equal 0, @run.reload.cursor end - test '.perform_now starts job from cursor position when job resumes' do + test ".perform_now starts job from cursor position when job resumes" do @run.update!(cursor: 0) Maintenance::TestTask.any_instance.expects(:process).once.with(2) @@ -216,7 +216,7 @@ class << self TaskJob.perform_now(@run) end - test '.perform_now accepts Active Record Relations as collection' do + test ".perform_now accepts Active Record Relations as collection" do Maintenance::TestTask.any_instance.stubs(collection: Post.all) Maintenance::TestTask.any_instance.expects(:process).times(Post.count) @@ -225,12 +225,12 @@ class << self assert_predicate @run.reload, :succeeded? end - test '.perform_now accepts CSVs as collection' do + test ".perform_now accepts CSVs as collection" do Maintenance::ImportPostsTask.any_instance.expects(:process).times(5) - run = Run.new(task_name: 'Maintenance::ImportPostsTask') + run = Run.new(task_name: "Maintenance::ImportPostsTask") run.csv_file.attach( - { io: File.open(file_fixture('sample.csv')), filename: 'sample.csv' } + { io: File.open(file_fixture("sample.csv")), filename: "sample.csv" } ) run.save TaskJob.perform_now(run) @@ -238,21 +238,21 @@ class << self assert_predicate run.reload, :succeeded? end - test '.perform_now sets the Run as errored when the Task collection is invalid' do - Maintenance::TestTask.any_instance.stubs(collection: 'not a collection') + test ".perform_now sets the Run as errored when the Task collection is invalid" do + Maintenance::TestTask.any_instance.stubs(collection: "not a collection") TaskJob.perform_now(@run) @run.reload assert_predicate @run, :errored? - assert_equal 'ArgumentError', @run.error_class + assert_equal "ArgumentError", @run.error_class assert_empty @run.backtrace - expected_message = 'Maintenance::TestTask#collection '\ - 'must be either an Active Record Relation, Array, or CSV.' + expected_message = "Maintenance::TestTask#collection "\ + "must be either an Active Record Relation, Array, or CSV." assert_equal expected_message, @run.error_message end - test '.perform_now sets the Run as errored when the Task collection is not defined' do + test ".perform_now sets the Run as errored when the Task collection is not defined" do collection_method = Maintenance::TestTask.instance_method(:collection) Maintenance::TestTask.remove_method(:collection) TaskJob.perform_now(@run) @@ -262,7 +262,7 @@ class << self Maintenance::TestTask.define_method(:collection, collection_method) end - test '.perform_now sets the Run as errored when the Task process is not defined' do + test ".perform_now sets the Run as errored when the Task process is not defined" do collection_method = Maintenance::TestTask.instance_method(:process) Maintenance::TestTask.remove_method(:process) TaskJob.perform_now(@run) @@ -272,13 +272,13 @@ class << self Maintenance::TestTask.define_method(:process, collection_method) end - test '.retry_on raises NotImplementedError' do + test ".retry_on raises NotImplementedError" do assert_raises NotImplementedError do Class.new(TaskJob) { retry_on StandardError } end end - test '.perform_now calls the error handler when there was an Error' do + test ".perform_now calls the error handler when there was an Error" do error_handler_before = MaintenanceTasks.error_handler handled_error = nil handled_task_context = nil @@ -290,23 +290,23 @@ class << self handled_errored_element = errored_el end - run = Run.create!(task_name: 'Maintenance::ErrorTask') + run = Run.create!(task_name: "Maintenance::ErrorTask") TaskJob.perform_now(run) assert_equal(ArgumentError, handled_error.class) - assert_equal('Maintenance::ErrorTask', handled_task_context[:task_name]) + assert_equal("Maintenance::ErrorTask", handled_task_context[:task_name]) assert_equal(2, handled_errored_element) ensure MaintenanceTasks.error_handler = error_handler_before end - test '.perform_now still persists the error properly if the error handler raises' do + test ".perform_now still persists the error properly if the error handler raises" do error_handler_before = MaintenanceTasks.error_handler MaintenanceTasks.error_handler = ->(error, _task_context, _errored_el) do raise error end - run = Run.create!(task_name: 'Maintenance::ErrorTask') + run = Run.create!(task_name: "Maintenance::ErrorTask") assert_raises { TaskJob.perform_now(run) } run.reload @@ -317,7 +317,7 @@ class << self MaintenanceTasks.error_handler = error_handler_before end - test '.perform_now handles case where run is not set and calls error handler' do + test ".perform_now handles case where run is not set and calls error handler" do error_handler_before = MaintenanceTasks.error_handler handled_error = nil handled_task_context = nil @@ -327,12 +327,12 @@ class << self end RaisingTaskJob = Class.new(TaskJob) do - before_perform(prepend: true) { raise 'Uh oh!' } + before_perform(prepend: true) { raise "Uh oh!" } end RaisingTaskJob.perform_now(@run) - assert_equal('Uh oh!', handled_error.message) + assert_equal("Uh oh!", handled_error.message) assert_empty(handled_task_context) ensure MaintenanceTasks.error_handler = error_handler_before diff --git a/test/lib/generators/maintenance_tasks/install_generator_test.rb b/test/lib/generators/maintenance_tasks/install_generator_test.rb index 9b3831f6..8e8fb89f 100644 --- a/test/lib/generators/maintenance_tasks/install_generator_test.rb +++ b/test/lib/generators/maintenance_tasks/install_generator_test.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' -require 'generators/maintenance_tasks/install_generator' +require "test_helper" +require "generators/maintenance_tasks/install_generator" module MaintenanceTasks class InstallGeneratorTest < Rails::Generators::TestCase tests InstallGenerator - SAMPLE_APP_PATH = Engine.root.join('tmp/sample_app') + SAMPLE_APP_PATH = Engine.root.join("tmp/sample_app") destination SAMPLE_APP_PATH setup :prepare_destination setup do - skip 'This test is too slow' if ENV['SKIP_SLOW'].present? + skip "This test is too slow" if ENV["SKIP_SLOW"].present? setup_sample_app end @@ -18,20 +18,20 @@ class InstallGeneratorTest < Rails::Generators::TestCase FileUtils.rm_rf(SAMPLE_APP_PATH) end - test 'generator mounts engine and runs migrations' do + test "generator mounts engine and runs migrations" do Dir.chdir(SAMPLE_APP_PATH) do run_generator - assert_file('config/routes.rb') do |contents| + assert_file("config/routes.rb") do |contents| assert_match( - %r{mount MaintenanceTasks::Engine => '/maintenance_tasks'}, + %r{mount MaintenanceTasks::Engine => "/maintenance_tasks"}, contents ) end - mig = 'db/migrate/create_maintenance_tasks_runs.maintenance_tasks.rb' + mig = "db/migrate/create_maintenance_tasks_runs.maintenance_tasks.rb" assert_migration(mig) - assert_file('db/schema.rb') do |contents| + assert_file("db/schema.rb") do |contents| assert_match(/create_table "maintenance_tasks_runs"/, contents) end end @@ -43,7 +43,7 @@ def setup_sample_app FileUtils.copy_entry(Rails.root, SAMPLE_APP_PATH) Dir.chdir(SAMPLE_APP_PATH) do - FileUtils.rm_r('db') + FileUtils.rm_r("db") end end end diff --git a/test/lib/generators/maintenance_tasks/task_generator_test.rb b/test/lib/generators/maintenance_tasks/task_generator_test.rb index 51b8e98a..7e015d14 100644 --- a/test/lib/generators/maintenance_tasks/task_generator_test.rb +++ b/test/lib/generators/maintenance_tasks/task_generator_test.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'test_helper' -require 'generators/maintenance_tasks/task_generator' +require "test_helper" +require "generators/maintenance_tasks/task_generator" module MaintenanceTasks class GeneratorTest < Rails::Generators::TestCase tests TaskGenerator - SAMPLE_APP_PATH = Engine.root.join('tmp/sample_app') + SAMPLE_APP_PATH = Engine.root.join("tmp/sample_app") destination SAMPLE_APP_PATH setup :prepare_destination @@ -13,16 +13,16 @@ def teardown FileUtils.rm_rf(SAMPLE_APP_PATH) end - test 'generator creates task skeleton and task test' do - run_generator ['sleepy'] - assert_file 'app/tasks/maintenance/sleepy_task.rb' do |task| + test "generator creates task skeleton and task test" do + run_generator ["sleepy"] + assert_file "app/tasks/maintenance/sleepy_task.rb" do |task| assert_match(/module Maintenance/, task) assert_match(/class SleepyTask < MaintenanceTasks::Task/, task) assert_match(/def collection/, task) assert_match(/def process\(element\)/, task) assert_match(/def count/, task) end - assert_file 'test/tasks/maintenance/sleepy_task_test.rb' do |task_test| + assert_file "test/tasks/maintenance/sleepy_task_test.rb" do |task_test| assert_match(/module Maintenance/, task_test) assert_match( /class SleepyTaskTest < ActiveSupport::TestCase/, @@ -31,14 +31,14 @@ def teardown end end - test 'generator creates a task spec if the application is using RSpec' do + test "generator creates a task spec if the application is using RSpec" do generators_config = Rails.application.config.generators old_test_framework = generators_config.options[:rails][:test_framework] generators_config.options[:rails][:test_framework] = :rspec - run_generator(['sleepy']) + run_generator(["sleepy"]) - assert_file('spec/tasks/maintenance/sleepy_task_spec.rb') do |task_spec| + assert_file("spec/tasks/maintenance/sleepy_task_spec.rb") do |task_spec| assert_match(/module Maintenance/, task_spec) assert_match(/RSpec.describe SleepyTask/, task_spec) end @@ -46,35 +46,35 @@ def teardown generators_config.options[:rails][:test_framework] = old_test_framework end - test 'generator uses configured tasks module' do + test "generator uses configured tasks module" do previous_task_module = MaintenanceTasks.tasks_module - MaintenanceTasks.tasks_module = 'Foo' + MaintenanceTasks.tasks_module = "Foo" - run_generator(['sleepy']) - assert_file('app/tasks/foo/sleepy_task.rb') do |task| + run_generator(["sleepy"]) + assert_file("app/tasks/foo/sleepy_task.rb") do |task| assert_match(/module Foo/, task) end ensure MaintenanceTasks.tasks_module = previous_task_module end - test 'generator namespaces task properly' do - run_generator ['admin/sleepy'] - assert_file 'app/tasks/maintenance/admin/sleepy_task.rb' do |task| + test "generator namespaces task properly" do + run_generator ["admin/sleepy"] + assert_file "app/tasks/maintenance/admin/sleepy_task.rb" do |task| assert_match(/class Admin::SleepyTask < MaintenanceTasks::Task/, task) end end - test 'generator does not duplicate task suffix' do - run_generator ['sleepy_task'] + test "generator does not duplicate task suffix" do + run_generator ["sleepy_task"] - assert_no_file 'app/tasks/maintenance/sleepy_task_task.rb' - assert_file 'app/tasks/maintenance/sleepy_task.rb' + assert_no_file "app/tasks/maintenance/sleepy_task_task.rb" + assert_file "app/tasks/maintenance/sleepy_task.rb" end - test 'generator creates a CSV Task if the --csv option is supplied' do - run_generator ['sleepy', '--csv'] - assert_file 'app/tasks/maintenance/sleepy_task.rb' do |task| + test "generator creates a CSV Task if the --csv option is supplied" do + run_generator ["sleepy", "--csv"] + assert_file "app/tasks/maintenance/sleepy_task.rb" do |task| assert_match(/class SleepyTask < MaintenanceTasks::Task/, task) assert_match(/csv_collection/, task) assert_match(/def process\(row\)/, task) diff --git a/test/lib/maintenance_tasks/cli_test.rb b/test/lib/maintenance_tasks/cli_test.rb index 583213b6..e13b59ce 100644 --- a/test/lib/maintenance_tasks/cli_test.rb +++ b/test/lib/maintenance_tasks/cli_test.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'test_helper' -require 'maintenance_tasks/cli' +require "test_helper" +require "maintenance_tasks/cli" module MaintenanceTasks class CLITest < ActiveSupport::TestCase @@ -9,41 +9,41 @@ class CLITest < ActiveSupport::TestCase @cli = CLI.new end - test '.exit_on_failure? is true' do + test ".exit_on_failure? is true" do assert_predicate CLI, :exit_on_failure? end - test '#perfom runs the given Task and prints a success message' do - task = mock(name: 'MyTask') + test "#perfom runs the given Task and prints a success message" do + task = mock(name: "MyTask") - Runner.expects(:run).with(name: 'MyTask', csv_file: nil).returns(task) - @cli.expects(:say_status).with(:success, 'MyTask was enqueued.', :green) + Runner.expects(:run).with(name: "MyTask", csv_file: nil).returns(task) + @cli.expects(:say_status).with(:success, "MyTask was enqueued.", :green) - @cli.perform('MyTask') + @cli.perform("MyTask") end - test '#perfom prints an error message when the runner raises' do - Runner.expects(:run).with(name: 'Wrong', csv_file: nil).raises('Invalid!') - @cli.expects(:say_status).with(:error, 'Invalid!', :red) + test "#perfom prints an error message when the runner raises" do + Runner.expects(:run).with(name: "Wrong", csv_file: nil).raises("Invalid!") + @cli.expects(:say_status).with(:error, "Invalid!", :red) - @cli.perform('Wrong') + @cli.perform("Wrong") end - test '#perform runs a CSV Task with the supplied CSV when --csv option used' do - task = mock(name: 'MyCsvTask') - csv_file_path = file_fixture('sample.csv') + test "#perform runs a CSV Task with the supplied CSV when --csv option used" do + task = mock(name: "MyCsvTask") + csv_file_path = file_fixture("sample.csv") opened_csv_file = File.open(csv_file_path) - expected_attachable = { io: opened_csv_file, filename: 'sample.csv' } + expected_attachable = { io: opened_csv_file, filename: "sample.csv" } @cli.expects(:options).returns(csv: csv_file_path) File.expects(:open).with(csv_file_path).returns(opened_csv_file) Runner.expects(:run) - .with(name: 'MyCsvTask', csv_file: expected_attachable) + .with(name: "MyCsvTask", csv_file: expected_attachable) .returns(task) @cli.expects(:say_status) - .with(:success, 'MyCsvTask was enqueued.', :green) + .with(:success, "MyCsvTask was enqueued.", :green) - @cli.perform('MyCsvTask') + @cli.perform("MyCsvTask") end end end diff --git a/test/lib/maintenance_tasks_test.rb b/test/lib/maintenance_tasks_test.rb index ac8eaffb..ea7f189e 100644 --- a/test/lib/maintenance_tasks_test.rb +++ b/test/lib/maintenance_tasks_test.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class MaintenanceTasksTest < ActiveSupport::TestCase - test 'deprecation warning raised when error_handler does not accept three arguments' do + test "deprecation warning raised when error_handler does not accept three arguments" do error_handler_before = MaintenanceTasks.error_handler - dep_msg = 'MaintenanceTasks.error_handler should be a lambda that takes '\ - 'three arguments: error, task_context, and errored_element.' + dep_msg = "MaintenanceTasks.error_handler should be a lambda that takes "\ + "three arguments: error, task_context, and errored_element." assert_deprecated(dep_msg) { MaintenanceTasks.error_handler = ->(error) {} } ensure MaintenanceTasks.error_handler = error_handler_before diff --git a/test/models/maintenance_tasks/progress_test.rb b/test/models/maintenance_tasks/progress_test.rb index 79fef58a..d9fcc870 100644 --- a/test/models/maintenance_tasks/progress_test.rb +++ b/test/models/maintenance_tasks/progress_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class ProgressTest < ActiveSupport::TestCase @@ -9,23 +9,23 @@ class ProgressTest < ActiveSupport::TestCase @progress = Progress.new(@run) end - test '#value is the Run tick count' do + test "#value is the Run tick count" do assert_equal 4, @progress.value end - test '#value is nil if the Run does not have a tick total' do + test "#value is nil if the Run does not have a tick total" do @run.tick_total = nil assert_nil @progress.value end - test '#value is the Run tick count if the Run does not have a tick total and it is stopped' do + test "#value is the Run tick count if the Run does not have a tick total and it is stopped" do @run.status = :paused @run.tick_total = nil assert_equal 4, @progress.value end - test '#value is nil if the Run tick count is strictly greater than its tick total' do + test "#value is nil if the Run tick count is strictly greater than its tick total" do @run.tick_count = 7 refute_nil @progress.value @@ -33,38 +33,38 @@ class ProgressTest < ActiveSupport::TestCase assert_nil @progress.value end - test '#max is the Run tick total' do + test "#max is the Run tick total" do assert_equal 7, @progress.max end - test '#max is the Run tick count if the Run does not have a tick total' do + test "#max is the Run tick count if the Run does not have a tick total" do @run.tick_total = nil assert_equal 4, @progress.max end - test '#max is the Run tick count if the Run tick count is greater than its tick total' do + test "#max is the Run tick count if the Run tick count is greater than its tick total" do @run.tick_count = 8 assert_equal 8, @progress.max end - test '#title returns a description with tick count, tick total, and percentage' do - assert_equal 'Processed 4 out of 7 (57%)', @progress.title + test "#title returns a description with tick count, tick total, and percentage" do + assert_equal "Processed 4 out of 7 (57%)", @progress.title end - test '#title returns a description with tick count when tick total is not present' do + test "#title returns a description with tick count when tick total is not present" do @run.tick_total = nil - assert_equal 'Processed 4 items.', @progress.title + assert_equal "Processed 4 items.", @progress.title end - test '#title returns a description with tick count and tick total when tick count is greater than its tick total' do + test "#title returns a description with tick count and tick total when tick count is greater than its tick total" do @run.tick_count = 8 - assert_equal 'Processed 8 items (expected 7).', @progress.title + assert_equal "Processed 8 items (expected 7).", @progress.title end - test '#title pluralizes the description according to the tick count' do + test "#title pluralizes the description according to the tick count" do @run.tick_count = 1 @run.tick_total = nil - assert_equal 'Processed 1 item.', @progress.title + assert_equal "Processed 1 item.", @progress.title end end end diff --git a/test/models/maintenance_tasks/run_test.rb b/test/models/maintenance_tasks/run_test.rb index 66aec0db..ee39744f 100644 --- a/test/models/maintenance_tasks/run_test.rb +++ b/test/models/maintenance_tasks/run_test.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class RunTest < ActiveSupport::TestCase test "invalid if the task doesn't exist" do - run = Run.new(task_name: 'Maintenance::DoesNotExist') + run = Run.new(task_name: "Maintenance::DoesNotExist") refute run.valid? end - test 'invalid if associated with CSV Task and no attachment' do - run = Run.new(task_name: 'Maintenance::ImportPostsTask') + test "invalid if associated with CSV Task and no attachment" do + run = Run.new(task_name: "Maintenance::ImportPostsTask") refute run.valid? end - test 'invalid if unassociated with CSV Task and attachment' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') - csv = Rack::Test::UploadedFile.new(file_fixture('sample.csv'), 'text/csv') + test "invalid if unassociated with CSV Task and attachment" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") + csv = Rack::Test::UploadedFile.new(file_fixture("sample.csv"), "text/csv") run.csv_file.attach(csv) refute run.valid? end - test '#persist_progress persists increments to tick count and time_running' do + test "#persist_progress persists increments to tick count and time_running" do run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", tick_count: 40, time_running: 10.2, ) @@ -34,23 +34,23 @@ class RunTest < ActiveSupport::TestCase assert_equal 12.2, run.time_running end - test '#persist_error updates Run to errored and sets ended_at' do + test "#persist_error updates Run to errored and sets ended_at" do freeze_time - run = Run.create!(task_name: 'Maintenance::ErrorTask') + run = Run.create!(task_name: "Maintenance::ErrorTask") - error = ArgumentError.new('Something went wrong') + error = ArgumentError.new("Something went wrong") error.set_backtrace(["lib/foo.rb:42:in `bar'"]) run.persist_error(error) assert_predicate run, :errored? - assert_equal 'ArgumentError', run.error_class - assert_equal 'Something went wrong', run.error_message + assert_equal "ArgumentError", run.error_class + assert_equal "Something went wrong", run.error_message assert_equal ["lib/foo.rb:42:in `bar'"], run.backtrace assert_equal Time.now, run.ended_at end - test '#reload_status reloads status and clears dirty tracking' do - run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') + test "#reload_status reloads status and clears dirty tracking" do + run = Run.create!(task_name: "Maintenance::UpdatePostsTask") Run.find(run.id).running! run.reload_status @@ -58,8 +58,8 @@ class RunTest < ActiveSupport::TestCase refute run.changed? end - test '#reload_status does not use query cache' do - run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') + test "#reload_status does not use query cache" do + run = Run.create!(task_name: "Maintenance::UpdatePostsTask") query_count = count_uncached_queries do ActiveRecord::Base.connection.cache do run.reload_status @@ -69,10 +69,10 @@ class RunTest < ActiveSupport::TestCase assert_equal 2, query_count end - test '#stopping? returns true if status is pausing or cancelling' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#stopping? returns true if status is pausing or cancelling" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") - (Run.statuses.keys - ['pausing', 'cancelling']).each do |status| + (Run.statuses.keys - ["pausing", "cancelling"]).each do |status| run.status = status refute_predicate run, :stopping? end @@ -84,15 +84,15 @@ class RunTest < ActiveSupport::TestCase assert_predicate run, :stopping? end - test '#stopped? is true if Run is paused' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#stopped? is true if Run is paused" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") run.status = :paused assert_predicate run, :stopped? end - test '#stopped? is true if Run is completed' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#stopped? is true if Run is completed" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") Run::COMPLETED_STATUSES.each do |status| run.status = status @@ -100,8 +100,8 @@ class RunTest < ActiveSupport::TestCase end end - test '#stopped? is false if Run is not paused nor completed' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#stopped? is false if Run is not paused nor completed" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") Run::STATUSES.excluding(Run::COMPLETED_STATUSES, :paused).each do |status| run.status = status @@ -109,21 +109,21 @@ class RunTest < ActiveSupport::TestCase end end - test '#started? returns false if the Run has no started_at timestamp' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#started? returns false if the Run has no started_at timestamp" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") refute_predicate run, :started? end - test '#started? returns true if the Run has a started_at timestamp' do + test "#started? returns true if the Run has a started_at timestamp" do run = Run.new( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", started_at: Time.now ) assert_predicate run, :started? end - test '#completed? returns true if status is succeeded, errored, or cancelled' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#completed? returns true if status is succeeded, errored, or cancelled" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") (Run::STATUSES - Run::COMPLETED_STATUSES).each do |status| run.status = status @@ -136,8 +136,8 @@ class RunTest < ActiveSupport::TestCase end end - test '#active? returns true if status is among Run::ACTIVE_STATUSES' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#active? returns true if status is among Run::ACTIVE_STATUSES" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") (Run::STATUSES - Run::ACTIVE_STATUSES).each do |status| run.status = status @@ -150,18 +150,18 @@ class RunTest < ActiveSupport::TestCase end end - test '#estimated_completion_time returns nil if the run is completed' do + test "#estimated_completion_time returns nil if the run is completed" do run = Run.new( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :succeeded ) assert_nil run.estimated_completion_time end - test '#estimated_completion_time returns nil if tick_count is 0' do + test "#estimated_completion_time returns nil if tick_count is 0" do run = Run.new( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running, tick_count: 0, tick_total: 10 @@ -170,9 +170,9 @@ class RunTest < ActiveSupport::TestCase assert_nil run.estimated_completion_time end - test '#estimated_completion_time returns nil if no tick_total' do + test "#estimated_completion_time returns nil if no tick_total" do run = Run.new( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running, tick_count: 1 ) @@ -180,12 +180,12 @@ class RunTest < ActiveSupport::TestCase assert_nil run.estimated_completion_time end - test '#estimated_completion_time returns estimated completion time based on average time elapsed per tick' do + test "#estimated_completion_time returns estimated completion time based on average time elapsed per tick" do started_at = Time.utc(2020, 1, 9, 9, 41, 44) travel_to started_at + 9.seconds run = Run.new( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", started_at: started_at, status: :running, tick_count: 9, @@ -197,10 +197,10 @@ class RunTest < ActiveSupport::TestCase assert_equal expected_completion_time, run.estimated_completion_time end - test '#cancel transitions the Run to cancelling if not paused' do + test "#cancel transitions the Run to cancelling if not paused" do [:enqueued, :running, :pausing, :interrupted].each do |status| run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: status, ) run.cancel @@ -209,10 +209,10 @@ class RunTest < ActiveSupport::TestCase end end - test '#cancel transitions the Run to cancelled if paused and updates ended_at' do + test "#cancel transitions the Run to cancelled if paused and updates ended_at" do freeze_time run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :paused, ) run.cancel @@ -221,10 +221,10 @@ class RunTest < ActiveSupport::TestCase assert_equal Time.now, run.ended_at end - test '#stuck? returns true if the Run is cancelling and has not been updated in more than 5 minutes' do + test "#stuck? returns true if the Run is cancelling and has not been updated in more than 5 minutes" do freeze_time run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :cancelling, ) refute_predicate run, :stuck? @@ -233,11 +233,11 @@ class RunTest < ActiveSupport::TestCase assert_predicate run, :stuck? end - test '#stuck? does not return true for other statuses' do + test "#stuck? does not return true for other statuses" do freeze_time - Run.statuses.except('cancelling').each_key do |status| + Run.statuses.except("cancelling").each_key do |status| run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: status, ) travel 5.minutes @@ -245,10 +245,10 @@ class RunTest < ActiveSupport::TestCase end end - test '#cancel transitions from cancelling to cancelled if it has not been updated in more than 5 minutes' do + test "#cancel transitions from cancelling to cancelled if it has not been updated in more than 5 minutes" do freeze_time run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :cancelling, ) @@ -262,14 +262,14 @@ class RunTest < ActiveSupport::TestCase assert_equal Time.now, run.ended_at end - test '#enqueued! ensures the status is marked as changed' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#enqueued! ensures the status is marked as changed" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") run.enqueued! - assert_equal ['enqueued', 'enqueued'], run.status_previous_change + assert_equal ["enqueued", "enqueued"], run.status_previous_change end - test '#enqueued! prevents already enqueued Run to be enqueued' do - run = Run.new(task_name: 'Maintenance::UpdatePostsTask') + test "#enqueued! prevents already enqueued Run to be enqueued" do + run = Run.new(task_name: "Maintenance::UpdatePostsTask") run.enqueued! assert_raises(ActiveRecord::RecordInvalid) do run.enqueued! @@ -283,7 +283,7 @@ def count_uncached_queries(&block) query_cb = ->(*, payload) { count += 1 unless payload[:cached] } ActiveSupport::Notifications.subscribed(query_cb, - 'sql.active_record', + "sql.active_record", &block) count diff --git a/test/models/maintenance_tasks/runner_test.rb b/test/models/maintenance_tasks/runner_test.rb index 0287d428..b216e451 100644 --- a/test/models/maintenance_tasks/runner_test.rb +++ b/test/models/maintenance_tasks/runner_test.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class RunnerTest < ActiveSupport::TestCase include ActiveJob::TestHelper setup do - @name = 'Maintenance::UpdatePostsTask' + @name = "Maintenance::UpdatePostsTask" @runner = Runner @job = MaintenanceTasks.job.constantize - @csv = file_fixture('sample.csv') + @csv = file_fixture("sample.csv") end - test '#run creates and performs a Run for the given Task when there is no active Run' do + test "#run creates and performs a Run for the given Task when there is no active Run" do assert_difference -> { Run.where(task_name: @name).count }, 1 do assert_enqueued_with(job: @job) do assert_equal Maintenance::UpdatePostsTask, @runner.run(name: @name) @@ -21,7 +21,7 @@ class RunnerTest < ActiveSupport::TestCase end end - test '#run enqueues the existing active Run for the given Task' do + test "#run enqueues the existing active Run for the given Task" do run = Run.create!(task_name: @name, status: :paused) assert_no_difference -> { Run.where(task_name: @name).count } do @@ -32,23 +32,23 @@ class RunnerTest < ActiveSupport::TestCase end end - test '#run raises validation error if no Task for given name' do - assert_no_difference -> { Run.where(task_name: 'Invalid').count } do + test "#run raises validation error if no Task for given name" do + assert_no_difference -> { Run.where(task_name: "Invalid").count } do assert_no_enqueued_jobs do error = assert_raises(ActiveRecord::RecordInvalid) do - @runner.run(name: 'Invalid') + @runner.run(name: "Invalid") end assert_equal( - 'Validation failed: Task name is not included in the list', + "Validation failed: Task name is not included in the list", error.message ) end end end - test '#run raises enqueuing errors if enqueuing raises' do - @job.expects(:perform_later).raises(RuntimeError, 'error') + test "#run raises enqueuing errors if enqueuing raises" do + @job.expects(:perform_later).raises(RuntimeError, "error") assert_no_enqueued_jobs do error = assert_raises(Runner::EnqueuingError) do @runner.run(name: @name) @@ -59,11 +59,11 @@ class RunnerTest < ActiveSupport::TestCase error.message ) assert_kind_of RuntimeError, error.cause - assert_equal 'error', error.cause.message + assert_equal "error", error.cause.message end end - test '#run raises enqueuing errors if enqueuing is unsuccessful' do + test "#run raises enqueuing errors if enqueuing is unsuccessful" do @job.expects(:perform_later).returns(false) assert_no_enqueued_jobs do error = assert_raises(Runner::EnqueuingError) do @@ -77,35 +77,35 @@ class RunnerTest < ActiveSupport::TestCase assert_kind_of RuntimeError, error.cause assert_equal( "The job to perform #{@name} could not be enqueued. "\ - 'Enqueuing has been prevented by a callback.', + "Enqueuing has been prevented by a callback.", error.cause.message ) end end - test '#run attaches CSV file to Run if one is provided' do - @runner.run(name: 'Maintenance::ImportPostsTask', csv_file: csv_io) + test "#run attaches CSV file to Run if one is provided" do + @runner.run(name: "Maintenance::ImportPostsTask", csv_file: csv_io) run = Run.last assert_predicate run.csv_file, :attached? assert_equal File.read(@csv), run.csv_file.download end - test '#run raises if CSV file is provided but Task does not process CSVs' do + test "#run raises if CSV file is provided but Task does not process CSVs" do assert_no_difference -> { Run.where(task_name: @name).count } do error = assert_raises(ActiveRecord::RecordInvalid) do @runner.run(name: @name, csv_file: csv_io) end assert_equal( - 'Validation failed: Csv file should not be attached to non-CSV Task.', + "Validation failed: Csv file should not be attached to non-CSV Task.", error.message ) end end - test '#run raises if no CSV file is provided and Task processes CSVs' do - task_name = 'Maintenance::ImportPostsTask' + test "#run raises if no CSV file is provided and Task processes CSVs" do + task_name = "Maintenance::ImportPostsTask" assert_no_difference -> { Run.where(task_name: task_name).count } do assert_no_enqueued_jobs do error = assert_raises(ActiveRecord::RecordInvalid) do @@ -113,7 +113,7 @@ class RunnerTest < ActiveSupport::TestCase end assert_equal( - 'Validation failed: Csv file must be attached to CSV Task.', + "Validation failed: Csv file must be attached to CSV Task.", error.message ) end @@ -123,11 +123,11 @@ class RunnerTest < ActiveSupport::TestCase private def csv_io - { io: File.open(@csv), filename: 'sample.csv' } + { io: File.open(@csv), filename: "sample.csv" } end - test '#new raises deprecation warning and returns self' do - dep_msg = 'Use Runner.run instead of Runner.new.run' + test "#new raises deprecation warning and returns self" do + dep_msg = "Use Runner.run instead of Runner.new.run" assert_deprecated(dep_msg) do assert_equal Runner, Runner.new end diff --git a/test/models/maintenance_tasks/runs_page_test.rb b/test/models/maintenance_tasks/runs_page_test.rb index f4d996de..01a9dda8 100644 --- a/test/models/maintenance_tasks/runs_page_test.rb +++ b/test/models/maintenance_tasks/runs_page_test.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class RunsPageTest < ActiveSupport::TestCase setup do - @task_name = 'Maintenance::TestTask' + @task_name = "Maintenance::TestTask" 21.times do Run.create!( task_name: @task_name, @@ -19,28 +19,28 @@ class RunsPageTest < ActiveSupport::TestCase @runs = Run.where(task_name: @task_name).order(created_at: :desc) end - test '#records returns the most recent 20 runs when there is no cursor' do + test "#records returns the most recent 20 runs when there is no cursor" do runs_page = RunsPage.new(@runs, nil) assert_equal @runs.first(20), runs_page.records end - test '#records returns 20 runs after cursor if one is present' do + test "#records returns 20 runs after cursor if one is present" do runs_page = RunsPage.new(@runs, @runs.first.id) assert_equal @runs.last(20), runs_page.records end - test '#next_cursor returns the id of the last run in the record set' do + test "#next_cursor returns the id of the last run in the record set" do last_id = @runs.last.id runs_page = RunsPage.new(@runs, @runs.first.id) assert_equal last_id, runs_page.next_cursor end - test '#last? returns true if the last run in the record set is the last run for the relation' do + test "#last? returns true if the last run in the record set is the last run for the relation" do runs_page = RunsPage.new(@runs, @runs.first.id) assert_predicate runs_page, :last? end - test '#last? returns false if the last run in the record set is not the last run for the relation' do + test "#last? returns false if the last run in the record set is not the last run for the relation" do runs_page = RunsPage.new(@runs, nil) refute_predicate runs_page, :last? end diff --git a/test/models/maintenance_tasks/task_data_test.rb b/test/models/maintenance_tasks/task_data_test.rb index 26589e12..d11d9916 100644 --- a/test/models/maintenance_tasks/task_data_test.rb +++ b/test/models/maintenance_tasks/task_data_test.rb @@ -1,146 +1,146 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class TaskDataTest < ActiveSupport::TestCase - test '.find returns a TaskData for an existing Task' do - task_data = TaskData.find('Maintenance::UpdatePostsTask') - assert_equal 'Maintenance::UpdatePostsTask', task_data.name + test ".find returns a TaskData for an existing Task" do + task_data = TaskData.find("Maintenance::UpdatePostsTask") + assert_equal "Maintenance::UpdatePostsTask", task_data.name end - test '.find returns a TaskData for a deleted Task with a Run' do - task_data = TaskData.find('Maintenance::DeletedTask') - assert_equal 'Maintenance::DeletedTask', task_data.name + test ".find returns a TaskData for a deleted Task with a Run" do + task_data = TaskData.find("Maintenance::DeletedTask") + assert_equal "Maintenance::DeletedTask", task_data.name end - test '.find raises if the Task does not exist' do + test ".find raises if the Task does not exist" do assert_raises Task::NotFoundError do - TaskData.find('Maintenance::DoesNotExist') + TaskData.find("Maintenance::DoesNotExist") end end - test '.available_tasks returns a list of Tasks as TaskData, ordered alphabetically by name' do + test ".available_tasks returns a list of Tasks as TaskData, ordered alphabetically by name" do expected = [ - 'Maintenance::CancelledEnqueueTask', - 'Maintenance::EnqueueErrorTask', - 'Maintenance::ErrorTask', - 'Maintenance::ImportPostsTask', - 'Maintenance::TestTask', - 'Maintenance::UpdatePostsTask', + "Maintenance::CancelledEnqueueTask", + "Maintenance::EnqueueErrorTask", + "Maintenance::ErrorTask", + "Maintenance::ImportPostsTask", + "Maintenance::TestTask", + "Maintenance::UpdatePostsTask", ] assert_equal expected, TaskData.available_tasks.map(&:name) end - test '#new sets last_run if one is passed as an argument' do - run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') - task_data = TaskData.new('Maintenance::UpdatePostsTask', run) + test "#new sets last_run if one is passed as an argument" do + run = Run.create!(task_name: "Maintenance::UpdatePostsTask") + task_data = TaskData.new("Maintenance::UpdatePostsTask", run) - assert_equal 'Maintenance::UpdatePostsTask', task_data.to_s + assert_equal "Maintenance::UpdatePostsTask", task_data.to_s end - test '#code returns the code source of the Task' do - task_data = TaskData.new('Maintenance::UpdatePostsTask') + test "#code returns the code source of the Task" do + task_data = TaskData.new("Maintenance::UpdatePostsTask") - assert_equal 'class UpdatePostsTask < MaintenanceTasks::Task', + assert_equal "class UpdatePostsTask < MaintenanceTasks::Task", task_data.code.each_line.grep(/UpdatePostsTask/).first.squish end - test '#code returns nil if the Task does not exist' do - task_data = TaskData.new('Maintenance::DoesNotExist') + test "#code returns nil if the Task does not exist" do + task_data = TaskData.new("Maintenance::DoesNotExist") assert_nil task_data.code end - test '#last_run returns the last Run associated with the Task' do + test "#last_run returns the last Run associated with the Task" do Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :succeeded ) - latest = Run.create!(task_name: 'Maintenance::UpdatePostsTask') - task_data = TaskData.new('Maintenance::UpdatePostsTask') + latest = Run.create!(task_name: "Maintenance::UpdatePostsTask") + task_data = TaskData.new("Maintenance::UpdatePostsTask") assert_equal latest, task_data.last_run end - test '#to_s returns the name of the Task' do - task_data = TaskData.new('Maintenance::UpdatePostsTask') + test "#to_s returns the name of the Task" do + task_data = TaskData.new("Maintenance::UpdatePostsTask") - assert_equal 'Maintenance::UpdatePostsTask', task_data.to_s + assert_equal "Maintenance::UpdatePostsTask", task_data.to_s end - test '#previous_runs returns all Runs for the Task except the first one' do + test "#previous_runs returns all Runs for the Task except the first one" do run_1 = maintenance_tasks_runs(:update_posts_task) run_2 = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :succeeded ) - Run.create!(task_name: 'Maintenance::UpdatePostsTask') + Run.create!(task_name: "Maintenance::UpdatePostsTask") - task_data = TaskData.find('Maintenance::UpdatePostsTask') + task_data = TaskData.find("Maintenance::UpdatePostsTask") assert_equal 2, task_data.previous_runs.count assert_equal run_2, task_data.previous_runs.first assert_equal run_1, task_data.previous_runs.last end - test '#previous_runs is empty when there are no Runs for the Task' do + test "#previous_runs is empty when there are no Runs for the Task" do Run.destroy_all - task_data = TaskData.find('Maintenance::UpdatePostsTask') + task_data = TaskData.find("Maintenance::UpdatePostsTask") assert_empty task_data.previous_runs end - test '#deleted? returns true if the Task does not exist' do - assert_predicate TaskData.new('Maintenance::DoesNotExist'), :deleted? + test "#deleted? returns true if the Task does not exist" do + assert_predicate TaskData.new("Maintenance::DoesNotExist"), :deleted? end - test '#deleted? returns false for an existing Task' do - refute_predicate TaskData.new('Maintenance::UpdatePostsTask'), :deleted? + test "#deleted? returns false for an existing Task" do + refute_predicate TaskData.new("Maintenance::UpdatePostsTask"), :deleted? end - test '#status is new when Task does not have any Runs' do + test "#status is new when Task does not have any Runs" do Run.destroy_all - task_data = TaskData.find('Maintenance::UpdatePostsTask') - assert_equal 'new', task_data.status + task_data = TaskData.find("Maintenance::UpdatePostsTask") + assert_equal "new", task_data.status end - test '#status is the latest Run status' do - Run.create!(task_name: 'Maintenance::UpdatePostsTask', status: :paused) - task_data = TaskData.find('Maintenance::UpdatePostsTask') - assert_equal 'paused', task_data.status + test "#status is the latest Run status" do + Run.create!(task_name: "Maintenance::UpdatePostsTask", status: :paused) + task_data = TaskData.find("Maintenance::UpdatePostsTask") + assert_equal "paused", task_data.status end - test '#category returns :active if the task is active' do - Run.create!(task_name: 'Maintenance::UpdatePostsTask') - task_data = TaskData.new('Maintenance::UpdatePostsTask') + test "#category returns :active if the task is active" do + Run.create!(task_name: "Maintenance::UpdatePostsTask") + task_data = TaskData.new("Maintenance::UpdatePostsTask") assert_equal :active, task_data.category end - test '#category returns :new if the task is new' do - assert_equal :new, TaskData.new('Maintenance::SomeNewTask').category + test "#category returns :new if the task is new" do + assert_equal :new, TaskData.new("Maintenance::SomeNewTask").category end - test '#category returns :completed if the task is completed' do + test "#category returns :completed if the task is completed" do Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :succeeded ) - task_data = TaskData.new('Maintenance::UpdatePostsTask') + task_data = TaskData.new("Maintenance::UpdatePostsTask") assert_equal :completed, task_data.category end - test '#csv_task? returns true if the Task includes the CsvTask module' do - assert_predicate TaskData.new('Maintenance::ImportPostsTask'), :csv_task? + test "#csv_task? returns true if the Task includes the CsvTask module" do + assert_predicate TaskData.new("Maintenance::ImportPostsTask"), :csv_task? end - test '#csv_task? returns false if the Task does not include the CsvTask module' do - refute_predicate TaskData.new('Maintenance::UpdatePostsTask'), :csv_task? + test "#csv_task? returns false if the Task does not include the CsvTask module" do + refute_predicate TaskData.new("Maintenance::UpdatePostsTask"), :csv_task? end - test '#csv_task? returns false if the Task is deleted' do - refute_predicate TaskData.new('Maintenance::DoesNotExist'), :csv_task? + test "#csv_task? returns false if the Task is deleted" do + refute_predicate TaskData.new("Maintenance::DoesNotExist"), :csv_task? end end end diff --git a/test/models/maintenance_tasks/ticker_test.rb b/test/models/maintenance_tasks/ticker_test.rb index 38260385..ba72aa08 100644 --- a/test/models/maintenance_tasks/ticker_test.rb +++ b/test/models/maintenance_tasks/ticker_test.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class TickerTest < ActiveSupport::TestCase setup { freeze_time } - test '#ticks persists if enough time has passed' do + test "#ticks persists if enough time has passed" do ticker = Ticker.new(0) do |ticks, duration| @ticks = ticks @duration = duration @@ -24,7 +24,7 @@ class TickerTest < ActiveSupport::TestCase refute @called end - test '#tick persists if the tick happens after the duration has passed' do + test "#tick persists if the tick happens after the duration has passed" do ticker = Ticker.new(1.second) do |ticks, duration| @ticks = ticks @duration = duration @@ -35,7 +35,7 @@ class TickerTest < ActiveSupport::TestCase assert_equal 2, @duration end - test '#tick persists multiple ticks after the duration has passed' do + test "#tick persists multiple ticks after the duration has passed" do ticker = Ticker.new(1.second) do |ticks, duration| @ticks = ticks @duration = duration diff --git a/test/system/maintenance_tasks/runs_test.rb b/test/system/maintenance_tasks/runs_test.rb index 14f32c9d..99d0f52f 100644 --- a/test/system/maintenance_tasks/runs_test.rb +++ b/test/system/maintenance_tasks/runs_test.rb @@ -1,47 +1,47 @@ # frozen_string_literal: true -require 'application_system_test_case' +require "application_system_test_case" module MaintenanceTasks class RunsTest < ApplicationSystemTestCase - test 'run a Task' do + test "run a Task" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') - click_on 'Run' + click_on("Maintenance::UpdatePostsTask") + click_on "Run" - assert_title 'Maintenance::UpdatePostsTask' - assert_text 'Enqueued' - assert_text 'Waiting to start.' - assert_no_button 'Run' + assert_title "Maintenance::UpdatePostsTask" + assert_text "Enqueued" + assert_text "Waiting to start." + assert_no_button "Run" end - test 'run a CSV Task' do + test "run a CSV Task" do visit maintenance_tasks_path - click_on('Maintenance::ImportPostsTask') - attach_file('csv_file', 'test/fixtures/files/sample.csv') - click_on 'Run' + click_on("Maintenance::ImportPostsTask") + attach_file("csv_file", "test/fixtures/files/sample.csv") + click_on "Run" - assert_title 'Maintenance::ImportPostsTask' - assert_text 'Enqueued' - assert_text 'Waiting to start.' - assert_no_button 'Run' + assert_title "Maintenance::ImportPostsTask" + assert_text "Enqueued" + assert_text "Waiting to start." + assert_no_button "Run" end - test 'download the CSV attached to a run for a CSV Task' do + test "download the CSV attached to a run for a CSV Task" do visit(maintenance_tasks_path) - click_on('Maintenance::ImportPostsTask') - attach_file('csv_file', 'test/fixtures/files/sample.csv') - click_on('Run') + click_on("Maintenance::ImportPostsTask") + attach_file("csv_file", "test/fixtures/files/sample.csv") + click_on("Run") perform_enqueued_jobs page.refresh - click_on('Download CSV') + click_on("Download CSV") - downloaded_csv = 'test/dummy/tmp/downloads/sample.csv' + downloaded_csv = "test/dummy/tmp/downloads/sample.csv" Timeout.timeout(1) do sleep(0.1) until File.exist?(downloaded_csv) @@ -49,148 +49,148 @@ class RunsTest < ApplicationSystemTestCase assert(File.exist?(downloaded_csv)) end - test 'pause a Run' do + test "pause a Run" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') - click_on 'Run' - click_on 'Pause' + click_on("Maintenance::UpdatePostsTask") + click_on "Run" + click_on "Pause" - assert_text 'Pausing' - assert_text 'Pausing…' + assert_text "Pausing" + assert_text "Pausing…" end - test 'resume a Run' do + test "resume a Run" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') - click_on 'Run' - click_on 'Pause' + click_on("Maintenance::UpdatePostsTask") + click_on "Run" + click_on "Pause" perform_enqueued_jobs page.refresh - click_on 'Resume' + click_on "Resume" - assert_text 'Enqueued' - assert_text 'Waiting to start.' + assert_text "Enqueued" + assert_text "Waiting to start." end - test 'cancel a Run' do + test "cancel a Run" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') - click_on 'Run' - click_on 'Cancel' + click_on("Maintenance::UpdatePostsTask") + click_on "Run" + click_on "Cancel" - assert_text 'Cancelling' - assert_text 'Cancelling…' + assert_text "Cancelling" + assert_text "Cancelling…" end - test 'cancel a pausing Run' do + test "cancel a pausing Run" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') - click_on 'Run' - click_on 'Pause' - assert_text 'Pausing' + click_on("Maintenance::UpdatePostsTask") + click_on "Run" + click_on "Pause" + assert_text "Pausing" - click_on 'Cancel' - assert_text 'Cancelling…' + click_on "Cancel" + assert_text "Cancelling…" end - test 'cancel a stuck Run' do + test "cancel a stuck Run" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') - click_on 'Run' - click_on 'Cancel' + click_on("Maintenance::UpdatePostsTask") + click_on "Run" + click_on "Cancel" - assert_text 'Cancelling…' - refute_button 'Cancel' + assert_text "Cancelling…" + refute_button "Cancel" travel 5.minutes refresh - click_on 'Cancel' + click_on "Cancel" end - test 'cancel a deleted task' do - visit maintenance_tasks_path + '/tasks/Maintenance::PausedDeletedTask' + test "cancel a deleted task" do + visit maintenance_tasks_path + "/tasks/Maintenance::PausedDeletedTask" - click_on 'Cancel' + click_on "Cancel" - assert_text 'Cancelled' + assert_text "Cancelled" end - test 'run a Task that errors' do + test "run a Task that errors" do visit maintenance_tasks_path - click_on('Maintenance::ErrorTask') + click_on("Maintenance::ErrorTask") perform_enqueued_jobs do - click_on 'Run' + click_on "Run" end - assert_text 'Errored' - assert_text 'Ran for less than 5 seconds until an error happened '\ - 'less than a minute ago.' - assert_text 'ArgumentError' - assert_text 'Something went wrong' + assert_text "Errored" + assert_text "Ran for less than 5 seconds until an error happened "\ + "less than a minute ago." + assert_text "ArgumentError" + assert_text "Something went wrong" assert_text "app/tasks/maintenance/error_task.rb:9:in `process'" end - test 'errors for double enqueue are shown' do + test "errors for double enqueue are shown" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') + click_on("Maintenance::UpdatePostsTask") url = page.current_url using_session(:other_tab) do visit url - click_on 'Run' - click_on 'Pause' + click_on "Run" + click_on "Pause" end - click_on 'Run' + click_on "Run" - alert_text = 'Validation failed: ' \ - 'Status Cannot transition run from status pausing to enqueued' + alert_text = "Validation failed: " \ + "Status Cannot transition run from status pausing to enqueued" assert_text alert_text end - test 'errors when enqueuing are shown' do + test "errors when enqueuing are shown" do visit maintenance_tasks_path - click_on 'Maintenance::EnqueueErrorTask' - click_on 'Run' - assert_text 'The job to perform Maintenance::EnqueueErrorTask '\ - 'could not be enqueued' - assert_text 'Error enqueuing' + click_on "Maintenance::EnqueueErrorTask" + click_on "Run" + assert_text "The job to perform Maintenance::EnqueueErrorTask "\ + "could not be enqueued" + assert_text "Error enqueuing" visit maintenance_tasks_path - click_on 'Maintenance::CancelledEnqueueTask' - click_on 'Run' - assert_text 'The job to perform Maintenance::CancelledEnqueueTask '\ - 'could not be enqueued' - assert_text 'The job to perform Maintenance::CancelledEnqueueTask '\ - 'could not be enqueued. Enqueuing has been prevented by a callback.' + click_on "Maintenance::CancelledEnqueueTask" + click_on "Run" + assert_text "The job to perform Maintenance::CancelledEnqueueTask "\ + "could not be enqueued" + assert_text "The job to perform Maintenance::CancelledEnqueueTask "\ + "could not be enqueued. Enqueuing has been prevented by a callback." end - test 'errors for invalid pause or cancel due to stale UI are shown' do + test "errors for invalid pause or cancel due to stale UI are shown" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') + click_on("Maintenance::UpdatePostsTask") url = page.current_url - click_on 'Run' + click_on "Run" using_session(:other_tab) do visit url - click_on 'Cancel' + click_on "Cancel" end - click_on 'Pause' + click_on "Pause" - alert_text = 'Validation failed: ' \ - 'Status Cannot transition run from status cancelling to pausing' + alert_text = "Validation failed: " \ + "Status Cannot transition run from status cancelling to pausing" assert_text alert_text end end diff --git a/test/system/maintenance_tasks/tasks_test.rb b/test/system/maintenance_tasks/tasks_test.rb index 29803441..61a13367 100644 --- a/test/system/maintenance_tasks/tasks_test.rb +++ b/test/system/maintenance_tasks/tasks_test.rb @@ -1,48 +1,48 @@ # frozen_string_literal: true -require 'application_system_test_case' +require "application_system_test_case" module MaintenanceTasks class TasksTest < ApplicationSystemTestCase - test 'list all tasks' do + test "list all tasks" do visit maintenance_tasks_path - assert_title 'Maintenance Tasks' + assert_title "Maintenance Tasks" - assert_link 'Maintenance::UpdatePostsTask' - assert_link 'Maintenance::ErrorTask' + assert_link "Maintenance::UpdatePostsTask" + assert_link "Maintenance::ErrorTask" end - test 'lists tasks by category' do + test "lists tasks by category" do visit maintenance_tasks_path expected = [ - 'New Tasks', + "New Tasks", "Maintenance::CancelledEnqueueTask\nNew", "Maintenance::EnqueueErrorTask\nNew", "Maintenance::ErrorTask\nNew", "Maintenance::ImportPostsTask\nNew", "Maintenance::TestTask\nNew", - 'Completed Tasks', + "Completed Tasks", "Maintenance::UpdatePostsTask\nSucceeded", ] - assert_equal expected, page.all('h3').map(&:text) + assert_equal expected, page.all("h3").map(&:text) end - test 'show a Task' do + test "show a Task" do visit maintenance_tasks_path - click_on('Maintenance::UpdatePostsTask') + click_on("Maintenance::UpdatePostsTask") - assert_title 'Maintenance::UpdatePostsTask' - assert_text 'Succeeded' - assert_text 'Ran for less than 5 seconds, finished 8 days ago.' + assert_title "Maintenance::UpdatePostsTask" + assert_text "Succeeded" + assert_text "Ran for less than 5 seconds, finished 8 days ago." end - test 'view a Task with multiple pages of Runs' do + test "view a Task with multiple pages of Runs" do Run.create!( - task_name: 'Maintenance::TestTask', + task_name: "Maintenance::TestTask", created_at: 1.hour.ago, started_at: 1.hour.ago, tick_count: 2, @@ -52,7 +52,7 @@ class TasksTest < ApplicationSystemTestCase ) 21.times do |i| Run.create!( - task_name: 'Maintenance::TestTask', + task_name: "Maintenance::TestTask", created_at: i.minutes.ago, started_at: i.minutes.ago, tick_count: 10, @@ -64,27 +64,27 @@ class TasksTest < ApplicationSystemTestCase visit maintenance_tasks_path - click_on('Maintenance::TestTask') - assert_no_text 'Errored' + click_on("Maintenance::TestTask") + assert_no_text "Errored" - click_on('Next page') - assert_text 'Errored' - assert_no_link 'Next page' + click_on("Next page") + assert_text "Errored" + assert_no_link "Next page" end - test 'show a deleted Task' do - visit maintenance_tasks_path + '/tasks/Maintenance::DeletedTask' + test "show a deleted Task" do + visit maintenance_tasks_path + "/tasks/Maintenance::DeletedTask" - assert_title 'Maintenance::DeletedTask' - assert_text 'Succeeded' - assert_button 'Run', disabled: true + assert_title "Maintenance::DeletedTask" + assert_text "Succeeded" + assert_button "Run", disabled: true end - test 'visit main page through iframe' do + test "visit main page through iframe" do visit root_path - within_frame('maintenance-tasks-iframe') do - assert_content 'Maintenance Tasks' + within_frame("maintenance-tasks-iframe") do + assert_content "Maintenance Tasks" end end end diff --git a/test/tasks/maintenance_tasks/csv_task_test.rb b/test/tasks/maintenance_tasks/csv_task_test.rb index ee6fda3d..983cd402 100644 --- a/test/tasks/maintenance_tasks/csv_task_test.rb +++ b/test/tasks/maintenance_tasks/csv_task_test.rb @@ -1,10 +1,10 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class CsvTaskTest < ActiveSupport::TestCase - test '.collection creates a CSV from the csv_content string' do - csv_file = file_fixture('sample.csv') + test ".collection creates a CSV from the csv_content string" do + csv_file = file_fixture("sample.csv") csv_task = Maintenance::ImportPostsTask.new csv_task.csv_content = csv_file.read @@ -14,12 +14,12 @@ class CsvTaskTest < ActiveSupport::TestCase assert collection.headers first_row = collection.first - assert_equal 'My Title 1', first_row['title'] - assert_equal 'Hello World 1!', first_row['content'] + assert_equal "My Title 1", first_row["title"] + assert_equal "Hello World 1!", first_row["content"] end - test '.count returns the number of rows to process, excluding headers and assuming a trailing newline' do - csv_file = file_fixture('sample.csv') + test ".count returns the number of rows to process, excluding headers and assuming a trailing newline" do + csv_file = file_fixture("sample.csv") csv_task = Maintenance::ImportPostsTask.new csv_task.csv_content = csv_file.read diff --git a/test/tasks/maintenance_tasks/task_test.rb b/test/tasks/maintenance_tasks/task_test.rb index 56c7c476..ad6624f6 100644 --- a/test/tasks/maintenance_tasks/task_test.rb +++ b/test/tasks/maintenance_tasks/task_test.rb @@ -1,70 +1,70 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class TaskTest < ActiveSupport::TestCase - test '.available_tasks returns list of tasks that inherit from the Task superclass' do + test ".available_tasks returns list of tasks that inherit from the Task superclass" do expected = [ - 'Maintenance::CancelledEnqueueTask', - 'Maintenance::EnqueueErrorTask', - 'Maintenance::ErrorTask', - 'Maintenance::ImportPostsTask', - 'Maintenance::TestTask', - 'Maintenance::UpdatePostsTask', + "Maintenance::CancelledEnqueueTask", + "Maintenance::EnqueueErrorTask", + "Maintenance::ErrorTask", + "Maintenance::ImportPostsTask", + "Maintenance::TestTask", + "Maintenance::UpdatePostsTask", ] assert_equal expected, MaintenanceTasks::Task.available_tasks.map(&:name).sort end - test '.named returns the task based on its name' do + test ".named returns the task based on its name" do expected_task = Maintenance::UpdatePostsTask - assert_equal expected_task, Task.named('Maintenance::UpdatePostsTask') + assert_equal expected_task, Task.named("Maintenance::UpdatePostsTask") end test ".named raises Not Found Error if the task doesn't exist" do error = assert_raises(Task::NotFoundError) do - Task.named('Maintenance::DoesNotExist') + Task.named("Maintenance::DoesNotExist") end - assert_equal 'Task Maintenance::DoesNotExist not found.', error.message - assert_equal 'Maintenance::DoesNotExist', error.name + assert_equal "Task Maintenance::DoesNotExist not found.", error.message + assert_equal "Maintenance::DoesNotExist", error.name end test ".named raises Not Found Error if the name doesn't refer to a Task" do error = assert_raises(Task::NotFoundError) do - Task.named('Array') + Task.named("Array") end - assert_equal 'Array is not a Task.', error.message - assert_equal 'Array', error.name + assert_equal "Array is not a Task.", error.message + assert_equal "Array", error.name end - test '.process calls #process' do + test ".process calls #process" do item = mock Maintenance::TestTask.any_instance.expects(:process).with(item) Maintenance::TestTask.process(item) end - test '.collection calls #collection' do + test ".collection calls #collection" do assert_equal [1, 2], Maintenance::TestTask.collection end - test '.count calls #count' do + test ".count calls #count" do assert_equal 2, Maintenance::TestTask.count end - test '#count is nil by default' do + test "#count is nil by default" do task = Task.new assert_nil task.count end - test '#collection raises NoMethodError' do + test "#collection raises NoMethodError" do error = assert_raises(NoMethodError) { Task.new.collection } - message = 'MaintenanceTasks::Task must implement `collection`.' + message = "MaintenanceTasks::Task must implement `collection`." assert_equal message, error.message end - test '#process raises NoMethodError' do - error = assert_raises(NoMethodError) { Task.new.process('an item') } - message = 'MaintenanceTasks::Task must implement `process`.' + test "#process raises NoMethodError" do + error = assert_raises(NoMethodError) { Task.new.process("an item") } + message = "MaintenanceTasks::Task must implement `process`." assert_equal message, error.message end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 43931046..619ced6c 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true # Configure Rails Environment -ENV['RAILS_ENV'] = 'test' +ENV["RAILS_ENV"] = "test" -require_relative '../test/dummy/config/environment' +require_relative "../test/dummy/config/environment" ActiveRecord::Migrator.migrations_paths = - [File.expand_path('../test/dummy/db/migrate', __dir__)] + [File.expand_path("../test/dummy/db/migrate", __dir__)] ActiveRecord::Migrator.migrations_paths << - File.expand_path('../db/migrate', __dir__) -require 'rails/test_help' -require 'mocha/minitest' + File.expand_path("../db/migrate", __dir__) +require "rails/test_help" +require "mocha/minitest" Mocha.configure do |c| c.display_matching_invocations_on_failure = true @@ -24,11 +24,11 @@ # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) - ActiveSupport::TestCase.fixture_path = File.expand_path('fixtures', __dir__) + ActiveSupport::TestCase.fixture_path = File.expand_path("fixtures", __dir__) ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path ActiveSupport::TestCase.file_fixture_path = - ActiveSupport::TestCase.fixture_path + '/files' + ActiveSupport::TestCase.fixture_path + "/files" ActiveSupport::TestCase.fixtures(:all) end diff --git a/test/validators/maintenance_tasks/run_status_validator_test.rb b/test/validators/maintenance_tasks/run_status_validator_test.rb index c8d76ce0..85c5cc2b 100644 --- a/test/validators/maintenance_tasks/run_status_validator_test.rb +++ b/test/validators/maintenance_tasks/run_status_validator_test.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" module MaintenanceTasks class RunStatusValidatorTest < ActiveSupport::TestCase - test 'run can go from enqueued or interrupted to running' do - enqueued_run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') + test "run can go from enqueued or interrupted to running" do + enqueued_run = Run.create!(task_name: "Maintenance::UpdatePostsTask") enqueued_run.status = :running assert enqueued_run.valid? interrupted_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :interrupted ) interrupted_run.status = :running @@ -20,9 +20,9 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert_no_invalid_transitions([:enqueued, :interrupted], :running) end - test 'run can go from paused to enqueued' do + test "run can go from paused to enqueued" do paused_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :paused ) paused_run.status = :enqueued @@ -32,9 +32,9 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert_no_invalid_transitions([:paused], :enqueued) end - test 'run can go from running, cancelling or pausing to succeeded' do + test "run can go from running, cancelling or pausing to succeeded" do running_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running ) running_run.status = :succeeded @@ -42,7 +42,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert running_run.valid? pausing_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :pausing ) pausing_run.status = :succeeded @@ -50,7 +50,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert pausing_run.valid? cancelling_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :cancelling ) cancelling_run.status = :succeeded @@ -63,14 +63,14 @@ class RunStatusValidatorTest < ActiveSupport::TestCase ) end - test 'run can go from enqueued, running, interrupted, pausing, or paused to cancelling' do - enqueued_run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') + test "run can go from enqueued, running, interrupted, pausing, or paused to cancelling" do + enqueued_run = Run.create!(task_name: "Maintenance::UpdatePostsTask") enqueued_run.status = :cancelling assert enqueued_run.valid? running_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running ) running_run.status = :cancelling @@ -78,7 +78,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert running_run.valid? interrupted_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :interrupted ) interrupted_run.status = :cancelling @@ -86,7 +86,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert interrupted_run.valid? pausing_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :pausing ) pausing_run.status = :cancelling @@ -94,7 +94,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert pausing_run.valid? paused_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :paused ) paused_run.status = :cancelling @@ -107,14 +107,14 @@ class RunStatusValidatorTest < ActiveSupport::TestCase ) end - test 'run can go from enqueued, interrupted or running to pausing' do - enqueued_run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') + test "run can go from enqueued, interrupted or running to pausing" do + enqueued_run = Run.create!(task_name: "Maintenance::UpdatePostsTask") enqueued_run.status = :pausing assert enqueued_run.valid? interrupted_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :interrupted ) interrupted_run.status = :pausing @@ -122,7 +122,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert interrupted_run.valid? running_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running ) running_run.status = :pausing @@ -135,9 +135,9 @@ class RunStatusValidatorTest < ActiveSupport::TestCase ) end - test 'run can go from pausing to paused' do + test "run can go from pausing to paused" do pausing_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :pausing ) pausing_run.status = :paused @@ -147,9 +147,9 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert_no_invalid_transitions([:pausing], :paused) end - test 'run can go from cancelling or paused to cancelled' do + test "run can go from cancelling or paused to cancelled" do cancelling_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :cancelling ) cancelling_run.status = :cancelled @@ -157,7 +157,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert cancelling_run.valid? paused_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :paused ) paused_run.status = :cancelled @@ -167,9 +167,9 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert_no_invalid_transitions([:cancelling, :paused], :cancelled) end - test 'run can go from running to interrupted' do + test "run can go from running to interrupted" do running_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running ) running_run.status = :interrupted @@ -179,14 +179,14 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert_no_invalid_transitions([:running], :interrupted) end - test 'run can go from enqueued, running, pausing, interrupted or cancelling to errored' do - enqueued_run = Run.create!(task_name: 'Maintenance::UpdatePostsTask') + test "run can go from enqueued, running, pausing, interrupted or cancelling to errored" do + enqueued_run = Run.create!(task_name: "Maintenance::UpdatePostsTask") enqueued_run.status = :errored assert enqueued_run.valid? running_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :running ) running_run.status = :errored @@ -194,7 +194,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert running_run.valid? pausing_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :pausing ) pausing_run.status = :errored @@ -202,7 +202,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert pausing_run.valid? interrupted_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :interrupted ) interrupted_run.status = :errored @@ -210,7 +210,7 @@ class RunStatusValidatorTest < ActiveSupport::TestCase assert interrupted_run.valid? cancelling_run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: :cancelling ) cancelling_run.status = :errored @@ -229,7 +229,7 @@ def assert_no_invalid_transitions(valid_starting_statuses, end_status) invalid_statuses = Run::STATUSES - valid_starting_statuses - [end_status] invalid_statuses.each do |status| run = Run.create!( - task_name: 'Maintenance::UpdatePostsTask', + task_name: "Maintenance::UpdatePostsTask", status: status )