f2899dfad80be9d05a97b816e966a5743a380c8d
[nonrtric.git] / test / usecases / odusliceassurance / goversion / 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/require"
31 )
32
33 func TestNewRequest(t *testing.T) {
34         assertions := require.New(t)
35
36         bodyBytes, _ := json.Marshal("body")
37         succesfullReq, _ := http.NewRequest(http.MethodGet, "url", bytes.NewReader(bodyBytes))
38
39         type args struct {
40                 method  string
41                 path    string
42                 payload interface{}
43         }
44         tests := []struct {
45                 name    string
46                 args    args
47                 want    *http.Request
48                 wantErr error
49         }{
50                 {
51                         name: "succesfull newRequest",
52                         args: args{
53                                 method:  http.MethodGet,
54                                 path:    "url",
55                                 payload: "body",
56                         },
57                         want:    succesfullReq,
58                         wantErr: nil,
59                 },
60                 {
61                         name: "request failed json marshal",
62                         args: args{
63                                 method: http.MethodGet,
64                                 path:   "url",
65                                 payload: map[string]interface{}{
66                                         "foo": make(chan int),
67                                 },
68                         },
69                         want:    nil,
70                         wantErr: fmt.Errorf("failed to marshal request body: json: unsupported type: chan int"),
71                 },
72                 {
73                         name: "request failed calling newRequest",
74                         args: args{
75                                 method:  "*?",
76                                 path:    "url",
77                                 payload: "body",
78                         },
79                         want:    nil,
80                         wantErr: fmt.Errorf("failed to create HTTP request: net/http: invalid method \"*?\""),
81                 },
82         }
83
84         for _, tt := range tests {
85                 t.Run(tt.name, func(t *testing.T) {
86                         client := New(&http.Client{})
87
88                         req, err := client.newRequest(tt.args.method, tt.args.path, tt.args.payload)
89                         if tt.wantErr != nil {
90                                 assertions.Equal(tt.want, req)
91                                 assertions.EqualError(tt.wantErr, err.Error())
92                         } else {
93                                 assertions.Equal("url", req.URL.Path)
94                                 assertions.Equal("application/json; charset=utf-8", req.Header.Get("Content-Type"))
95                                 assertions.Empty(req.Header.Get("Authorization"))
96                                 assertions.Nil(err)
97                         }
98
99                 })
100         }
101 }
102
103 func TestGet(t *testing.T) {
104         assertions := require.New(t)
105         type args struct {
106                 header   string
107                 respCode int
108                 resp     interface{}
109         }
110         tests := []struct {
111                 name    string
112                 args    args
113                 wantErr string
114         }{
115                 {
116                         name: "successful GET request",
117                         args: args{
118                                 header:   "application/json",
119                                 respCode: http.StatusOK,
120                                 resp:     "Success!",
121                         },
122                         wantErr: "",
123                 },
124                 {
125                         name: "error GET request",
126                         args: args{
127                                 header:   "application/json",
128                                 respCode: http.StatusBadRequest,
129                                 resp:     nil,
130                         },
131                         wantErr: "failed to do request, 400 status code received",
132                 },
133         }
134
135         for _, tt := range tests {
136
137                 t.Run(tt.name, func(t *testing.T) {
138                         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
139                                 response, _ := json.Marshal(tt.args.resp)
140                                 w.Header().Set("Content-Type", tt.args.header)
141                                 w.WriteHeader(tt.args.respCode)
142                                 w.Write(response)
143                         }))
144                         defer srv.Close()
145
146                         client := New(&http.Client{})
147                         var res interface{}
148                         err := client.Get(srv.URL, &res)
149
150                         if err != nil {
151                                 assertions.Equal(tt.wantErr, err.Error())
152                         }
153                         assertions.Equal(tt.args.resp, res)
154                 })
155         }
156 }
157
158 func TestPost(t *testing.T) {
159         assertions := require.New(t)
160         type args struct {
161                 header   string
162                 respCode int
163                 resp     interface{}
164         }
165         tests := []struct {
166                 name    string
167                 args    args
168                 wantErr string
169         }{
170                 {
171                         name: "successful Post request",
172                         args: args{
173                                 header:   "application/json",
174                                 respCode: http.StatusOK,
175                                 resp:     "Success!",
176                         },
177                         wantErr: "",
178                 },
179         }
180
181         for _, tt := range tests {
182
183                 t.Run(tt.name, func(t *testing.T) {
184                         srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
185
186                                 assertions.Equal(http.MethodPost, r.Method)
187                                 assertions.Contains(r.Header.Get("Content-Type"), "application/json")
188
189                                 var reqBody interface{}
190                                 decoder := json.NewDecoder(r.Body)
191                                 decoder.Decode(&reqBody)
192                                 assertions.Equal(reqBody, `json:"example"`)
193
194                                 response, _ := json.Marshal(tt.args.resp)
195                                 w.Header().Set("Content-Type", tt.args.header)
196                                 w.WriteHeader(tt.args.respCode)
197                                 w.Write(response)
198                         }))
199                         defer srv.Close()
200
201                         client := New(&http.Client{})
202                         payload := `json:"example"`
203                         err := client.Post(srv.URL, payload, nil)
204
205                         if err != nil {
206                                 assertions.Equal(tt.wantErr, err.Error())
207                         }
208                 })
209         }
210 }