Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ThreadSafety::NewThread cop #38

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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