|
| 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 | + var tests = []struct { |
| 16 | + viewName string |
| 17 | + disableKeepalive bool |
| 18 | + expectedValue int64 |
| 19 | + }{ |
| 20 | + { |
| 21 | + viewName: "ntrack/listener/accepts", |
| 22 | + disableKeepalive: true, |
| 23 | + expectedValue: 5, |
| 24 | + }, |
| 25 | + { |
| 26 | + viewName: "ntrack/listener/accepts", |
| 27 | + disableKeepalive: false, |
| 28 | + expectedValue: 1, |
| 29 | + }, |
| 30 | + { |
| 31 | + viewName: "ntrack/listener/closed", |
| 32 | + disableKeepalive: true, |
| 33 | + expectedValue: 5, |
| 34 | + }, |
| 35 | + { |
| 36 | + viewName: "ntrack/listener/open", |
| 37 | + disableKeepalive: true, |
| 38 | + expectedValue: 0, |
| 39 | + }, |
| 40 | + { |
| 41 | + viewName: "ntrack/listener/open", |
| 42 | + disableKeepalive: false, |
| 43 | + expectedValue: 1, |
| 44 | + }, |
| 45 | + } |
| 46 | + |
| 47 | + for _, tt := range tests { |
| 48 | + t.Run(tt.viewName, func(t *testing.T) { |
| 49 | + lis, err := net.Listen("tcp", "127.0.0.1:0") |
| 50 | + require.NoError(t, err) |
| 51 | + |
| 52 | + ilis, stats := NewInstrumentedListener(lis) |
| 53 | + view.Register(stats.views...) |
| 54 | + |
| 55 | + testClientConnections(t, ilis, tt.disableKeepalive) |
| 56 | + |
| 57 | + rows, err := view.RetrieveData(tt.viewName) |
| 58 | + require.NoError(t, err) |
| 59 | + |
| 60 | + switch data := rows[0].Data.(type) { |
| 61 | + case *view.CountData: |
| 62 | + assert.Equal(t, tt.expectedValue, data.Value) |
| 63 | + case *view.LastValueData: |
| 64 | + assert.Equal(t, float64(tt.expectedValue), data.Value) |
| 65 | + } |
| 66 | + view.Unregister(stats.views...) |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +func testClientConnections(t *testing.T, lis net.Listener, disableKeepalive bool) { |
| 72 | + t.Helper() |
| 73 | + |
| 74 | + srv := &http.Server{ |
| 75 | + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 76 | + w.WriteHeader(http.StatusOK) |
| 77 | + }), |
| 78 | + } |
| 79 | + |
| 80 | + go func() { |
| 81 | + if err := srv.Serve(lis); err != nil { |
| 82 | + t.Fatal(err) |
| 83 | + } |
| 84 | + }() |
| 85 | + |
| 86 | + tr := &http.Transport{DisableKeepAlives: disableKeepalive} |
| 87 | + client := &http.Client{Transport: tr} |
| 88 | + |
| 89 | + requestCount := 5 |
| 90 | + for i := 0; i < requestCount; i++ { |
| 91 | + resp, err := client.Get(fmt.Sprintf("http://%s", lis.Addr())) |
| 92 | + require.NoError(t, err) |
| 93 | + resp.Body.Close() |
| 94 | + } |
| 95 | + |
| 96 | +} |
0 commit comments