Skip to content

Commit

Permalink
Listen explicitly on localhost on heartbeat TCP tests (elastic#15583)
Browse files Browse the repository at this point in the history
Some tests were requiring localhost to resolve to 127.0.0.1, but this is
not always the case. In some machines localhost resolve to other local
addresses as 127.0.1.1, or to [::1] if ipv4 is not available.
  • Loading branch information
jsoriano committed Jan 15, 2020
1 parent 26e105f commit 8937ed3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
2 changes: 1 addition & 1 deletion NOTICE.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Elastic Beats
Copyright 2014-2019 Elasticsearch BV
Copyright 2014-2020 Elasticsearch BV

This product includes software developed by The Apache Software
Foundation (http://www.apache.org/).
Expand Down
27 changes: 24 additions & 3 deletions heartbeat/monitors/active/tcp/tcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,43 @@ func setupServer(t *testing.T, serverCreator func(http.Handler) *httptest.Server
return server, port
}

// newLocalhostTestServer starts a server listening on the IP resolved from `localhost`
// httptest.NewServer() binds explicitly on 127.0.0.1 (or [::1] if ipv4 is not available).
// The IP resolved from `localhost` can be a different one, like 127.0.1.1.
func newLocalhostTestServer(handler http.Handler) *httptest.Server {
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
panic("failed to listen on localhost: " + err.Error())
}

server := &httptest.Server{
Listener: listener,
Config: &http.Server{Handler: handler},
}
server.Start()

return server
}

func TestUpEndpointJob(t *testing.T) {
server, port := setupServer(t, httptest.NewServer)
server, port := setupServer(t, newLocalhostTestServer)
defer server.Close()

serverURL, err := url.Parse(server.URL)
require.NoError(t, err)

event := testTCPCheck(t, "localhost", port)

testslike.Test(
t,
lookslike.Strict(lookslike.Compose(
hbtest.BaseChecks("127.0.0.1", "up", "tcp"),
hbtest.BaseChecks(serverURL.Hostname(), "up", "tcp"),
hbtest.SummaryChecks(1, 0),
hbtest.SimpleURLChecks(t, "tcp", "localhost", port),
hbtest.RespondingTCPChecks(),
lookslike.MustCompile(map[string]interface{}{
"resolve": map[string]interface{}{
"ip": "127.0.0.1",
"ip": serverURL.Hostname(),
"rtt.us": isdef.IsDuration,
},
}),
Expand Down

0 comments on commit 8937ed3

Please sign in to comment.