47cf8b7c277e18c56b89fd434bacdc011ddbdcd0
[nonrtric/plt/sme.git] / capifcore / 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         "fmt"
26         "io"
27         "net/http"
28         "testing"
29
30         "github.com/stretchr/testify/mock"
31         "github.com/stretchr/testify/require"
32         "oransc.org/nonrtric/capifcore/internal/restclient/mocks"
33 )
34
35 func TestRequestError_Error(t *testing.T) {
36         assertions := require.New(t)
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 TestPutOk(t *testing.T) {
45         assertions := require.New(t)
46         clientMock := mocks.HTTPClient{}
47
48         clientMock.On("Do", mock.Anything).Return(&http.Response{
49                 StatusCode: http.StatusOK,
50                 Body:       io.NopCloser(bytes.NewReader([]byte("body"))),
51         }, nil)
52
53         if err := Put("http://localhost:9990", []byte("body"), &clientMock); err != nil {
54                 t.Errorf("Put() error = %v, did not want error", err)
55         }
56         var actualRequest *http.Request
57         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
58                 actualRequest = req
59                 return true
60         }))
61         assertions.Equal(http.MethodPut, actualRequest.Method)
62         assertions.Equal("http", actualRequest.URL.Scheme)
63         assertions.Equal("localhost:9990", actualRequest.URL.Host)
64         assertions.Equal("application/json", actualRequest.Header.Get("Content-Type"))
65         body, _ := io.ReadAll(actualRequest.Body)
66         expectedBody := []byte("body")
67         assertions.Equal(expectedBody, body)
68         clientMock.AssertNumberOfCalls(t, "Do", 1)
69 }
70
71 func TestPostOk(t *testing.T) {
72         assertions := require.New(t)
73         clientMock := mocks.HTTPClient{}
74
75         clientMock.On("Do", mock.Anything).Return(&http.Response{
76                 StatusCode: http.StatusOK,
77                 Body:       io.NopCloser(bytes.NewReader([]byte("body"))),
78         }, nil)
79
80         headers := map[string]string{
81                 "Content-Type": "application/json",
82         }
83         if err := Post("http://localhost:9990", []byte("body"), headers, &clientMock); err != nil {
84                 t.Errorf("Post() error = %v, did not want error", err)
85         }
86         var actualRequest *http.Request
87         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
88                 actualRequest = req
89                 return true
90         }))
91         assertions.Equal(http.MethodPost, actualRequest.Method)
92         assertions.Equal("http", actualRequest.URL.Scheme)
93         assertions.Equal("localhost:9990", actualRequest.URL.Host)
94         assertions.Equal("application/json", actualRequest.Header.Get("Content-Type"))
95         body, _ := io.ReadAll(actualRequest.Body)
96         expectedBody := []byte("body")
97         assertions.Equal(expectedBody, body)
98         clientMock.AssertNumberOfCalls(t, "Do", 1)
99 }
100
101 func Test_doErrorCases(t *testing.T) {
102         assertions := require.New(t)
103         type args struct {
104                 url              string
105                 mockReturnStatus int
106                 mockReturnBody   []byte
107                 mockReturnError  error
108         }
109         tests := []struct {
110                 name    string
111                 args    args
112                 wantErr error
113         }{
114                 {
115                         name: "Bad request should get RequestError",
116                         args: args{
117                                 url:              "badRequest",
118                                 mockReturnStatus: http.StatusBadRequest,
119                                 mockReturnBody:   []byte("bad request"),
120                                 mockReturnError:  nil,
121                         },
122                         wantErr: RequestError{
123                                 StatusCode: http.StatusBadRequest,
124                                 Body:       []byte("bad request"),
125                         },
126                 },
127                 {
128                         name: "Server unavailable should get error",
129                         args: args{
130                                 url:             "serverUnavailable",
131                                 mockReturnError: fmt.Errorf("Server unavailable"),
132                         },
133                         wantErr: fmt.Errorf("Server unavailable"),
134                 },
135         }
136         for _, tt := range tests {
137                 t.Run(tt.name, func(t *testing.T) {
138                         clientMock := mocks.HTTPClient{}
139                         clientMock.On("Do", mock.Anything).Return(&http.Response{
140                                 StatusCode: tt.args.mockReturnStatus,
141                                 Body:       io.NopCloser(bytes.NewReader(tt.args.mockReturnBody)),
142                         }, tt.args.mockReturnError)
143                         _, err := do("PUT", tt.args.url, nil, map[string]string{}, &clientMock)
144                         assertions.Equal(tt.wantErr, err, tt.name)
145                 })
146         }
147 }