deploy_pin 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 35a66d67226260fef29b9e01169afb28c1d36cda391c95d7a04e088f38b7c47c
4
- data.tar.gz: 38a5be44f0e79bf4a7d1b11f680439b895d8ab940058be5bb0f2aba0b2dd68e1
3
+ metadata.gz: 8b82546e12b8efb37175c7f4715df4dca0e86f3d29f337d7b19e9bf975bec893
4
+ data.tar.gz: 817165c4aafef54887c4881727a32000789ee05366d1b528d1a6ca7cda461023
5
5
  SHA512:
6
- metadata.gz: bf576786c356837a07b52da2822d51830f637e0353c12100ea98afc4c599d76f86b97a09f3972368798a5a4d3aaaef0c17686eb4d5d9a268e107b2cb14f813fb
7
- data.tar.gz: 296448270b06e13c0d7d87bf33badbb3563ae7e324e8f52d8a203ab7cbd111104a24ac0b489d409ee0257f116d53a3154bec14270bbdd612f01c501e6a3be0c5
6
+ metadata.gz: 642d508e1428b5cfc71451b8f60dd198f2cd8fa6ff1e6c0f33bb66461e8ab5346fa8b1beb7bb1802fe3bf49b8518995762996fea38413b5826e54516bda11dfe
7
+ data.tar.gz: 3b4c4686384e1cba64724c56ce3746a8f67e3c4964878299404c091e96b10123f1e75c2bb58fcd092c4a039e73908b8364e8335fd406beeba662692af4998e8a
data/README.md CHANGED
@@ -98,6 +98,7 @@ end
98
98
  rails g deploy_pin:task backfill_user_names -g I
99
99
 
100
100
  # 2. Write the code in lib/deploy_pin/<timestamp>_backfill_user_names.rb
101
+ # and its test in spec/deploy_pin/<timestamp>_backfill_user_names_spec.rb
101
102
 
102
103
  # 3. See what is pending
103
104
  rake deploy_pin:list
@@ -167,7 +168,7 @@ rake 'deploy_pin:run[I, !20190401135040]' # group I except one task
167
168
 
168
169
  | Command | Description |
169
170
  |---|---|
170
- | `rails g deploy_pin:task <title> -g <group>` | Generate a task. Options: `--parallel`, `--recurring --identifier <n>`, `-a <author>` |
171
+ | `rails g deploy_pin:task <title> -g <group>` | Generate a task and its [test](#testing-tasks). Options: `--parallel`, `--recurring --identifier <n>`, `-a <author>`, `--skip-test`, `--test-framework=rspec` |
171
172
  | `rake deploy_pin:list[...]` | List pending tasks, including their code |
172
173
  | `rake deploy_pin:short_list[...]` | List pending tasks by group, without the code |
173
174
  | `rake deploy_pin:run[...]` | Run pending tasks |
@@ -402,6 +403,38 @@ Task records are kept by a storage provider, set with `storage`:
402
403
 
403
404
  `DeployPin::Storage.record_class` returns the model of the configured provider. Statement timeouts and the parallel timeout rely on ActiveRecord. Without it, tasks run without a timeout.
404
405
 
406
+ ### Testing tasks
407
+
408
+ `rails g deploy_pin:task` also creates a spec for the task, at `spec/deploy_pin/<task file>_spec.rb`. The directory is created if it doesn't exist. The spec runs the task end to end, the same way a deploy does, through `rake 'deploy_pin:run[<identifier>]'`. It checks that the task runs without errors and is marked as done. Add your own expectations for what the task changes:
409
+
410
+ ```ruby
411
+ # spec/deploy_pin/20261124120000_backfill_user_names_spec.rb (generated)
412
+ RSpec.describe 'DeployPin task 20261124120000_backfill_user_names' do
413
+ subject(:run_task) { Rake::Task['deploy_pin:run'].invoke('20261124120000') }
414
+
415
+ # ...
416
+
417
+ it 'backfills user names' do
418
+ user = User.create!(email: 'user@example.com', name: nil)
419
+
420
+ expect { run_task }.to change { user.reload.name }.to('user@example.com')
421
+ end
422
+ end
423
+ ```
424
+
425
+ The spec turns off `continue_on_error`, so a failing task always fails its spec.
426
+
427
+ RSpec is the only supported framework for now. It is detected automatically when the `RSpec` constant is loaded, which is the case when `rspec-rails` is in the `:development` group, as rspec-rails recommends. If nothing is detected, the generator skips the test and says so. Set the framework and the directory, or turn test generation off, in the initializer:
428
+
429
+ ```ruby
430
+ DeployPin.setup do
431
+ test_framework :rspec # detected by default; `false` to not generate tests
432
+ tests_path 'spec/deploy_pin' # default for RSpec
433
+ end
434
+ ```
435
+
436
+ For a single task, pass `--skip-test` or `--test-framework=rspec` to the generator.
437
+
405
438
  ### Output formatting
406
439
 
407
440
  `run_formatter`, `list_formatter` and `short_list_formatter` control what the rake tasks print. The install generator writes working defaults into the initializer.
@@ -456,6 +489,8 @@ All options are set in `DeployPin.setup`. See the [API docs](https://rubydoc.inf
456
489
  | `statement_timeout` | — | Default database statement timeout |
457
490
  | `storage` | `:active_record` | `:active_record` or `:mongoid` |
458
491
  | `continue_on_error` | `false` | Log failed tasks and continue instead of stopping |
492
+ | `test_framework` | detected (`:rspec` if `RSpec` is loaded) | Test framework for generated task tests; `false` to skip them. See [Testing tasks](#testing-tasks) |
493
+ | `tests_path` | `'spec/deploy_pin'` | Directory for generated task tests |
459
494
  | `task_wrapper` | runs the task | `->(task, task_runner) { ... }` around every task, e.g. for logging or error reporting |
460
495
  | `deployment_state_transition` | off | See [Deployment state](#deployment-state) |
461
496
  | `run_formatter`, `list_formatter`, `short_list_formatter` | — | See [Output formatting](#output-formatting) |
@@ -132,9 +132,10 @@ module DeployPin
132
132
 
133
133
  # :reek:UtilityFunction and :reek:ControlParameter
134
134
  def run_with_timeout(task, &block)
135
- return yield unless task.under_timeout? && DeployPin::Database.available?
135
+ timeout = DeployPin.statement_timeout
136
+ return yield unless timeout && task.under_timeout? && DeployPin::Database.available?
136
137
 
137
- DeployPin::Database.execute_with_timeout(DeployPin.statement_timeout, **{}, &block)
138
+ DeployPin::Database.execute_with_timeout(timeout, **{}, &block)
138
139
  end
139
140
 
140
141
  def execution_duration
@@ -5,7 +5,9 @@ module DeployPin
5
5
  module Database
6
6
  extend self
7
7
 
8
- # Runs a block under a database statement timeout.
8
+ # Runs a block under a database statement timeout. On databases without
9
+ # statement timeouts (anything but PostgreSQL, MySQL and MariaDB, e.g.
10
+ # SQLite), the block runs without a timeout and a warning is printed once.
9
11
  #
10
12
  # @example Use the default {DeployPin.statement_timeout}
11
13
  # # 20190401135040:I
@@ -67,8 +69,20 @@ module DeployPin
67
69
  end
68
70
 
69
71
  def set_max_timeout(timeout)
72
+ engine = db_engine
73
+ return warn_unsupported_engine unless engine
74
+
70
75
  timeout_in_milliseconds = timeout.to_f.in_milliseconds.ceil # Make sure is always at least 1. 0 turns this off
71
- connection.execute db_engine::TIMEOUT_STATEMENT % connection.quote(timeout_in_milliseconds)
76
+ connection.execute engine::TIMEOUT_STATEMENT % connection.quote(timeout_in_milliseconds)
77
+ end
78
+
79
+ # Databases without a statement timeout (e.g. SQLite) run the block without one.
80
+ def warn_unsupported_engine
81
+ return if @unsupported_engine_warned
82
+
83
+ @unsupported_engine_warned = true
84
+ warn "[DeployPin] Statement timeouts are not supported for the #{connection.adapter_name} adapter; " \
85
+ 'running without a timeout.'
72
86
  end
73
87
 
74
88
  def db_engine
@@ -4,5 +4,16 @@ module DeployPin
4
4
  # Rails engine that loads the `deploy_pin:*` rake tasks.
5
5
  class Engine < ::Rails::Engine
6
6
  isolate_namespace DeployPin
7
+
8
+ # Task files (`20190401135040_backfill_users.rb`) are not constants, so
9
+ # Zeitwerk must not autoload them. Without this, an app that autoloads
10
+ # `lib/` (`config.autoload_lib`, the default since Rails 7.1) fails to
11
+ # boot once a task exists in `lib/deploy_pin`.
12
+ initializer 'deploy_pin.ignore_tasks_path', after: :load_config_initializers do |app|
13
+ tasks_path = DeployPin.tasks_path
14
+ next if tasks_path.blank?
15
+
16
+ Rails.autoloaders.each { |loader| loader.ignore(app.root.join(tasks_path)) }
17
+ end
7
18
  end
8
19
  end
@@ -57,7 +57,7 @@ module DeployPin
57
57
  attr_accessor :method_name, :parallel_args, :db_block
58
58
 
59
59
  def with_database_timeout(&block)
60
- return yield unless DeployPin::Database.available?
60
+ return yield unless DeployPin::Database.available? && timeout
61
61
 
62
62
  ActiveRecord::Base.connection_pool.with_connection do
63
63
  DeployPin::Database.execute_with_timeout(timeout, **timeout_params, &block)
@@ -2,5 +2,5 @@
2
2
 
3
3
  module DeployPin
4
4
  # The gem version.
5
- VERSION = '1.9.0'
5
+ VERSION = '1.10.0'
6
6
  end
data/lib/deploy_pin.rb CHANGED
@@ -100,6 +100,21 @@ require 'colorize'
100
100
  # @param val [Proc, nil] `->(task, task_runner) { ... }`; omit to read the current one
101
101
  # @return [Proc]
102
102
  #
103
+ # @!method self.test_framework(val = nil)
104
+ # Test framework for the test file that `rails g deploy_pin:task` creates
105
+ # next to each task; `false` turns test generation off. When not set, RSpec
106
+ # is used if the `RSpec` constant is loaded (e.g. rspec-rails in the
107
+ # `:development` group); otherwise no test is generated.
108
+ # @see TaskGenerator::TEST_FRAMEWORKS
109
+ # @param val [Symbol, false, nil] new value; omit to read the current one
110
+ # @return [Symbol, false, nil]
111
+ #
112
+ # @!method self.tests_path(val = nil)
113
+ # Directory for the tests that `rails g deploy_pin:task` creates. When not
114
+ # set, the test framework's default is used (`spec/deploy_pin` for RSpec).
115
+ # @param val [String, nil] new value; omit to read the current one
116
+ # @return [String, nil]
117
+ #
103
118
  # @!method self.tasks_path(val = nil)
104
119
  # Directory that holds task files.
105
120
  # @param val [String, nil] new value; omit to read the current one
@@ -123,6 +138,8 @@ module DeployPin
123
138
  storage
124
139
  task_wrapper
125
140
  tasks_path
141
+ test_framework
142
+ tests_path
126
143
  ].freeze
127
144
 
128
145
  # Values the options are reset to by {setup_defaults!}.
@@ -8,6 +8,9 @@ DeployPin.setup do
8
8
  groups %w[pre I II III]
9
9
  fallback_group 'III'
10
10
  statement_timeout 10.minutes
11
+ # Tests generated for each task: RSpec is used when it is loaded, or set it here.
12
+ # test_framework :rspec # false to not generate tests
13
+ # tests_path 'spec/deploy_pin'
11
14
  deployment_state_transition({
12
15
  ongoing: %w[I III],
13
16
  pending: 'rollback', # enters to pending step before "rollback"
@@ -6,3 +6,8 @@ Example:
6
6
 
7
7
  This will create:
8
8
  lib/deploy_pin/{task_id}_some_name_of_task.rb
9
+ spec/deploy_pin/{task_id}_some_name_of_task_spec.rb
10
+
11
+ The test framework comes from DeployPin.test_framework (default: rspec),
12
+ and the directory from DeployPin.tests_path (default: spec/deploy_pin).
13
+ Use --skip-test to not create the test, or --test-framework=rspec to pick one.
@@ -2,14 +2,34 @@
2
2
 
3
3
  module DeployPin
4
4
  # `rails g deploy_pin:task <title> --group <group> [--parallel] [--recurring --identifier <id>]`:
5
- # creates a task file in {DeployPin.tasks_path}.
5
+ # creates a task file in {DeployPin.tasks_path}, and a test for it with
6
+ # the configured {DeployPin.test_framework} in {DeployPin.tests_path}
7
+ # (`spec/deploy_pin` for RSpec by default).
8
+ #
9
+ # @example Skip the test, or pick the framework for one task
10
+ # rails g deploy_pin:task backfill_users -g I --skip-test
11
+ # rails g deploy_pin:task backfill_users -g I --test-framework=rspec
6
12
  class TaskGenerator < Rails::Generators::Base
13
+ # Supported test frameworks: the default directory for the tests (used
14
+ # when {DeployPin.tests_path} is not set) and the test file name, where
15
+ # `%<task>s` is the task file name without `.rb`.
16
+ TEST_FRAMEWORKS = {
17
+ rspec: { path: 'spec/deploy_pin', file: '%<task>s_spec.rb' }
18
+ }.freeze
19
+
20
+ # Printed when no test framework is configured and none is detected.
21
+ UNDETECTED_TEST_FRAMEWORK = 'test for the task: no test framework detected. ' \
22
+ 'Add rspec-rails to the :development group, or set DeployPin.test_framework :rspec'
23
+
7
24
  class_option :parallel, type: :boolean, aliases: '-p'
8
25
  class_option :recurring, type: :boolean, aliases: '-r'
9
26
  class_option :identifier, aliases: '-i'
10
27
  argument :title, required: true
11
28
  class_option :group, aliases: '-g', default: DeployPin.fallback_group
12
29
  class_option :author, aliases: '-a'
30
+ class_option :test_framework, type: :string,
31
+ desc: "Test framework for the task's test (default: DeployPin.test_framework)"
32
+ class_option :skip_test, type: :boolean, default: false, desc: 'Do not generate a test for the task'
13
33
 
14
34
  source_root File.expand_path('templates', __dir__)
15
35
 
@@ -34,18 +54,77 @@ module DeployPin
34
54
  @group = options[:group]
35
55
  @recurring = options[:recurring]
36
56
  @identifier = @recurring ? options[:identifier] : Time.now.strftime('%Y%m%d%H%M%S')
37
- filename = @recurring ? "r_#{@identifier}_#{title}.rb" : "#{@identifier}_#{title}.rb"
38
- template template_file, "#{DeployPin.tasks_path}/#{filename}"
57
+ template template_file, task_path
39
58
  end
40
59
 
60
+ # Writes the test for the task, unless tests are turned off.
41
61
  # @return [void]
42
- # @raise [Thor::Error] if the group is missing or not in {DeployPin.groups}
62
+ def create_test_file
63
+ framework = test_framework
64
+ return if framework == false # turned off on purpose
65
+ return say_status(:skip, UNDETECTED_TEST_FRAMEWORK, :yellow) unless framework
66
+
67
+ template "#{framework}/task_spec.rb.erb", test_file_path(framework)
68
+ end
69
+
70
+ # @return [void]
71
+ # @raise [Thor::Error] if the group is missing or not in {DeployPin.groups},
72
+ # or the test framework is not one of {TEST_FRAMEWORKS}
43
73
  def validate
44
74
  raise Thor::Error, set_color('Missing required option: --group', :red) if options[:group].blank?
45
75
 
46
- return if DeployPin.groups.include?(options[:group])
76
+ unless DeployPin.groups.include?(options[:group])
77
+ raise Thor::Error, set_color("Group '#{options[:group]}' is not defined in DeployPin.groups", :red)
78
+ end
47
79
 
48
- raise Thor::Error, set_color("Group '#{options[:group]}' is not defined in DeployPin.groups", :red)
80
+ validate_test_framework
49
81
  end
82
+
83
+ private
84
+
85
+ # The task file name without the extension, e.g. `20190401135040_backfill_users`.
86
+ def task_name
87
+ @recurring ? "r_#{@identifier}_#{title}" : "#{@identifier}_#{title}"
88
+ end
89
+
90
+ def task_path
91
+ "#{DeployPin.tasks_path}/#{task_name}.rb"
92
+ end
93
+
94
+ # The test file in {DeployPin.tests_path}, or in the framework's default directory.
95
+ def test_file_path(framework)
96
+ settings = TEST_FRAMEWORKS.fetch(framework)
97
+ directory = DeployPin.tests_path.presence || settings[:path]
98
+
99
+ File.join(directory.to_s, format(settings[:file], task: task_name))
100
+ end
101
+
102
+ # The --test-framework flag or DeployPin.test_framework, else the detected one.
103
+ #
104
+ # @return [Symbol, false, nil] the framework; false when tests are turned
105
+ # off (--skip-test, `test_framework false`); nil when none is detected
106
+ def test_framework
107
+ return false if options[:skip_test]
108
+
109
+ configured = options[:test_framework].presence || DeployPin.test_framework
110
+ return configured if configured == false
111
+
112
+ configured&.to_sym || detected_test_framework
113
+ end
114
+
115
+ # RSpec is the only supported framework, detected by its constant
116
+ # (no dependency on Rails' generator settings).
117
+ def detected_test_framework
118
+ :rspec if defined?(::RSpec)
119
+ end
120
+
121
+ def validate_test_framework
122
+ framework = test_framework
123
+ return if !framework || TEST_FRAMEWORKS.key?(framework)
124
+
125
+ raise Thor::Error, set_color(
126
+ "Unknown test framework '#{framework}'. Supported: #{TEST_FRAMEWORKS.keys.join(', ')}", :red
127
+ )
128
+ end
50
129
  end
51
130
  end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails_helper'
4
+ require 'rake'
5
+
6
+ # Runs the task end to end, the same way a deploy does: `rake 'deploy_pin:run[<%= @identifier %>]'`.
7
+ RSpec.describe 'DeployPin task <%= task_name %>' do
8
+ subject(:run_task) { Rake::Task['deploy_pin:run'].invoke('<%= @identifier %>') }
9
+
10
+ before(:all) { Rails.application.load_tasks unless Rake::Task.task_defined?('deploy_pin:run') }
11
+
12
+ before do
13
+ Rake::Task['deploy_pin:run'].reenable
14
+ # A failing task must fail the spec, even if continue_on_error is enabled in this environment.
15
+ allow(DeployPin).to receive(:continue_on_error).and_return(false)
16
+ end
17
+
18
+ it 'runs without errors' do
19
+ expect { run_task }.not_to raise_error
20
+ end
21
+ <% unless @recurring -%>
22
+
23
+ it 'is marked as done' do
24
+ run_task
25
+
26
+ expect(DeployPin::Storage.record_class.find_by(uuid: <%= @identifier %>)&.completed_at).to be_present
27
+ end
28
+ <% end -%>
29
+
30
+ # Describe what the task changes, for example:
31
+ #
32
+ # it 'backfills user names' do
33
+ # user = User.create!(email: 'user@example.com', name: nil)
34
+ #
35
+ # expect { run_task }.to change { user.reload.name }.to('user@example.com')
36
+ # end
37
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: deploy_pin
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.9.0
4
+ version: 1.10.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Viktor Sych
@@ -332,6 +332,7 @@ files:
332
332
  - lib/generators/deploy_pin/task/USAGE
333
333
  - lib/generators/deploy_pin/task/task_generator.rb
334
334
  - lib/generators/deploy_pin/task/templates/parallel_task.rb.erb
335
+ - lib/generators/deploy_pin/task/templates/rspec/task_spec.rb.erb
335
336
  - lib/generators/deploy_pin/task/templates/task.rb.erb
336
337
  - lib/generators/deploy_pin/upgrade/USAGE
337
338
  - lib/generators/deploy_pin/upgrade/templates/upgrade_deploy_pins.rb