Merge "Refactor Go code"
[nonrtric.git] / dmaap-mediator-producer / internal / restclient / HTTPClient_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 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package restclient
22
23 import (
24         "bytes"
25         "errors"
26         "fmt"
27         "io/ioutil"
28         "net/http"
29         "testing"
30
31         "github.com/stretchr/testify/mock"
32         "github.com/stretchr/testify/require"
33         "oransc.org/nonrtric/dmaapmediatorproducer/mocks/httpclient"
34 )
35
36 func TestRequestError_Error(t *testing.T) {
37         assertions := require.New(t)
38         actualError := RequestError{
39                 StatusCode: http.StatusBadRequest,
40                 Body:       []byte("error"),
41         }
42         assertions.Equal("Request failed due to error response with status: 400 and body: error", actualError.Error())
43 }
44 func TestGet(t *testing.T) {
45         assertions := require.New(t)
46         type args struct {
47                 url              string
48                 mockReturnStatus int
49                 mockReturnBody   string
50                 mockReturnError  error
51         }
52         tests := []struct {
53                 name        string
54                 args        args
55                 want        []byte
56                 wantedError error
57         }{
58                 {
59                         name: "Test Get with OK response",
60                         args: args{
61                                 url:              "http://testOk",
62                                 mockReturnStatus: http.StatusOK,
63                                 mockReturnBody:   "Response",
64                         },
65                         want: []byte("Response"),
66                 },
67                 {
68                         name: "Test Get with Not OK response",
69                         args: args{
70                                 url:              "http://testNotOk",
71                                 mockReturnStatus: http.StatusBadRequest,
72                                 mockReturnBody:   "Bad Response",
73                         },
74                         want: nil,
75                         wantedError: RequestError{
76                                 StatusCode: http.StatusBadRequest,
77                                 Body:       []byte("Bad Response"),
78                         },
79                 },
80                 {
81                         name: "Test Get with error",
82                         args: args{
83                                 url:             "http://testError",
84                                 mockReturnError: errors.New("Failed Request"),
85                         },
86                         want:        nil,
87                         wantedError: errors.New("Failed Request"),
88                 },
89         }
90         for _, tt := range tests {
91                 t.Run(tt.name, func(t *testing.T) {
92                         clientMock := httpclient.HTTPClient{}
93                         clientMock.On("Get", tt.args.url).Return(&http.Response{
94                                 StatusCode: tt.args.mockReturnStatus,
95                                 Body:       ioutil.NopCloser(bytes.NewReader([]byte(tt.args.mockReturnBody))),
96                         }, tt.args.mockReturnError)
97
98                         got, err := Get(tt.args.url, &clientMock)
99                         assertions.Equal(tt.wantedError, err, tt.name)
100                         assertions.Equal(tt.want, got, tt.name)
101                         clientMock.AssertCalled(t, "Get", tt.args.url)
102                 })
103         }
104 }
105
106 func TestPutOk(t *testing.T) {
107         assertions := require.New(t)
108         clientMock := httpclient.HTTPClient{}
109
110         clientMock.On("Do", mock.Anything).Return(&http.Response{
111                 StatusCode: http.StatusOK,
112         }, nil)
113
114         if err := Put("http://localhost:9990", []byte("body"), &clientMock); err != nil {
115                 t.Errorf("Put() error = %v, did not want error", err)
116         }
117         var actualRequest *http.Request
118         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
119                 actualRequest = req
120                 return true
121         }))
122         assertions.Equal(http.MethodPut, actualRequest.Method)
123         assertions.Equal("http", actualRequest.URL.Scheme)
124         assertions.Equal("localhost:9990", actualRequest.URL.Host)
125         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
126         body, _ := ioutil.ReadAll(actualRequest.Body)
127         expectedBody := []byte("body")
128         assertions.Equal(expectedBody, body)
129         clientMock.AssertNumberOfCalls(t, "Do", 1)
130 }
131
132 func TestPostOk(t *testing.T) {
133         assertions := require.New(t)
134         clientMock := httpclient.HTTPClient{}
135
136         clientMock.On("Do", mock.Anything).Return(&http.Response{
137                 StatusCode: http.StatusOK,
138         }, nil)
139
140         if err := Post("http://localhost:9990", []byte("body"), &clientMock); err != nil {
141                 t.Errorf("Put() error = %v, did not want error", err)
142         }
143         var actualRequest *http.Request
144         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
145                 actualRequest = req
146                 return true
147         }))
148         assertions.Equal(http.MethodPost, actualRequest.Method)
149         assertions.Equal("http", actualRequest.URL.Scheme)
150         assertions.Equal("localhost:9990", actualRequest.URL.Host)
151         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
152         body, _ := ioutil.ReadAll(actualRequest.Body)
153         expectedBody := []byte("body")
154         assertions.Equal(expectedBody, body)
155         clientMock.AssertNumberOfCalls(t, "Do", 1)
156 }
157
158 func Test_doErrorCases(t *testing.T) {
159         assertions := require.New(t)
160         type args struct {
161                 url              string
162                 mockReturnStatus int
163                 mockReturnBody   []byte
164                 mockReturnError  error
165         }
166         tests := []struct {
167                 name    string
168                 args    args
169                 wantErr error
170         }{
171                 {
172                         name: "Bad request should get RequestError",
173                         args: args{
174                                 url:              "badRequest",
175                                 mockReturnStatus: http.StatusBadRequest,
176                                 mockReturnBody:   []byte("bad request"),
177                                 mockReturnError:  nil,
178                         },
179                         wantErr: RequestError{
180                                 StatusCode: http.StatusBadRequest,
181                                 Body:       []byte("bad request"),
182                         },
183                 },
184                 {
185                         name: "Server unavailable should get error",
186                         args: args{
187                                 url:             "serverUnavailable",
188                                 mockReturnError: fmt.Errorf("Server unavailable"),
189                         },
190                         wantErr: fmt.Errorf("Server unavailable"),
191                 },
192         }
193         for _, tt := range tests {
194                 t.Run(tt.name, func(t *testing.T) {
195                         clientMock := httpclient.HTTPClient{}
196                         clientMock.On("Do", mock.Anything).Return(&http.Response{
197                                 StatusCode: tt.args.mockReturnStatus,
198                                 Body:       ioutil.NopCloser(bytes.NewReader(tt.args.mockReturnBody)),
199                         }, tt.args.mockReturnError)
200                         err := do("PUT", tt.args.url, nil, &clientMock)
201                         assertions.Equal(tt.wantErr, err, tt.name)
202                 })
203         }
204 }