Skip to content

Commit

Permalink
Merge pull request #38 from viralpraxis/fix-new-thread-cop-for-thread…
Browse files Browse the repository at this point in the history
…-with-arguments
  • Loading branch information
mikegee authored Sep 8, 2024
2 parents 9d6e12b + fa872de commit b68c6b5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
8 changes: 3 additions & 5 deletions lib/rubocop/cop/thread_safety/new_thread.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,15 @@ module ThreadSafety
# Thread.new { do_work }
class NewThread < Base
MSG = 'Avoid starting new threads.'
RESTRICT_ON_SEND = %i[new].freeze
RESTRICT_ON_SEND = %i[new fork start].freeze

# @!method new_thread?(node)
def_node_matcher :new_thread?, <<~MATCHER
(send (const {nil? cbase} :Thread) :new)
(send (const {nil? cbase} :Thread) {:new :fork :start} ...)
MATCHER

def on_send(node)
return unless new_thread?(node)

add_offense(node)
new_thread?(node) { add_offense(node) }
end
end
end
Expand Down
34 changes: 32 additions & 2 deletions spec/rubocop/cop/thread_safety/new_thread_spec.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,47 @@
# frozen_string_literal: true

RSpec.describe RuboCop::Cop::ThreadSafety::NewThread, :config do
let(:msg) { 'Avoid starting new threads.' }

it 'registers an offense for starting a new thread' do
expect_offense(<<~RUBY)
Thread.new { do_work }
^^^^^^^^^^ Avoid starting new threads.
^^^^^^^^^^ #{msg}
RUBY
end

it 'registers an offense for starting a new thread with positional arguments' do
expect_offense(<<~RUBY)
Thread.new(1) { do_work }
^^^^^^^^^^^^^ #{msg}
RUBY
end

it 'registers an offense for starting a new thread with keyword arguments' do
expect_offense(<<~RUBY)
Thread.new(a: 42) { do_work }
^^^^^^^^^^^^^^^^^ #{msg}
RUBY
end

it 'registers an offense for starting a new thread with `fork` method' do
expect_offense(<<~RUBY)
Thread.fork { do_work }
^^^^^^^^^^^ #{msg}
RUBY
end

it 'registers an offense for starting a new thread with `start` method' do
expect_offense(<<~RUBY)
Thread.start { do_work }
^^^^^^^^^^^^ #{msg}
RUBY
end

it 'registers an offense for starting a new thread with top-level constant' do
expect_offense(<<~RUBY)
::Thread.new { do_work }
^^^^^^^^^^^^ Avoid starting new threads.
^^^^^^^^^^^^ #{msg}
RUBY
end

Expand Down

0 comments on commit b68c6b5

Please sign in to comment.