Update documentation and Raise test coverage
[nonrtric/rapp/ransliceassurance.git] / icsversion / internal / restclient / client_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: 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                 userInfo [2]string
45         }
46         tests := []struct {
47                 name    string
48                 args    args
49                 want    *http.Request
50                 wantErr error
51         }{
52                 {
53                         name: "succesfull newRequest",
54                         args: args{
55                                 method:   http.MethodGet,
56                                 path:     "url",
57                                 payload:  "body",
58                                 userInfo: [2]string{"user", "pass"},
59                         },
60                         want:    succesfullReq,
61                         wantErr: nil,
62                 },
63                 {
64                         name: "request failed json marshal",
65                         args: args{
66                                 method: http.MethodGet,
67                                 path:   "url",
68                                 payload: map[string]interface{}{
69                                         "foo": make(chan int),
70                                 },
71                         },
72                         want:    nil,
73                         wantErr: fmt.Errorf("failed to marshal request body: json: unsupported type: chan int"),
74                 },
75                 {
76                         name: "request failed calling newRequest",
77                         args: args{
78                                 method:  "*?",
79                                 path:    "url",
80                                 payload: "body",
81                         },
82                         want:    nil,
83                         wantErr: fmt.Errorf("failed to create HTTP request: net/http: invalid method \"*?\""),
84                 },
85         }
86
87         for _, tt := range tests {
88                 t.Run(tt.name, func(t *testing.T) {
89                         client := New(&http.Client{}, false)
90                         var req *http.Request
91                         var err error
92                         if tt.args.userInfo[0] != "" {
93                                 req, err = client.newRequest(tt.args.method, tt.args.path, tt.args.payload, tt.args.userInfo[0], tt.args.userInfo[1])
94                         } else {
95                                 req, err = client.newRequest(tt.args.method, tt.args.path, tt.args.payload)
96                         }
97
98                         if tt.wantErr != nil {
99                                 assertions.Equal(tt.want, req)
100                                 assertions.EqualError(tt.wantErr, err.Error())
101                         } else {
102                                 assertions.Equal("url", req.URL.Path)
103                                 assertions.Equal("application/json", req.Header.Get("Content-Type"))
104                                 if tt.args.userInfo[0] != "" {
105                                         assertions.Contains(req.Header.Get("Authorization"), "Basic dXNlcjpwYXNz")
106                                 } else {
107                                         assertions.Empty(req.Header.Get("Authorization"))
108                                 }
109
110                                 assertions.Nil(err)
111                         }
112
113                 })
114         }
115 }
116
117 func TestGet(t *testing.T) {
118         assertions := require.New(t)
119         type args struct {
120                 header   string
121                 respCode int
122                 resp     interface{}
123                 userInfo [2]string
124         }
125         tests := []struct {
126                 name    string
127                 args    args
128                 wantErr string
129         }{
130                 {
131                         name: "successful GET request",
132                         args: args{
133                                 header:   "application/json",
134                                 respCode: http.StatusOK,
135                                 resp:     "Success!",
136                                 userInfo: [2]string{"user", "pass"},
137                         },
138                         wantErr: "",
139                 },
140                 {
141                         name: "error GET request",
142                         args: args{
143                                 header:   "application/json",
144                                 respCode: http.StatusBadRequest,
145                                 resp:     nil,
146                         },
147                         wantErr: "error response with status: 400 and body:",
148                 },
149         }
150
151         for _, tt := range tests {
152
153                 t.Run(tt.name, func(t *testing.T) {
154                         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
155                                 assertions.Equal(http.MethodGet, r.Method)
156                                 response, _ := json.Marshal(tt.args.resp)
157                                 w.Header().Set("Content-Type", tt.args.header)
158                                 w.WriteHeader(tt.args.respCode)
159                                 w.Write(response)
160                         }))
161                         defer srv.Close()
162
163                         client := New(&http.Client{}, false)
164                         var err error
165                         var res interface{}
166                         if tt.args.userInfo[0] != "" {
167                                 err = client.Get(srv.URL, &res, tt.args.userInfo[0], tt.args.userInfo[1])
168                         } else {
169                                 err = client.Get(srv.URL, &res)
170                         }
171
172                         if err != nil {
173                                 assertions.Contains(err.Error(), tt.wantErr)
174                         }
175                         assertions.Equal(tt.args.resp, res)
176                 })
177         }
178 }
179
180 func TestPost(t *testing.T) {
181         assertions := require.New(t)
182
183         type args struct {
184                 header   string
185                 payload  interface{}
186                 respCode int
187                 resp     interface{}
188                 userInfo [2]string
189         }
190         tests := []struct {
191                 name    string
192                 args    args
193                 wantErr string
194         }{
195                 {
196                         name: "successful POST request",
197                         args: args{
198                                 header:   "application/json",
199                                 payload:  `json:"example"`,
200                                 respCode: http.StatusOK,
201                                 resp:     "Success!",
202                                 userInfo: [2]string{"user", "pass"},
203                         },
204                         wantErr: "",
205                 },
206                 {
207                         name: "error POST request",
208                         args: args{
209                                 header:   "application/json",
210                                 payload:  `json:"example"`,
211                                 respCode: http.StatusBadRequest,
212                                 resp:     nil,
213                         },
214                         wantErr: "error response with status: 400 and body:",
215                 },
216                 {
217                         name: "error to create POST request",
218                         args: args{
219                                 header: "application/json",
220                                 payload: map[string]interface{}{
221                                         "foo": make(chan int),
222                                 },
223                                 respCode: http.StatusBadRequest,
224                                 resp:     nil,
225                         },
226                         wantErr: "failed to marshal request body: json: unsupported type: chan int",
227                 },
228         }
229
230         for _, tt := range tests {
231
232                 t.Run(tt.name, func(t *testing.T) {
233                         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
234
235                                 assert.Equal(t, http.MethodPost, r.Method)
236                                 assert.Contains(t, r.Header.Get("Content-Type"), "application/json")
237
238                                 var reqBody string
239                                 decoder := json.NewDecoder(r.Body)
240                                 decoder.Decode(&reqBody)
241                                 assert.Equal(t, reqBody, `json:"example"`)
242
243                                 response, _ := json.Marshal(tt.args.resp)
244                                 w.Header().Set("Content-Type", tt.args.header)
245                                 w.WriteHeader(tt.args.respCode)
246                                 w.Write(response)
247                         }))
248                         defer srv.Close()
249
250                         client := New(&http.Client{}, false)
251                         var err error
252                         if tt.args.userInfo[0] != "" {
253                                 err = client.Post(srv.URL, tt.args.payload, nil, tt.args.userInfo[0], tt.args.userInfo[1])
254                         } else {
255                                 err = client.Post(srv.URL, tt.args.payload, nil)
256                         }
257
258                         if err != nil {
259                                 assertions.Contains(err.Error(), tt.wantErr)
260                         } else {
261                                 assertions.Equal(tt.args.resp, "Success!")
262                         }
263
264                 })
265         }
266 }
267
268 func TestPut(t *testing.T) {
269         assertions := require.New(t)
270
271         type args struct {
272                 header   string
273                 payload  interface{}
274                 respCode int
275                 resp     interface{}
276                 userInfo [2]string
277         }
278         tests := []struct {
279                 name    string
280                 args    args
281                 wantErr string
282         }{
283                 {
284                         name: "successful PUT request",
285                         args: args{
286                                 header:   "application/json",
287                                 payload:  `json:"example"`,
288                                 respCode: http.StatusOK,
289                                 resp:     "Success!",
290                                 userInfo: [2]string{"user", "pass"},
291                         },
292                         wantErr: "",
293                 },
294                 {
295                         name: "error PUT request",
296                         args: args{
297                                 header:   "application/json",
298                                 payload:  `json:"example"`,
299                                 respCode: http.StatusBadRequest,
300                                 resp:     nil,
301                         },
302                         wantErr: "error response with status: 400 and body:",
303                 },
304                 {
305                         name: "error to create PUT request",
306                         args: args{
307                                 header: "application/json",
308                                 payload: map[string]interface{}{
309                                         "foo": make(chan int),
310                                 },
311                                 respCode: http.StatusBadRequest,
312                                 resp:     nil,
313                         },
314                         wantErr: "failed to marshal request body: json: unsupported type: chan int",
315                 },
316         }
317
318         for _, tt := range tests {
319
320                 t.Run(tt.name, func(t *testing.T) {
321                         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
322
323                                 assert.Equal(t, http.MethodPut, r.Method)
324                                 assert.Contains(t, r.Header.Get("Content-Type"), "application/json")
325
326                                 var reqBody string
327                                 decoder := json.NewDecoder(r.Body)
328                                 decoder.Decode(&reqBody)
329                                 assert.Equal(t, reqBody, `json:"example"`)
330
331                                 response, _ := json.Marshal(tt.args.resp)
332                                 w.Header().Set("Content-Type", tt.args.header)
333                                 w.WriteHeader(tt.args.respCode)
334                                 w.Write(response)
335                         }))
336                         defer srv.Close()
337
338                         client := New(&http.Client{}, false)
339                         var err error
340                         if tt.args.userInfo[0] != "" {
341                                 err = client.Put(srv.URL, tt.args.payload, nil, tt.args.userInfo[0], tt.args.userInfo[1])
342                         } else {
343                                 err = client.Put(srv.URL, tt.args.payload, nil)
344                         }
345
346                         if err != nil {
347                                 assertions.Contains(err.Error(), tt.wantErr)
348                         } else {
349                                 assertions.Equal(tt.args.resp, "Success!")
350                         }
351
352                 })
353         }
354 }
355
356 func TestDelete(t *testing.T) {
357         header := "application/json"
358         respCode := http.StatusOK
359         resp := "Success!"
360
361         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
362
363                 assert.Equal(t, http.MethodDelete, r.Method)
364                 assert.Contains(t, r.Header.Get("Content-Type"), "application/json")
365
366                 var reqBody string
367                 decoder := json.NewDecoder(r.Body)
368                 decoder.Decode(&reqBody)
369                 assert.Equal(t, reqBody, `json:"example"`)
370
371                 response, _ := json.Marshal(resp)
372                 w.Header().Set("Content-Type", header)
373                 w.WriteHeader(respCode)
374                 w.Write(response)
375         }))
376         defer srv.Close()
377
378         client := New(&http.Client{}, false)
379         payload := `json:"example"`
380         // With user info
381         err := client.Delete(srv.URL, payload, nil, "admin", "pass")
382
383         if err != nil {
384                 assert.Equal(t, "", err.Error())
385         }
386
387         // Without user info
388         err = client.Delete(srv.URL, payload, nil)
389
390         if err != nil {
391                 assert.Equal(t, "", err.Error())
392         }
393 }