Skip to content

Commit

Permalink
Close the socket before spawning a new one
Browse files Browse the repository at this point in the history
When using a persistent connection, new sockets will be created for
every single request and they are never closed.

This commit makes it so that the current socket is closed before a new
one is connected.
  • Loading branch information
rzane committed May 24, 2022
1 parent 7a2a406 commit 3d3bdc2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/webmock/http_lib_adapters/net_http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ def start_without_connect


def start_with_connect_without_finish
if @socket
@socket.close
@socket = nil
end
do_start
end

Expand Down
32 changes: 32 additions & 0 deletions spec/acceptance/net_http/net_http_shared.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,38 @@
end
end

it "should allow sending multiple requests when persisted", net_connect: true do
@http = Net::HTTP.new('example.org')
@http.start
expect(@http.get("/")).to be_a(Net::HTTPSuccess)
expect(@http.get("/")).to be_a(Net::HTTPSuccess)
expect(@http.get("/")).to be_a(Net::HTTPSuccess)
@http.finish
end

it "should not leak file descriptors", net_connect: true do
sockets = Set.new

@http = Net::HTTP.new('example.org')
@http.start
sockets << @http.instance_variable_get(:@socket)
@http.get("/")
sockets << @http.instance_variable_get(:@socket)
@http.get("/")
sockets << @http.instance_variable_get(:@socket)
@http.get("/")
sockets << @http.instance_variable_get(:@socket)
@http.finish

if WebMock::Config.instance.net_http_connect_on_start
expect(sockets.length).to eq(1)
else
expect(sockets.length).to eq(4)
end

expect(sockets.all?(&:closed?)).to be(true)
end

it "should pass the read_timeout value on", net_connect: true do
@http = Net::HTTP.new('localhost', port)
read_timeout = @http.read_timeout + 1
Expand Down

0 comments on commit 3d3bdc2

Please sign in to comment.