2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
30 "github.com/stretchr/testify/mock"
31 "github.com/stretchr/testify/require"
32 "oransc.org/nonrtric/capifcore/internal/restclient/mocks"
35 func TestRequestError_Error(t *testing.T) {
36 assertions := require.New(t)
37 actualError := RequestError{
38 StatusCode: http.StatusBadRequest,
39 Body: []byte("error"),
41 assertions.Equal("Request failed due to error response with status: 400 and body: error", actualError.Error())
44 func TestPutOk(t *testing.T) {
45 assertions := require.New(t)
46 clientMock := mocks.HTTPClient{}
48 clientMock.On("Do", mock.Anything).Return(&http.Response{
49 StatusCode: http.StatusOK,
52 if err := Put("http://localhost:9990", []byte("body"), &clientMock); err != nil {
53 t.Errorf("Put() error = %v, did not want error", err)
55 var actualRequest *http.Request
56 clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
60 assertions.Equal(http.MethodPut, actualRequest.Method)
61 assertions.Equal("http", actualRequest.URL.Scheme)
62 assertions.Equal("localhost:9990", actualRequest.URL.Host)
63 assertions.Equal("application/json", actualRequest.Header.Get("Content-Type"))
64 body, _ := io.ReadAll(actualRequest.Body)
65 expectedBody := []byte("body")
66 assertions.Equal(expectedBody, body)
67 clientMock.AssertNumberOfCalls(t, "Do", 1)
70 func Test_doErrorCases(t *testing.T) {
71 assertions := require.New(t)
84 name: "Bad request should get RequestError",
87 mockReturnStatus: http.StatusBadRequest,
88 mockReturnBody: []byte("bad request"),
91 wantErr: RequestError{
92 StatusCode: http.StatusBadRequest,
93 Body: []byte("bad request"),
97 name: "Server unavailable should get error",
99 url: "serverUnavailable",
100 mockReturnError: fmt.Errorf("Server unavailable"),
102 wantErr: fmt.Errorf("Server unavailable"),
105 for _, tt := range tests {
106 t.Run(tt.name, func(t *testing.T) {
107 clientMock := mocks.HTTPClient{}
108 clientMock.On("Do", mock.Anything).Return(&http.Response{
109 StatusCode: tt.args.mockReturnStatus,
110 Body: io.NopCloser(bytes.NewReader(tt.args.mockReturnBody)),
111 }, tt.args.mockReturnError)
112 err := do("PUT", tt.args.url, nil, "", &clientMock)
113 assertions.Equal(tt.wantErr, err, tt.name)