|
| 1 | +package httpclient_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "sync" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/globocom/httpclient" |
| 12 | + "github.com/stretchr/testify/assert" |
| 13 | +) |
| 14 | + |
| 15 | +type mockMetrics struct { |
| 16 | + pushToSeriesCalls []string |
| 17 | + incrCounterCalls []string |
| 18 | + incrCounterWithAttrsCalls []struct { |
| 19 | + key string |
| 20 | + attrs map[string]string |
| 21 | + } |
| 22 | + lock sync.Mutex |
| 23 | +} |
| 24 | + |
| 25 | +func (m *mockMetrics) PushToSeries(key string, value float64) { |
| 26 | + m.lock.Lock() |
| 27 | + defer m.lock.Unlock() |
| 28 | + m.pushToSeriesCalls = append(m.pushToSeriesCalls, key) |
| 29 | +} |
| 30 | + |
| 31 | +func (m *mockMetrics) IncrCounter(key string) { |
| 32 | + m.lock.Lock() |
| 33 | + defer m.lock.Unlock() |
| 34 | + m.incrCounterCalls = append(m.incrCounterCalls, key) |
| 35 | +} |
| 36 | + |
| 37 | +func (m *mockMetrics) IncrCounterWithAttrs(key string, attrs map[string]string) { |
| 38 | + m.lock.Lock() |
| 39 | + defer m.lock.Unlock() |
| 40 | + m.incrCounterWithAttrsCalls = append(m.incrCounterWithAttrsCalls, struct { |
| 41 | + key string |
| 42 | + attrs map[string]string |
| 43 | + }{key, attrs}) |
| 44 | +} |
| 45 | + |
| 46 | +func TestHTTPClient_MetricsIntegration(t *testing.T) { |
| 47 | + metrics := &mockMetrics{} |
| 48 | + server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { |
| 49 | + rw.WriteHeader(http.StatusOK) |
| 50 | + rw.Write([]byte("OK")) |
| 51 | + })) |
| 52 | + defer server.Close() |
| 53 | + |
| 54 | + client := httpclient.NewHTTPClient( |
| 55 | + &httpclient.LoggerAdapter{Writer: io.Discard}, |
| 56 | + httpclient.WithHostURL(server.URL), |
| 57 | + httpclient.WithMetrics(metrics), |
| 58 | + ) |
| 59 | + |
| 60 | + req := client.NewRequest() |
| 61 | + resp, err := req.Get("/") |
| 62 | + assert.NoError(t, err) |
| 63 | + assert.NotNil(t, resp) |
| 64 | + |
| 65 | + assert.Eventually(t, func() bool { |
| 66 | + metrics.lock.Lock() |
| 67 | + defer metrics.lock.Unlock() |
| 68 | + return len(metrics.pushToSeriesCalls) > 0 && len(metrics.incrCounterCalls) > 0 && len(metrics.incrCounterWithAttrsCalls) > 0 |
| 69 | + }, time.Second, 100*time.Millisecond) |
| 70 | +} |
0 commit comments