github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/tequilapi/endpoints/stop_test.go (about) 1 /* 2 * Copyright (C) 2017 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package endpoints 19 20 import ( 21 "context" 22 "net/http" 23 "net/http/httptest" 24 "strings" 25 "testing" 26 "time" 27 28 "github.com/gin-gonic/gin" 29 30 "github.com/stretchr/testify/assert" 31 ) 32 33 type fakeStopper struct { 34 stopAllowed chan struct{} 35 stopped chan struct{} 36 } 37 38 func (fs *fakeStopper) AllowStop() { 39 fs.stopAllowed <- struct{}{} 40 } 41 42 func (fs *fakeStopper) Stop() { 43 <-fs.stopAllowed 44 fs.stopped <- struct{}{} 45 } 46 47 func TestAddRouteForStop(t *testing.T) { 48 stopper := fakeStopper{ 49 stopAllowed: make(chan struct{}, 1), 50 stopped: make(chan struct{}, 1), 51 } 52 router := gin.Default() 53 err := AddRouteForStop(stopper.Stop)(router) 54 assert.NoError(t, err) 55 56 resp := httptest.NewRecorder() 57 58 cancelCtx, finishRequestHandling := context.WithCancel(context.Background()) 59 req := httptest.NewRequest("POST", "/stop", strings.NewReader("")).WithContext(cancelCtx) 60 router.ServeHTTP(resp, req) 61 assert.Equal(t, http.StatusAccepted, resp.Code) 62 assert.Equal(t, 0, len(stopper.stopped)) 63 64 stopper.AllowStop() 65 finishRequestHandling() 66 67 select { 68 case <-stopper.stopped: 69 case <-time.After(time.Second): 70 t.Error("Stopper was not executed") 71 } 72 }