de66e5d0e4be3b2fff94335f2886a30862067cd9
[nonrtric/rapp/ransliceassurance.git] / smoversion / internal / restclient / client_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //        http://www.apache.org/licenses/LICENSE-2.0
11 //
12 //   Unless required by applicable law or agreed to in writing, software
13 //   distributed under the License is distributed on an "AS IS" BASIS,
14 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 //   See the License for the specific language governing permissions and
16 //   limitations under the License.
17 //   ========================LICENSE_END===================================
18 //
19
20 package restclient
21
22 import (
23         "bytes"
24         "encoding/json"
25         "fmt"
26         "net/http"
27         "net/http/httptest"
28         "testing"
29
30         "github.com/stretchr/testify/assert"
31         "github.com/stretchr/testify/require"
32 )
33
34 func TestNewRequest(t *testing.T) {
35         assertions := require.New(t)
36
37         bodyBytes, _ := json.Marshal("body")
38         succesfullReq, _ := http.NewRequest(http.MethodGet, "url", bytes.NewReader(bodyBytes))
39
40         type args struct {
41                 method  string
42                 path    string
43                 payload interface{}
44         }
45         tests := []struct {
46                 name    string
47                 args    args
48                 want    *http.Request
49                 wantErr error
50         }{
51                 {
52                         name: "succesfull newRequest",
53                         args: args{
54                                 method:  http.MethodGet,
55                                 path:    "url",
56                                 payload: "body",
57                         },
58                         want:    succesfullReq,
59                         wantErr: nil,
60                 },
61                 {
62                         name: "request failed json marshal",
63                         args: args{
64                                 method: http.MethodGet,
65                                 path:   "url",
66                                 payload: map[string]interface{}{
67                                         "foo": make(chan int),
68                                 },
69                         },
70                         want:    nil,
71                         wantErr: fmt.Errorf("failed to marshal request body: json: unsupported type: chan int"),
72                 },
73                 {
74                         name: "request failed calling newRequest",
75                         args: args{
76                                 method:  "*?",
77                                 path:    "url",
78                                 payload: "body",
79                         },
80                         want:    nil,
81                         wantErr: fmt.Errorf("failed to create HTTP request: net/http: invalid method \"*?\""),
82                 },
83         }
84
85         for _, tt := range tests {
86                 t.Run(tt.name, func(t *testing.T) {
87                         client := New(&http.Client{}, false)
88
89                         req, err := client.newRequest(tt.args.method, tt.args.path, tt.args.payload)
90                         if tt.wantErr != nil {
91                                 assertions.Equal(tt.want, req)
92                                 assertions.EqualError(tt.wantErr, err.Error())
93                         } else {
94                                 assertions.Equal("url", req.URL.Path)
95                                 assertions.Equal("application/json", req.Header.Get("Content-Type"))
96                                 assertions.Empty(req.Header.Get("Authorization"))
97                                 assertions.Nil(err)
98                         }
99
100                 })
101         }
102 }
103
104 func TestGet(t *testing.T) {
105         assertions := require.New(t)
106         type args struct {
107                 header   string
108                 respCode int
109                 resp     interface{}
110         }
111         tests := []struct {
112                 name    string
113                 args    args
114                 wantErr string
115         }{
116                 {
117                         name: "successful GET request",
118                         args: args{
119                                 header:   "application/json",
120                                 respCode: http.StatusOK,
121                                 resp:     "Success!",
122                         },
123                         wantErr: "",
124                 },
125                 {
126                         name: "error GET request",
127                         args: args{
128                                 header:   "application/json",
129                                 respCode: http.StatusBadRequest,
130                                 resp:     nil,
131                         },
132                         wantErr: "error response with status: 400 and body:",
133                 },
134         }
135
136         for _, tt := range tests {
137
138                 t.Run(tt.name, func(t *testing.T) {
139                         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
140                                 assertions.Equal(http.MethodGet, r.Method)
141                                 response, _ := json.Marshal(tt.args.resp)
142                                 w.Header().Set("Content-Type", tt.args.header)
143                                 w.WriteHeader(tt.args.respCode)
144                                 w.Write(response)
145                         }))
146                         defer srv.Close()
147
148                         client := New(&http.Client{}, false)
149                         var res interface{}
150                         err := client.Get(srv.URL, &res)
151
152                         if err != nil {
153                                 assertions.Contains(err.Error(), tt.wantErr)
154                         }
155                         assertions.Equal(tt.args.resp, res)
156                 })
157         }
158 }
159
160 func TestPost(t *testing.T) {
161         header := "application/json"
162         respCode := http.StatusOK
163         resp := "Success!"
164
165         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
166
167                 assert.Equal(t, http.MethodPost, r.Method)
168                 assert.Contains(t, r.Header.Get("Content-Type"), "application/json")
169
170                 var reqBody string
171                 decoder := json.NewDecoder(r.Body)
172                 decoder.Decode(&reqBody)
173                 assert.Equal(t, reqBody, `json:"example"`)
174
175                 response, _ := json.Marshal(resp)
176                 w.Header().Set("Content-Type", header)
177                 w.WriteHeader(respCode)
178                 w.Write(response)
179         }))
180         defer srv.Close()
181
182         client := New(&http.Client{}, false)
183         payload := `json:"example"`
184         err := client.Post(srv.URL, payload, nil, "admin", "pass")
185
186         if err != nil {
187                 assert.Equal(t, "", err.Error())
188         }
189 }
190
191 func TestPut(t *testing.T) {
192         header := "application/json"
193         respCode := http.StatusOK
194         resp := "Success!"
195
196         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
197
198                 assert.Equal(t, http.MethodPut, r.Method)
199                 assert.Contains(t, r.Header.Get("Content-Type"), "application/json")
200
201                 var reqBody string
202                 decoder := json.NewDecoder(r.Body)
203                 decoder.Decode(&reqBody)
204                 assert.Equal(t, reqBody, `json:"example"`)
205
206                 response, _ := json.Marshal(resp)
207                 w.Header().Set("Content-Type", header)
208                 w.WriteHeader(respCode)
209                 w.Write(response)
210         }))
211         defer srv.Close()
212
213         client := New(&http.Client{}, false)
214         payload := `json:"example"`
215         err := client.Put(srv.URL, payload, nil, "admin", "pass")
216
217         if err != nil {
218                 assert.Equal(t, "", err.Error())
219         }
220 }