Commit 16c0338a authored by Michal Witkowski's avatar Michal Witkowski

add tests

parent 8e8aa272
This diff is collapsed.
......@@ -71,7 +71,7 @@ func DialNameToContext(ctx context.Context, dialerName string) context.Context {
// NewDialContextFunc returns a `DialContext` function that tracks outbound connections.
// The signature is compatible with `http.Tranport.DialContext` and is meant to be used there.
func NewDialContextFunc(optFuncs ...dialerOpt) func(context.Context, string, string) (net.Conn, error) {
func NewDialContextFunc(optFuncs ...dialerOpt) (func(context.Context, string, string) (net.Conn, error)) {
opts := &dialerOpts{name: defaultName, monitoring: true, parentDialer: &net.Dialer{}}
for _, f := range optFuncs {
f(opts)
......@@ -90,7 +90,7 @@ func NewDialContextFunc(optFuncs ...dialerOpt) func(context.Context, string, str
// NewDialFunc returns a `Dial` function that tracks outbound connections.
// The signature is compatible with `http.Tranport.Dial` and is meant to be used there for Go < 1.7.
func NewDialFunc(optFuncs ...dialerOpt) func(string, string) (net.Conn, error) {
func NewDialFunc(optFuncs ...dialerOpt) (func(string, string) (net.Conn, error)) {
dialContextFunc := NewDialContextFunc(optFuncs...)
return func(network string, addr string) (net.Conn, error) {
return dialContextFunc(context.TODO(), network, addr)
......
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package conntrack_test
import (
"net"
"net/http"
"testing"
"context"
"time"
"github.com/mwitkow/go-conntrack"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
func TestListenerTestSuite(t *testing.T) {
suite.Run(t, &ListenerTestSuite{})
}
var (
listenerName = "some_name"
)
type ListenerTestSuite struct {
suite.Suite
serverListener net.Listener
httpServer http.Server
}
func (s *ListenerTestSuite) SetupSuite() {
var err error
s.serverListener, err = net.Listen("tcp", "127.0.0.1:0")
require.NoError(s.T(), err, "must be able to allocate a port for serverListener")
s.serverListener = conntrack.NewListener(s.serverListener, conntrack.TrackWithName(listenerName), conntrack.TrackWithTracing())
s.httpServer = http.Server{
Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusOK)
}),
}
go func() {
s.httpServer.Serve(s.serverListener)
}()
}
func (s *ListenerTestSuite) TestTrackingMetricsPreregistered() {
// this will create the default listener, check if it is registered
conntrack.NewListener(s.serverListener)
for testId, testCase := range []struct {
metricName string
existingLabels []string
}{
{"net_conntrack_listener_conn_accepted_total", []string{"default"}},
{"net_conntrack_listener_conn_closed_total", []string{"default"}},
{"net_conntrack_listener_conn_accepted_total", []string{listenerName}},
{"net_conntrack_listener_conn_closed_total", []string{listenerName}},
} {
lineCount := len(fetchPrometheusLines(s.T(), testCase.metricName, testCase.existingLabels...))
assert.NotEqual(s.T(), 0, lineCount, "metrics must exist for test case %d", testId)
}
}
func (s *ListenerTestSuite) TestMonitoringNormalConns() {
beforeAccepted := sumCountersForMetricAndLabels(s.T(), "net_conntrack_listener_conn_accepted_total", listenerName)
beforeClosed := sumCountersForMetricAndLabels(s.T(), "net_conntrack_listener_conn_closed_total", listenerName)
conn, err := (&net.Dialer{}).DialContext(context.TODO(), "tcp", s.serverListener.Addr().String())
require.NoError(s.T(), err, "DialContext should successfully establish a conn here")
assert.Equal(s.T(), beforeAccepted+1, sumCountersForMetricAndLabels(s.T(), "net_conntrack_listener_conn_accepted_total", listenerName),
"the accepted conn counter must be incremented after connection was opened")
assert.Equal(s.T(), beforeClosed, sumCountersForMetricAndLabels(s.T(), "net_conntrack_listener_conn_closed_total", listenerName),
"the closed conn counter must not be incremented before the connection is closed")
conn.Close()
assert.Equal(s.T(), beforeClosed+1, sumCountersForMetricAndLabels(s.T(), "net_conntrack_listener_conn_closed_total", listenerName),
"the closed conn counter must be incremented after connection was closed")
}
func (s *ListenerTestSuite) TestTracingNormalComms() {
conn, err := (&net.Dialer{}).DialContext(context.TODO(), "tcp", s.serverListener.Addr().String())
require.NoError(s.T(), err, "DialContext should successfully establish a conn here")
time.Sleep(5 * time.Millisecond)
assert.Contains(s.T(), fetchTraceEvents(s.T(), "net.ServerConn."+listenerName), conn.LocalAddr().String(),
"the /debug/trace/events page must contain the live connection")
time.Sleep(5 * time.Millisecond)
conn.Close()
}
func (s *ListenerTestSuite) TearDownSuite() {
if s.serverListener != nil {
s.T().Logf("stopped http.Server at: %v", s.serverListener.Addr().String())
s.serverListener.Close()
}
}
package conntrack_test
import (
"bufio"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require"
)
func fetchPrometheusLines(t *testing.T, metricName string, matchingLabelValues ...string) []string {
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/", nil)
require.NoError(t, err, "failed creating request for Prometheus handler")
prometheus.Handler().ServeHTTP(resp, req)
reader := bufio.NewReader(resp.Body)
ret := []string{}
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
break
} else {
require.NoError(t, err, "error reading stuff")
}
if !strings.HasPrefix(line, metricName) {
continue
}
matches := true
for _, labelValue := range matchingLabelValues {
if !strings.Contains(line, `"`+labelValue+`"`) {
matches = false
}
}
if matches {
ret = append(ret, line)
}
}
return ret
}
func sumCountersForMetricAndLabels(t *testing.T, metricName string, matchingLabelValues ...string) int {
count := 0
for _, line := range fetchPrometheusLines(t, metricName, matchingLabelValues...) {
valueString := line[strings.LastIndex(line, " ")+1 : len(line)-1]
valueFloat, err := strconv.ParseFloat(valueString, 32)
require.NoError(t, err, "failed parsing value for line: %v", line)
count += int(valueFloat)
}
return count
}
package conntrack_test
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"golang.org/x/net/trace"
)
func fetchTraceEvents(t *testing.T, familyName string) string {
resp := httptest.NewRecorder()
url := fmt.Sprintf("/debug/events?fam=%s&b=0&exp=1", familyName)
req, err := http.NewRequest("GET", url, nil)
require.NoError(t, err, "failed creating request for Prometheus handler")
trace.RenderEvents(resp, req, true)
out, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err, "failed reading the trace page")
return string(out)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment