Skip to content

Commit

Permalink
Change stub socket for Ruby 2.4 compat
Browse files Browse the repository at this point in the history
Background:

1.  As of Ruby 2.2, calling #close on a socket that's already closed
    no longer raises an exception.

2.  As of Ruby 2.4, Net::HTTP no longer checks #closed? every time
    before calling #close on a socket, since there's no longer any
    danger it will raise. See:

    * r56795 (ruby/ruby@6394b63db9abe34234e7)
    * r56865 (ruby/ruby@f845a9ef76c0195254de)

FakeWeb's internal StubSocket has been short-circuiting those pre-2.4
checks by just always returning true when #closed? is checked,
preventing #close from ever being called.

Now that the checks are gone, StubSocket needs its own #close
method. This fixes a variety of NoMethodErrors on Ruby 2.4, but is
basically backwards-compatible with earlier implementations.

(When running on pre-Ruby 2.2, I suppose StubSocket should raise when
you call #close on an already-closed socket. I'll look into that, but
all our functional tests are passing on earlier Rubies at the moment.)

While we're at it, I changed #closed? to stop just always returning
true, to be closer to how the Ruby stdlib's sockets behave. This
doesn't appear to break anything but I'll revert that part if I find
anything in the relevant Net::HTTP code that conflicts.

Thanks for reporting and submitting patches: @voxik in #59,
@SamMolokanov in #60.

Closes #59.
References #57.
  • Loading branch information
chrisk committed Jun 26, 2017
1 parent 7555507 commit 9cd9aae
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/fake_web/stub_socket.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ def initialize(*args)
end

def closed?
@closed ||= true
@closed ||= false
@closed
end

def close
@closed = true
end

def readuntil(*args)
Expand Down
18 changes: 18 additions & 0 deletions test/test_stub_socket_compatibility.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,22 @@ def test_stub_socket_only_responds_to_continue_timeout_under_193_or_later
socket = http.instance_variable_get(:@socket)
assert_equal RUBY_VERSION >= "1.9.3", socket.respond_to?(:continue_timeout=)
end

def test_stub_socket_responds_to_close_and_always_returns_true
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 80)
http.get("/")
socket = http.instance_variable_get(:@socket)
assert_equal socket.close, true
end

def test_stub_socket_tracks_closed_state
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 80)
http.get("/")
socket = http.instance_variable_get(:@socket)
assert !socket.closed?
socket.close
assert socket.closed?
end
end

0 comments on commit 9cd9aae

Please sign in to comment.