1
2
3
4 package otelhttp_test
5
6 import (
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "strings"
11 "testing"
12
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15
16 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
17 )
18
19 func TestHandler(t *testing.T) {
20 testCases := []struct {
21 name string
22 handler func(*testing.T) http.Handler
23 requestBody io.Reader
24 expectedStatusCode int
25 }{
26 {
27 name: "implements flusher",
28 handler: func(t *testing.T) http.Handler {
29 return otelhttp.NewHandler(
30 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31 assert.Implements(t, (*http.Flusher)(nil), w)
32 }), "test_handler",
33 )
34 },
35 expectedStatusCode: http.StatusOK,
36 },
37 {
38 name: "succeeds",
39 handler: func(t *testing.T) http.Handler {
40 return otelhttp.NewHandler(
41 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
42 assert.NotNil(t, r.Body)
43
44 b, err := io.ReadAll(r.Body)
45 assert.NoError(t, err)
46 assert.Equal(t, "hello world", string(b))
47 }), "test_handler",
48 )
49 },
50 requestBody: strings.NewReader("hello world"),
51 expectedStatusCode: http.StatusOK,
52 },
53 {
54 name: "succeeds with a nil body",
55 handler: func(t *testing.T) http.Handler {
56 return otelhttp.NewHandler(
57 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
58 assert.Nil(t, r.Body)
59 }), "test_handler",
60 )
61 },
62 expectedStatusCode: http.StatusOK,
63 },
64 {
65 name: "succeeds with an http.NoBody",
66 handler: func(t *testing.T) http.Handler {
67 return otelhttp.NewHandler(
68 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
69 assert.Equal(t, http.NoBody, r.Body)
70 }), "test_handler",
71 )
72 },
73 requestBody: http.NoBody,
74 expectedStatusCode: http.StatusOK,
75 },
76 }
77 for _, tc := range testCases {
78 t.Run(tc.name, func(t *testing.T) {
79 r, err := http.NewRequest(http.MethodGet, "http://localhost/", tc.requestBody)
80 require.NoError(t, err)
81
82 rr := httptest.NewRecorder()
83 tc.handler(t).ServeHTTP(rr, r)
84 assert.Equal(t, tc.expectedStatusCode, rr.Result().StatusCode)
85 })
86 }
87 }
88
View as plain text