MCPcopy Create free account
hub / github.com/TheThingsNetwork/lorawan-stack / TestHTTP

Function TestHTTP

pkg/ratelimit/http_test.go:33–138  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

31}
32
33func TestHTTP(t *testing.T) {
34 a := assertions.New(t)
35
36 limiter := &mockLimiter{}
37
38 const class = "http:test"
39 middleware := ratelimit.HTTPMiddleware(limiter, class)
40 handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
41
42 t.Run("Pass", func(t *testing.T) {
43 limiter.limit = false
44 limiter.result = ratelimit.Result{Limit: 10}
45
46 rec := httptest.NewRecorder()
47 handler.ServeHTTP(rec, httpRequest("/path", "10.10.10.10"))
48
49 a.So(rec.Header().Get("x-rate-limit-limit"), should.Equal, "10")
50 a.So(rec.Result().StatusCode, should.Equal, http.StatusOK)
51
52 a.So(limiter.calledWithResource.Key(), should.ContainSubstring, "/path")
53 a.So(limiter.calledWithResource.Key(), should.ContainSubstring, "10.10.10.10")
54 a.So(limiter.calledWithResource.Classes(), should.Resemble, []string{class, "http"})
55 })
56
57 t.Run("PathTemplate", func(t *testing.T) {
58 limiter.limit = false
59 limiter.result = ratelimit.Result{Limit: 10}
60
61 restore := ratelimit.SetPathTemplate(func(r *http.Request) (string, bool) {
62 return "/path/{id}", true
63 })
64 defer restore()
65
66 rec := httptest.NewRecorder()
67 handler.ServeHTTP(rec, httpRequest("/path/123", "10.10.10.10"))
68
69 a.So(rec.Header().Get("x-rate-limit-limit"), should.Equal, "10")
70 a.So(rec.Result().StatusCode, should.Equal, http.StatusOK)
71
72 a.So(limiter.calledWithResource.Key(), should.ContainSubstring, "/path/123")
73 a.So(limiter.calledWithResource.Key(), should.ContainSubstring, "10.10.10.10")
74 a.So(limiter.calledWithResource.Classes(), should.Resemble, []string{"http:test:/path/{id}", class, "http"})
75 })
76
77 t.Run("AuthToken", func(t *testing.T) {
78 limiter.limit = false
79 limiter.result = ratelimit.Result{Limit: 10}
80
81 rec := httptest.NewRecorder()
82 req := httpRequest("/path", "10.10.10.10").WithContext(tokenContext(authTokenID))
83 handler.ServeHTTP(rec, req)
84
85 a.So(rec.Header().Get("x-rate-limit-limit"), should.Equal, "10")
86 a.So(rec.Result().StatusCode, should.Equal, http.StatusOK)
87
88 a.So(limiter.calledWithResource.Key(), should.ContainSubstring, "/path")
89 a.So(limiter.calledWithResource.Key(), should.ContainSubstring, authTokenID)
90 a.So(limiter.calledWithResource.Classes(), should.Resemble, []string{class, "http"})

Callers

nothing calls this directly

Calls 12

HTTPMiddlewareFunction · 0.92
SetPathTemplateFunction · 0.92
httpRequestFunction · 0.85
tokenContextFunction · 0.85
HeaderMethod · 0.80
NewMethod · 0.65
RunMethod · 0.65
GetMethod · 0.65
ResultMethod · 0.65
KeyMethod · 0.65
ClassesMethod · 0.65
ServeHTTPMethod · 0.45

Tested by

no test coverage detected