diff --git a/lib/sparoid.rb b/lib/sparoid.rb index de233a0..d1b6bb5 100644 --- a/lib/sparoid.rb +++ b/lib/sparoid.rb @@ -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 diff --git a/test/sparoid_test.rb b/test/sparoid_test.rb index 72f282b..5d64484 100644 --- a/test/sparoid_test.rb +++ b/test/sparoid_test.rb @@ -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