github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/tequilapi/endpoints/access_policies_test.go (about) 1 /* 2 * Copyright (C) 2019 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 "net/http" 22 "net/http/httptest" 23 "testing" 24 25 "github.com/gin-gonic/gin" 26 27 "github.com/mysteriumnetwork/node/requests" 28 "github.com/stretchr/testify/assert" 29 ) 30 31 const bindAllAddress = "0.0.0.0" 32 33 func Test_Get_AccessPolicies_ReturnsAccessPolicies(t *testing.T) { 34 mockResponse := ` 35 { 36 "entries": [ 37 { 38 "id": "mysterium", 39 "title": "Mysterium verified traffic", 40 "description": "Mysterium Network approved identities", 41 "allow": [ 42 { 43 "type": "identity", 44 "value": "0xf4d6ffba09d460ebe10d24667770437981ce3de9" 45 } 46 ] 47 } 48 ] 49 }` 50 server := newTestServer(http.StatusOK, mockResponse) 51 52 r := gin.Default() 53 err := AddRoutesForAccessPolicies(requests.NewHTTPClient(bindAllAddress, requests.DefaultTimeout), server.URL)(r) 54 assert.Nil(t, err) 55 56 req, err := http.NewRequest( 57 http.MethodGet, 58 "/access-policies", 59 nil, 60 ) 61 assert.Nil(t, err) 62 63 resp := httptest.NewRecorder() 64 r.ServeHTTP(resp, req) 65 66 assert.Equal(t, http.StatusOK, resp.Code) 67 assert.JSONEq(t, mockResponse, resp.Body.String()) 68 } 69 70 func Test_Get_AccessPolicies_WhenRequestFails_ReturnsError(t *testing.T) { 71 server := newTestServer(http.StatusInternalServerError, `{"error": "something bad"}`) 72 73 router := summonTestGin() 74 err := AddRoutesForAccessPolicies(requests.NewHTTPClient(bindAllAddress, requests.DefaultTimeout), server.URL)(router) 75 assert.Nil(t, err) 76 77 req, err := http.NewRequest( 78 http.MethodGet, 79 "/access-policies", 80 nil, 81 ) 82 assert.Nil(t, err) 83 84 resp := httptest.NewRecorder() 85 router.ServeHTTP(resp, req) 86 87 assert.Equal(t, http.StatusInternalServerError, resp.Code) 88 } 89 90 func newTestServer(mockStatus int, mockResponse string) *httptest.Server { 91 return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 92 w.WriteHeader(mockStatus) 93 w.Write([]byte(mockResponse)) 94 })) 95 }