Register types DMaaP mediator producer
[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         "io/ioutil"
27         "net/http"
28         "reflect"
29         "testing"
30
31         "github.com/stretchr/testify/mock"
32         "github.com/stretchr/testify/require"
33         "oransc.org/nonrtric/dmaapmediatorproducer/mocks"
34 )
35
36 func TestGet(t *testing.T) {
37         clientMock := mocks.HTTPClient{}
38
39         clientMock.On("Get", "http://testOk").Return(&http.Response{
40                 StatusCode: http.StatusOK,
41                 Body:       ioutil.NopCloser(bytes.NewReader([]byte("Response"))),
42         }, nil)
43
44         clientMock.On("Get", "http://testNotOk").Return(&http.Response{
45                 StatusCode: http.StatusBadRequest,
46                 Body:       ioutil.NopCloser(bytes.NewReader([]byte("Bad Response"))),
47         }, nil)
48
49         clientMock.On("Get", "http://testError").Return(nil, errors.New("Failed Request"))
50
51         Client = &clientMock
52
53         type args struct {
54                 url string
55         }
56         tests := []struct {
57                 name        string
58                 args        args
59                 want        []byte
60                 wantErr     bool
61                 wantedError error
62         }{
63                 {
64                         name: "Test Get with OK response",
65                         args: args{
66                                 url: "http://testOk",
67                         },
68                         want:    []byte("Response"),
69                         wantErr: false,
70                 },
71                 {
72                         name: "Test Get with Not OK response",
73                         args: args{
74                                 url: "http://testNotOk",
75                         },
76                         want:    nil,
77                         wantErr: true,
78                         wantedError: RequestError{
79                                 StatusCode: http.StatusBadRequest,
80                                 Body:       []byte("Bad Response"),
81                         },
82                 },
83                 {
84                         name: "Test Get with error",
85                         args: args{
86                                 url: "http://testError",
87                         },
88                         want:        nil,
89                         wantErr:     true,
90                         wantedError: errors.New("Failed Request"),
91                 },
92         }
93         for _, tt := range tests {
94                 t.Run(tt.name, func(t *testing.T) {
95                         got, err := Get(tt.args.url)
96                         if (err != nil) != tt.wantErr {
97                                 t.Errorf("Get() error = %v, wantErr %v", err, tt.wantErr)
98                                 return
99                         }
100                         if !reflect.DeepEqual(got, tt.want) {
101                                 t.Errorf("Get() = %v, want %v", got, tt.want)
102                         }
103                         if tt.wantErr && err.Error() != tt.wantedError.Error() {
104                                 t.Errorf("Get() error = %v, wantedError % v", err, tt.wantedError.Error())
105                         }
106                 })
107         }
108 }
109
110 func TestPutOk(t *testing.T) {
111         assertions := require.New(t)
112         clientMock := mocks.HTTPClient{}
113
114         clientMock.On("Do", mock.Anything).Return(&http.Response{
115                 StatusCode: http.StatusOK,
116         }, nil)
117
118         Client = &clientMock
119         if err := Put("http://localhost:9990", []byte("body")); err != nil {
120                 t.Errorf("Put() error = %v, did not want error", err)
121         }
122         var actualRequest *http.Request
123         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
124                 actualRequest = req
125                 return true
126         }))
127         assertions.Equal(http.MethodPut, actualRequest.Method)
128         assertions.Equal("http", actualRequest.URL.Scheme)
129         assertions.Equal("localhost:9990", actualRequest.URL.Host)
130         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
131         body, _ := ioutil.ReadAll(actualRequest.Body)
132         expectedBody := []byte("body")
133         assertions.Equal(expectedBody, body)
134         clientMock.AssertNumberOfCalls(t, "Do", 1)
135 }
136
137 func TestPutBadResponse(t *testing.T) {
138         assertions := require.New(t)
139         clientMock := mocks.HTTPClient{}
140
141         clientMock.On("Do", mock.Anything).Return(&http.Response{
142                 StatusCode: http.StatusBadRequest,
143                 Body:       ioutil.NopCloser(bytes.NewReader([]byte("Bad Request"))),
144         }, nil)
145
146         Client = &clientMock
147         err := Put("url", []byte("body"))
148         assertions.NotNil("Put() error = %v, wanted error", err)
149         expectedErrorMessage := "Request failed due to error response with status: 400 and body: Bad Request"
150         assertions.Equal(expectedErrorMessage, err.Error())
151 }
152
153 func TestPutError(t *testing.T) {
154         assertions := require.New(t)
155         clientMock := mocks.HTTPClient{}
156
157         clientMock.On("Do", mock.Anything).Return(nil, errors.New("Failed Request"))
158
159         Client = &clientMock
160         err := Put("url", []byte("body"))
161         assertions.NotNil("Put() error = %v, wanted error", err)
162         expectedErrorMessage := "Failed Request"
163         assertions.Equal(expectedErrorMessage, err.Error())
164 }