Skip to content

Commit

Permalink
make #public_ip always return an instance of Resolv::IPv4, as was don…
Browse files Browse the repository at this point in the history
…e prior
  • Loading branch information
oskgu360 committed Jul 23, 2024
1 parent 60a8e0a commit 2b07eb3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
6 changes: 4 additions & 2 deletions lib/sparoid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,12 @@ def public_ip(host = "checkip.amazonaws.com")
sock.print "GET / HTTP/1.1\r\nHost: #{host}\r\nConnection: close\r\n\r\n"
status = sock.readline(chomp: true)
raise ResolvError.new("#{host} response: #{status}") unless status.start_with? "HTTP/1.1 200 "
until sock.readline(chomp: true).empty?

until sock.readline(chomp: true).empty?
# skip all headers
end
sock.readline(chomp: true) # this is the IP
ip = sock.readline(chomp: true) # this is the IP
Resolv::IPv4.create ip
end
end

Expand Down
17 changes: 12 additions & 5 deletions test/sparoid_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,25 +62,32 @@ def test_it_sends_message_with_empty_cache_file
end

def test_it_resolves_public_ip_only_once_per_instance
dns = Minitest::Mock.new
dns.expect :getresource, Resolv::IPv4.create("1.1.1.1"), ["myip.opendns.com", Resolv::DNS::Resource::IN::A]
Resolv::DNS.stub(:open, ->(_, &blk) { blk.call dns }) do
sock = Minitest::Mock.new
sock = Minitest::Mock.new
sock.expect :sync=, nil, [true]
sock.expect :print, nil, ["GET / HTTP/1.1\r\nHost: checkip.amazonaws.com\r\nConnection: close\r\n\r\n"]
sock.expect :readline, "HTTP/1.1 200 ", [], chomp: true
sock.expect :readline, "", [], chomp: true
sock.expect :readline, "1.1.1.1", [], chomp: true
Socket.stub(:tcp, ->(_host, _port, **_opts, &blk) { blk.call(sock) }) do
s = Sparoid::Instance.new
2.times do
s.send(:public_ip)
end
end
dns.verify

sock.verify
end

def test_it_raises_resolve_error_on_dns_socket_error
key = "0000000000000000000000000000000000000000000000000000000000000000"
hmac_key = "0000000000000000000000000000000000000000000000000000000000000000"
open_for_ip = Resolv::IPv4.create("1.1.1.1")
error = ->(*_) { raise SocketError, "getaddrinfo: Name or service not known" }

Addrinfo.stub(:getaddrinfo, error) do
assert_raises(Sparoid::ResolvError) do
Sparoid::Instance.new.auth(key, hmac_key, "127.0.0.1", 1337)
Sparoid::Instance.new.auth(key, hmac_key, "127.0.0.1", 1337, open_for_ip: )
end
end
end
Expand Down

0 comments on commit 2b07eb3

Please sign in to comment.