Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Commit d181a28

Browse files
committed
Use Mutex from core, prevent it from being stubbed
1 parent fdd801c commit d181a28

File tree

4 files changed

+16
-103
lines changed

4 files changed

+16
-103
lines changed

lib/rspec/support/mutex.rb

Lines changed: 0 additions & 73 deletions
This file was deleted.

lib/rspec/support/reentrant_mutex.rb

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
module RSpec
22
module Support
3+
# This class protects us against Mutex.new stubbed out within tests.
4+
# @private
5+
class Mutex < ::Mutex
6+
class << self
7+
define_method(:new, &::Mutex.method(:new))
8+
end
9+
end
10+
311
# Allows a thread to lock out other threads from a critical section of code,
412
# while allowing the thread with the lock to reenter that section.
513
#
614
# Based on Monitor as of 2.2 -
715
# https://github.com/ruby/ruby/blob/eb7ddaa3a47bf48045d26c72eb0f263a53524ebc/lib/monitor.rb#L9
816
#
9-
# Depends on Mutex, but Mutex is only available as part of core since 1.9.1:
10-
# exists - http://ruby-doc.org/core-1.9.1/Mutex.html
11-
# dne - http://ruby-doc.org/core-1.9.0/Mutex.html
12-
#
1317
# @private
1418
class ReentrantMutex
1519
def initialize
@@ -40,22 +44,5 @@ def exit
4044
@mutex.unlock
4145
end
4246
end
43-
44-
if defined? ::Mutex
45-
# On 1.9 and up, this is in core, so we just use the real one
46-
class Mutex < ::Mutex
47-
# If you mock Mutex.new you break our usage of Mutex, so
48-
# instead we capture the original method to return Mutexs.
49-
NEW_MUTEX_METHOD = Mutex.method(:new)
50-
51-
def self.new
52-
NEW_MUTEX_METHOD.call
53-
end
54-
end
55-
else # For 1.8.7
56-
# :nocov:
57-
RSpec::Support.require_rspec_support "mutex"
58-
# :nocov:
59-
end
6047
end
6148
end

spec/rspec/support/mutex_spec.rb

Lines changed: 0 additions & 8 deletions
This file was deleted.

spec/rspec/support/reentrant_mutex_spec.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
require 'rspec/support/reentrant_mutex'
22
require 'thread_order'
33

4+
RSpec.describe RSpec::Support::Mutex do
5+
it "allows ::Mutex to be mocked" do
6+
expect(Mutex).to receive(:new)
7+
::Mutex.new
8+
end
9+
end
10+
411
# There are no assertions specifically
5-
# They are pass if they don't deadlock
12+
# They pass if they don't deadlock
613
RSpec.describe RSpec::Support::ReentrantMutex do
714
let!(:mutex) { described_class.new }
815
let!(:order) { ThreadOrder.new }

0 commit comments

Comments
 (0)