|
| 1 | +package ntrack |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | + "go.opencensus.io/stats/view" |
| 12 | +) |
| 13 | + |
| 14 | +func TestListener(t *testing.T) { |
| 15 | + |
| 16 | + var tests = []struct { |
| 17 | + viewName string |
| 18 | + disableKeepalive bool |
| 19 | + expectedValue int64 |
| 20 | + }{ |
| 21 | + { |
| 22 | + viewName: "ntrack/listener/accepts", |
| 23 | + disableKeepalive: true, |
| 24 | + expectedValue: 5, |
| 25 | + }, |
| 26 | + { |
| 27 | + viewName: "ntrack/listener/accepts", |
| 28 | + disableKeepalive: false, |
| 29 | + expectedValue: 1, |
| 30 | + }, |
| 31 | + { |
| 32 | + viewName: "ntrack/listener/closed", |
| 33 | + disableKeepalive: true, |
| 34 | + expectedValue: 5, |
| 35 | + }, |
| 36 | + } |
| 37 | + |
| 38 | + for _, tt := range tests { |
| 39 | + t.Run(tt.viewName, func(t *testing.T) { |
| 40 | + lis, err := net.Listen("tcp", "127.0.0.1:0") |
| 41 | + require.NoError(t, err) |
| 42 | + |
| 43 | + ilis, stats := NewInstrumentedListener(lis) |
| 44 | + view.Register(stats.views...) |
| 45 | + |
| 46 | + testClientConnections(t, ilis, tt.disableKeepalive) |
| 47 | + |
| 48 | + rows, err := view.RetrieveData(tt.viewName) |
| 49 | + require.NoError(t, err) |
| 50 | + data := rows[0].Data.(*view.CountData) |
| 51 | + assert.Equal(t, tt.expectedValue, data.Value) |
| 52 | + view.Unregister(stats.views...) |
| 53 | + }) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +func testClientConnections(t *testing.T, lis net.Listener, disableKeepalive bool) { |
| 58 | + t.Helper() |
| 59 | + |
| 60 | + srv := &http.Server{ |
| 61 | + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 62 | + w.WriteHeader(http.StatusOK) |
| 63 | + }), |
| 64 | + } |
| 65 | + |
| 66 | + go func() { |
| 67 | + if err := srv.Serve(lis); err != nil { |
| 68 | + t.Fatal(err) |
| 69 | + } |
| 70 | + }() |
| 71 | + |
| 72 | + tr := &http.Transport{DisableKeepAlives: disableKeepalive} |
| 73 | + client := &http.Client{Transport: tr} |
| 74 | + |
| 75 | + requestCount := 5 |
| 76 | + for i := 0; i < requestCount; i++ { |
| 77 | + resp, err := client.Get(fmt.Sprintf("http://%s", lis.Addr())) |
| 78 | + require.NoError(t, err) |
| 79 | + resp.Body.Close() |
| 80 | + } |
| 81 | + |
| 82 | +} |
0 commit comments