|
| 1 | +// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved. |
| 2 | +// See the file LICENSE for licensing terms. |
| 3 | + |
| 4 | +package server |
| 5 | + |
| 6 | +import ( |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/require" |
| 12 | + |
| 13 | + "github.com/ava-labs/avalanchego/snow" |
| 14 | +) |
| 15 | + |
| 16 | +func TestRejectMiddleware(t *testing.T) { |
| 17 | + type test struct { |
| 18 | + name string |
| 19 | + handlerFunc func(*require.Assertions) http.Handler |
| 20 | + state snow.State |
| 21 | + expectedStatusCode int |
| 22 | + } |
| 23 | + |
| 24 | + tests := []test{ |
| 25 | + { |
| 26 | + name: "chain is state syncing", |
| 27 | + handlerFunc: func(require *require.Assertions) http.Handler { |
| 28 | + return http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| 29 | + require.Fail("shouldn't have called handler") |
| 30 | + }) |
| 31 | + }, |
| 32 | + state: snow.StateSyncing, |
| 33 | + expectedStatusCode: http.StatusServiceUnavailable, |
| 34 | + }, |
| 35 | + { |
| 36 | + name: "chain is bootstrapping", |
| 37 | + handlerFunc: func(require *require.Assertions) http.Handler { |
| 38 | + return http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| 39 | + require.Fail("shouldn't have called handler") |
| 40 | + }) |
| 41 | + }, |
| 42 | + state: snow.Bootstrapping, |
| 43 | + expectedStatusCode: http.StatusServiceUnavailable, |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "chain is done bootstrapping", |
| 47 | + handlerFunc: func(*require.Assertions) http.Handler { |
| 48 | + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 49 | + w.WriteHeader(http.StatusTeapot) |
| 50 | + }) |
| 51 | + }, |
| 52 | + state: snow.NormalOp, |
| 53 | + expectedStatusCode: http.StatusTeapot, |
| 54 | + }, |
| 55 | + } |
| 56 | + |
| 57 | + for _, tt := range tests { |
| 58 | + t.Run(tt.name, func(t *testing.T) { |
| 59 | + require := require.New(t) |
| 60 | + |
| 61 | + ctx := &snow.ConsensusContext{} |
| 62 | + ctx.State.Set(snow.EngineState{ |
| 63 | + State: tt.state, |
| 64 | + }) |
| 65 | + |
| 66 | + middleware := rejectMiddleware(tt.handlerFunc(require), ctx) |
| 67 | + w := httptest.NewRecorder() |
| 68 | + middleware.ServeHTTP(w, nil) |
| 69 | + require.Equal(tt.expectedStatusCode, w.Code) |
| 70 | + }) |
| 71 | + } |
| 72 | +} |
0 commit comments