http: use a method to get local address

And limit its export to testing.
This commit is contained in:
Vincent Bernat
2022-08-21 00:43:47 +02:00
parent 18ee3eac6f
commit 3e3bcbdada
17 changed files with 32 additions and 28 deletions

View File

@@ -36,9 +36,7 @@ type Component struct {
durations *reporter.HistogramVec durations *reporter.HistogramVec
sizes *reporter.HistogramVec sizes *reporter.HistogramVec
} }
address net.Addr
// Local address used by the HTTP server. Only valid after Start().
Address net.Addr
// GinRouter is the router exposed for /api // GinRouter is the router exposed for /api
GinRouter *gin.Engine GinRouter *gin.Engine
@@ -142,7 +140,7 @@ func (c *Component) Start() error {
if err != nil { if err != nil {
return fmt.Errorf("unable to listen to %v: %w", c.config.Listen, err) return fmt.Errorf("unable to listen to %v: %w", c.config.Listen, err)
} }
c.Address = listener.Addr() c.address = listener.Addr()
// Start serving requests // Start serving requests
c.t.Go(func() error { c.t.Go(func() error {

View File

@@ -25,7 +25,7 @@ func TestHandler(t *testing.T) {
})) }))
// Check the HTTP server is running and answering metrics // Check the HTTP server is running and answering metrics
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/test", URL: "/test",
ContentType: "text/plain; charset=utf-8", ContentType: "text/plain; charset=utf-8",
@@ -61,7 +61,7 @@ func TestGinRouter(t *testing.T) {
}) })
}) })
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/test", URL: "/api/v0/test",
ContentType: "application/json; charset=utf-8", ContentType: "application/json; charset=utf-8",
@@ -81,7 +81,7 @@ func TestGinRouterPanic(t *testing.T) {
panic("heeeelp") panic("heeeelp")
}) })
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/test", URL: "/api/v0/test",
StatusCode: 500, StatusCode: 500,

View File

@@ -6,6 +6,7 @@
package http package http
import ( import (
"net"
"testing" "testing"
"akvorado/common/daemon" "akvorado/common/daemon"
@@ -26,3 +27,8 @@ func NewMock(t *testing.T, r *reporter.Reporter) *Component {
helpers.StartStop(t, c) helpers.StartStop(t, c)
return c return c
} }
// LocalAddr returns the address the HTTP server is listening to.
func (c *Component) LocalAddr() net.Addr {
return c.address
}

View File

@@ -23,7 +23,7 @@ func TestServeAssets(t *testing.T) {
conf.ServeLiveFS = live conf.ServeLiveFS = live
_, h, _, _ := NewMock(t, conf) _, h, _, _ := NewMock(t, conf)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/", URL: "/",
ContentType: "text/html; charset=utf-8", ContentType: "text/html; charset=utf-8",

View File

@@ -28,7 +28,7 @@ func TestUserHandler(t *testing.T) {
endpoint.GET("/avatar", c.UserAvatarHandlerFunc) endpoint.GET("/avatar", c.UserAvatarHandlerFunc)
t.Run("default user configured", func(t *testing.T) { t.Run("default user configured", func(t *testing.T) {
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
Description: "user info, no user logged in", Description: "user info, no user logged in",
URL: "/api/v0/console/user/info", URL: "/api/v0/console/user/info",
@@ -106,7 +106,7 @@ func TestUserHandler(t *testing.T) {
t.Run("no default user", func(t *testing.T) { t.Run("no default user", func(t *testing.T) {
c.config.DefaultUser.Login = "" c.config.DefaultUser.Login = ""
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
Description: "user info, no user logged in", Description: "user info, no user logged in",
URL: "/api/v0/console/user/info", URL: "/api/v0/console/user/info",

View File

@@ -15,7 +15,7 @@ func TestConfigHandler(t *testing.T) {
config := DefaultConfiguration() config := DefaultConfiguration()
config.Version = "1.2.3" config.Version = "1.2.3"
_, h, _, _ := NewMock(t, config) _, h, _, _ := NewMock(t, config)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/configuration", URL: "/api/v0/console/configuration",
JSONOutput: gin.H{ JSONOutput: gin.H{

View File

@@ -31,7 +31,7 @@ func TestServeDocs(t *testing.T) {
_, h, _, _ := NewMock(t, conf) _, h, _, _ := NewMock(t, conf)
resp, err := netHTTP.Get(fmt.Sprintf("http://%s/api/v0/console/docs/%s", resp, err := netHTTP.Get(fmt.Sprintf("http://%s/api/v0/console/docs/%s",
h.Address, tc.Path)) h.LocalAddr(), tc.Path))
if err != nil { if err != nil {
t.Fatalf("GET /api/v0/console/docs/%s:\n%+v", tc.Path, err) t.Fatalf("GET /api/v0/console/docs/%s:\n%+v", tc.Path, err)
} }

View File

@@ -91,7 +91,7 @@ UNION DISTINCT
}). }).
Return(nil) Return(nil)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/filter/validate", URL: "/api/v0/console/filter/validate",
JSONInput: gin.H{"filter": `InIfName = "Gi0/0/0/1"`}, JSONInput: gin.H{"filter": `InIfName = "Gi0/0/0/1"`},

View File

@@ -559,7 +559,7 @@ func TestGraphHandler(t *testing.T) {
SetArg(1, expectedSQL). SetArg(1, expectedSQL).
Return(nil) Return(nil)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
Description: "single direction", Description: "single direction",
URL: "/api/v0/console/graph", URL: "/api/v0/console/graph",

View File

@@ -169,7 +169,7 @@ func TestSankeyHandler(t *testing.T) {
SetArg(1, expectedSQL). SetArg(1, expectedSQL).
Return(nil) Return(nil)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/sankey", URL: "/api/v0/console/sankey",
JSONInput: gin.H{ JSONInput: gin.H{

View File

@@ -77,7 +77,7 @@ func TestWidgetLastFlow(t *testing.T) {
return nil return nil
}) })
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/widget/flow-last", URL: "/api/v0/console/widget/flow-last",
JSONOutput: gin.H{ JSONOutput: gin.H{
@@ -105,7 +105,7 @@ func TestFlowRate(t *testing.T) {
`SELECT COUNT(*)/300 AS rate FROM flows WHERE TimeReceived > date_sub(minute, 5, now())`). `SELECT COUNT(*)/300 AS rate FROM flows WHERE TimeReceived > date_sub(minute, 5, now())`).
Return(mockRow) Return(mockRow)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/widget/flow-rate", URL: "/api/v0/console/widget/flow-rate",
JSONOutput: gin.H{ JSONOutput: gin.H{
@@ -132,7 +132,7 @@ func TestWidgetExporters(t *testing.T) {
SetArg(1, expected). SetArg(1, expected).
Return(nil) Return(nil)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/widget/exporters", URL: "/api/v0/console/widget/exporters",
JSONOutput: gin.H{ JSONOutput: gin.H{
@@ -180,7 +180,7 @@ func TestWidgetTop(t *testing.T) {
}), }),
) )
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/widget/top/src-port", URL: "/api/v0/console/widget/top/src-port",
JSONOutput: gin.H{ JSONOutput: gin.H{
@@ -245,7 +245,7 @@ ORDER BY Time WITH FILL
SetArg(1, expected). SetArg(1, expected).
Return(nil) Return(nil)
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/console/widget/graph?points=100", URL: "/api/v0/console/widget/graph?points=100",
JSONOutput: gin.H{ JSONOutput: gin.H{

View File

@@ -204,7 +204,7 @@ func TestCore(t *testing.T) {
t.Run("http flows", func(t *testing.T) { t.Run("http flows", func(t *testing.T) {
c.httpFlowFlushDelay = 20 * time.Millisecond c.httpFlowFlushDelay = 20 * time.Millisecond
resp, err := netHTTP.Get(fmt.Sprintf("http://%s/api/v0/inlet/flows", c.d.HTTP.Address)) resp, err := netHTTP.Get(fmt.Sprintf("http://%s/api/v0/inlet/flows", c.d.HTTP.LocalAddr()))
if err != nil { if err != nil {
t.Fatalf("GET /api/v0/inlet/flows:\n%+v", err) t.Fatalf("GET /api/v0/inlet/flows:\n%+v", err)
} }
@@ -277,7 +277,7 @@ func TestCore(t *testing.T) {
// Test HTTP flow clients with a limit // Test HTTP flow clients with a limit
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
t.Run("http flows with limit", func(t *testing.T) { t.Run("http flows with limit", func(t *testing.T) {
resp, err := netHTTP.Get(fmt.Sprintf("http://%s/api/v0/inlet/flows?limit=4", c.d.HTTP.Address)) resp, err := netHTTP.Get(fmt.Sprintf("http://%s/api/v0/inlet/flows?limit=4", c.d.HTTP.LocalAddr()))
if err != nil { if err != nil {
t.Fatalf("GET /api/v0/inlet/flows:\n%+v", err) t.Fatalf("GET /api/v0/inlet/flows:\n%+v", err)
} }

View File

@@ -37,5 +37,5 @@ func TestHTTPEndpoints(t *testing.T) {
}, },
} }
helpers.TestHTTPEndpoints(t, c.d.HTTP.Address, cases) helpers.TestHTTPEndpoints(t, c.d.HTTP.LocalAddr(), cases)
} }

View File

@@ -62,7 +62,7 @@ func TestHTTPEndpoints(t *testing.T) {
}, },
} }
helpers.TestHTTPEndpoints(t, c.d.HTTP.Address, cases) helpers.TestHTTPEndpoints(t, c.d.HTTP.LocalAddr(), cases)
} }
func TestAdditionalASNs(t *testing.T) { func TestAdditionalASNs(t *testing.T) {
@@ -91,5 +91,5 @@ func TestAdditionalASNs(t *testing.T) {
}, },
} }
helpers.TestHTTPEndpoints(t, c.d.HTTP.Address, cases) helpers.TestHTTPEndpoints(t, c.d.HTTP.LocalAddr(), cases)
} }

View File

@@ -168,7 +168,7 @@ func (c *Component) getHTTPBaseURL(address string) (string, error) {
localAddr := conn.LocalAddr().(*net.UDPAddr) localAddr := conn.LocalAddr().(*net.UDPAddr)
// Combine with HTTP port // Combine with HTTP port
_, port, err := net.SplitHostPort(c.d.HTTP.Address.String()) _, port, err := net.SplitHostPort(c.d.HTTP.LocalAddr().String())
if err != nil { if err != nil {
return "", fmt.Errorf("cannot get HTTP port: %w", err) return "", fmt.Errorf("cannot get HTTP port: %w", err)
} }

View File

@@ -138,7 +138,7 @@ func TestGetHTTPBaseURL(t *testing.T) {
} }
expectedURL := &url.URL{ expectedURL := &url.URL{
Scheme: "http", Scheme: "http",
Host: http.Address.String(), Host: http.LocalAddr().String(),
} }
parsedURL.Host = parsedURL.Host[strings.LastIndex(parsedURL.Host, ":"):] parsedURL.Host = parsedURL.Host[strings.LastIndex(parsedURL.Host, ":"):]
expectedURL.Host = expectedURL.Host[strings.LastIndex(expectedURL.Host, ":"):] expectedURL.Host = expectedURL.Host[strings.LastIndex(expectedURL.Host, ":"):]

View File

@@ -29,7 +29,7 @@ func TestConfigurationEndpoint(t *testing.T) {
"bye": "Goodbye pal!", "bye": "Goodbye pal!",
}) })
helpers.TestHTTPEndpoints(t, h.Address, helpers.HTTPEndpointCases{ helpers.TestHTTPEndpoints(t, h.LocalAddr(), helpers.HTTPEndpointCases{
{ {
URL: "/api/v0/orchestrator/configuration/inlet", URL: "/api/v0/orchestrator/configuration/inlet",
ContentType: "application/x-yaml; charset=utf-8", ContentType: "application/x-yaml; charset=utf-8",