From fa872de2997356720f2382d8df62e3943776c42f Mon Sep 17 00:00:00 2001 From: viralpraxis Date: Sun, 8 Sep 2024 00:16:48 +0300 Subject: [PATCH] Fix `ThreadSafety::NewThread` cop --- lib/rubocop/cop/thread_safety/new_thread.rb | 8 ++--- .../cop/thread_safety/new_thread_spec.rb | 34 +++++++++++++++++-- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/lib/rubocop/cop/thread_safety/new_thread.rb b/lib/rubocop/cop/thread_safety/new_thread.rb index 01cacef..0bbe470 100644 --- a/lib/rubocop/cop/thread_safety/new_thread.rb +++ b/lib/rubocop/cop/thread_safety/new_thread.rb @@ -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 diff --git a/spec/rubocop/cop/thread_safety/new_thread_spec.rb b/spec/rubocop/cop/thread_safety/new_thread_spec.rb index 56ce6e1..b848cab 100644 --- a/spec/rubocop/cop/thread_safety/new_thread_spec.rb +++ b/spec/rubocop/cop/thread_safety/new_thread_spec.rb @@ -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