Skip to content

Commit

Permalink
some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
groob committed Jan 9, 2019
1 parent 842015c commit e4d225b
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions ntrack/listener_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package ntrack

import (
"fmt"
"net"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opencensus.io/stats/view"
)

func TestListener(t *testing.T) {

var tests = []struct {
viewName string
disableKeepalive bool
expectedValue int64
}{
{
viewName: "ntrack/listener/accepts",
disableKeepalive: true,
expectedValue: 5,
},
{
viewName: "ntrack/listener/accepts",
disableKeepalive: false,
expectedValue: 1,
},
{
viewName: "ntrack/listener/closed",
disableKeepalive: true,
expectedValue: 5,
},
}

for _, tt := range tests {
t.Run(tt.viewName, func(t *testing.T) {
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)

ilis, stats := NewInstrumentedListener(lis)
view.Register(stats.views...)

testClientConnections(t, ilis, tt.disableKeepalive)

rows, err := view.RetrieveData(tt.viewName)
require.NoError(t, err)
data := rows[0].Data.(*view.CountData)
assert.Equal(t, tt.expectedValue, data.Value)
view.Unregister(stats.views...)
})
}
}

func testClientConnections(t *testing.T, lis net.Listener, disableKeepalive bool) {
t.Helper()

srv := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}),
}

go func() {
if err := srv.Serve(lis); err != nil {
t.Fatal(err)
}
}()

tr := &http.Transport{DisableKeepAlives: disableKeepalive}
client := &http.Client{Transport: tr}

requestCount := 5
for i := 0; i < requestCount; i++ {
resp, err := client.Get(fmt.Sprintf("http://%s", lis.Addr()))
require.NoError(t, err)
resp.Body.Close()
}

}

0 comments on commit e4d225b

Please sign in to comment.