Add test for consumer restclient
[nonrtric.git] / test / usecases / oruclosedlooprecovery / 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         "fmt"
25         "io/ioutil"
26         "net/http"
27         "testing"
28
29         "github.com/stretchr/testify/mock"
30         "github.com/stretchr/testify/require"
31         "oransc.org/usecase/oruclosedloop/mocks"
32 )
33
34 func TestRequestError_Error(t *testing.T) {
35         assertions := require.New(t)
36
37         actualError := RequestError{
38                 StatusCode: http.StatusBadRequest,
39                 Body:       []byte("error"),
40         }
41         assertions.Equal("Request failed due to error response with status: 400 and body: error", actualError.Error())
42 }
43
44 func TestGet(t *testing.T) {
45         assertions := require.New(t)
46
47         type args struct {
48                 url              string
49                 mockReturnStatus int
50                 mockReturnBody   []byte
51                 mockReturnError  error
52         }
53         tests := []struct {
54                 name    string
55                 args    args
56                 want    []byte
57                 wantErr error
58         }{
59                 {
60                         name: "Ok response",
61                         args: args{
62                                 url:              "ok",
63                                 mockReturnStatus: http.StatusOK,
64                                 mockReturnBody:   []byte("body"),
65                                 mockReturnError:  nil,
66                         },
67                         want:    []byte("body"),
68                         wantErr: nil,
69                 },
70                 {
71                         name: "Bad request should get RequestError",
72                         args: args{
73                                 url:              "badRequest",
74                                 mockReturnStatus: http.StatusBadRequest,
75                                 mockReturnBody:   []byte("bad request"),
76                                 mockReturnError:  nil,
77                         },
78                         want: nil,
79                         wantErr: RequestError{
80                                 StatusCode: http.StatusBadRequest,
81                                 Body:       []byte("bad request"),
82                         },
83                 },
84                 {
85                         name: "Server unavailable should get error",
86                         args: args{
87                                 url:             "serverUnavailable",
88                                 mockReturnError: fmt.Errorf("Server unavailable"),
89                         },
90                         want:    nil,
91                         wantErr: fmt.Errorf("Server unavailable"),
92                 },
93         }
94         for _, tt := range tests {
95                 t.Run(tt.name, func(t *testing.T) {
96                         clientMock := mocks.HTTPClient{}
97                         clientMock.On("Get", tt.args.url).Return(&http.Response{
98                                 StatusCode: tt.args.mockReturnStatus,
99                                 Body:       ioutil.NopCloser(bytes.NewReader(tt.args.mockReturnBody)),
100                         }, tt.args.mockReturnError)
101                         Client = &clientMock
102
103                         got, err := Get(tt.args.url)
104                         assertions.Equal(tt.wantErr, err, tt.name)
105                         assertions.Equal(tt.want, got, tt.name)
106                         clientMock.AssertCalled(t, "Get", tt.args.url)
107                 })
108         }
109 }
110
111 func TestPutWithoutAuth(t *testing.T) {
112         assertions := require.New(t)
113
114         clientMock := mocks.HTTPClient{}
115         clientMock.On("Do", mock.Anything).Return(&http.Response{
116                 StatusCode: http.StatusOK,
117         }, nil)
118         Client = &clientMock
119
120         error := PutWithoutAuth("url", []byte("body"))
121
122         assertions.Nil(error)
123         var actualRequest *http.Request
124         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
125                 actualRequest = req
126                 return true
127         }))
128         assertions.Equal(http.MethodPut, actualRequest.Method)
129         assertions.Equal("url", actualRequest.URL.Path)
130         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
131         assertions.Empty(actualRequest.Header.Get("Authorization"))
132         body, _ := ioutil.ReadAll(actualRequest.Body)
133         expectedBody := []byte("body")
134         assertions.Equal(expectedBody, body)
135         clientMock.AssertNumberOfCalls(t, "Do", 1)
136 }
137
138 func TestPut(t *testing.T) {
139         assertions := require.New(t)
140
141         clientMock := mocks.HTTPClient{}
142         clientMock.On("Do", mock.Anything).Return(&http.Response{
143                 StatusCode: http.StatusOK,
144         }, nil)
145         Client = &clientMock
146
147         error := Put("url", "body", "admin", "pwd")
148
149         assertions.Nil(error)
150         var actualRequest *http.Request
151         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
152                 actualRequest = req
153                 return true
154         }))
155         assertions.Equal(http.MethodPut, actualRequest.Method)
156         assertions.Equal("url", actualRequest.URL.Path)
157         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
158         tempRequest, _ := http.NewRequest("", "", nil)
159         tempRequest.SetBasicAuth("admin", "pwd")
160         assertions.Equal(tempRequest.Header.Get("Authorization"), actualRequest.Header.Get("Authorization"))
161         body, _ := ioutil.ReadAll(actualRequest.Body)
162         expectedBody := []byte("body")
163         assertions.Equal(expectedBody, body)
164         clientMock.AssertNumberOfCalls(t, "Do", 1)
165 }
166
167 func TestDelete(t *testing.T) {
168         assertions := require.New(t)
169
170         clientMock := mocks.HTTPClient{}
171         clientMock.On("Do", mock.Anything).Return(&http.Response{
172                 StatusCode: http.StatusOK,
173         }, nil)
174         Client = &clientMock
175
176         error := Delete("url")
177
178         assertions.Nil(error)
179         var actualRequest *http.Request
180         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
181                 actualRequest = req
182                 return true
183         }))
184         assertions.Equal(http.MethodDelete, actualRequest.Method)
185         assertions.Equal("url", actualRequest.URL.Path)
186         assertions.Empty(actualRequest.Header.Get("Content-Type"))
187         assertions.Empty(actualRequest.Header.Get("Authorization"))
188         assertions.Equal(http.NoBody, actualRequest.Body)
189         clientMock.AssertNumberOfCalls(t, "Do", 1)
190 }
191
192 func Test_doErrorCases(t *testing.T) {
193         assertions := require.New(t)
194
195         type args struct {
196                 url              string
197                 mockReturnStatus int
198                 mockReturnBody   []byte
199                 mockReturnError  error
200         }
201         tests := []struct {
202                 name    string
203                 args    args
204                 wantErr error
205         }{
206                 {
207                         name: "Bad request should get RequestError",
208                         args: args{
209                                 url:              "badRequest",
210                                 mockReturnStatus: http.StatusBadRequest,
211                                 mockReturnBody:   []byte("bad request"),
212                                 mockReturnError:  nil,
213                         },
214                         wantErr: RequestError{
215                                 StatusCode: http.StatusBadRequest,
216                                 Body:       []byte("bad request"),
217                         },
218                 },
219                 {
220                         name: "Server unavailable should get error",
221                         args: args{
222                                 url:             "serverUnavailable",
223                                 mockReturnError: fmt.Errorf("Server unavailable"),
224                         },
225                         wantErr: fmt.Errorf("Server unavailable"),
226                 },
227         }
228         for _, tt := range tests {
229                 t.Run(tt.name, func(t *testing.T) {
230                         clientMock := mocks.HTTPClient{}
231                         clientMock.On("Do", mock.Anything).Return(&http.Response{
232                                 StatusCode: tt.args.mockReturnStatus,
233                                 Body:       ioutil.NopCloser(bytes.NewReader(tt.args.mockReturnBody)),
234                         }, tt.args.mockReturnError)
235                         Client = &clientMock
236
237                         err := do("PUT", tt.args.url, nil)
238                         assertions.Equal(tt.wantErr, err, tt.name)
239                 })
240         }
241 }