eintopf.info@v0.13.16/service/killswitch/transport_test.go (about) 1 // Copyright (C) 2022 The Eintopf authors 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <https://www.gnu.org/licenses/>. 15 16 package killswitch_test 17 18 import ( 19 "context" 20 "fmt" 21 "net/http" 22 "testing" 23 24 "eintopf.info/internal/xhttptest" 25 "eintopf.info/service/killswitch" 26 ) 27 28 func TestRouter(t *testing.T) { 29 tests := []xhttptest.HttpTest{ 30 { 31 Name: "TurnOffInvalidHash", 32 URI: "/turnoff/invalid", 33 WantStatus: http.StatusBadRequest, 34 }, { 35 Name: "TurnOffValidHash", 36 URI: "/turnoff/foo", 37 WantStatus: http.StatusOK, 38 }, { 39 Name: "TurnOnInvalidHash", 40 URI: "/turnon/invalid", 41 WantStatus: http.StatusBadRequest, 42 }, { 43 Name: "TurnOnValidHash", 44 URI: "/turnon/foo", 45 WantStatus: http.StatusOK, 46 }, 47 } 48 49 killswitchService := killswitch.NewService(killswitch.NewMemoryStore(), []string{"foo"}) 50 51 xhttptest.TestRouter(t, killswitch.Router(killswitchService), tests) 52 } 53 54 func testHandler() http.HandlerFunc { 55 fn := func(w http.ResponseWriter, req *http.Request) { 56 w.WriteHeader(http.StatusOK) 57 } 58 return http.HandlerFunc(fn) 59 } 60 61 func TestMiddleware(t *testing.T) { 62 store := killswitch.NewMemoryStore() 63 killswitchService := killswitch.NewService(store, nil) 64 65 onFunc := func(on bool) func() error { 66 return func() error { 67 err := store.SetState(context.Background(), on) 68 if err != nil { 69 return fmt.Errorf("store.SetState(ctx, %t): %s", on, err) 70 } 71 return nil 72 } 73 } 74 75 tests := []xhttptest.HttpTest{ 76 { 77 Name: "On200", 78 PreTest: onFunc(true), 79 URI: "/foo", 80 WantStatus: http.StatusOK, 81 }, { 82 Name: "Off503", 83 PreTest: onFunc(false), 84 URI: "/foo", 85 WantStatus: http.StatusServiceUnavailable, 86 }, { 87 Name: "OffTurnOn200", 88 PreTest: onFunc(false), 89 URI: "/turnon", 90 WantStatus: http.StatusOK, 91 }, 92 } 93 94 xhttptest.TestMiddleware(t, killswitch.Middleware(killswitchService), tests) 95 }