Change of ECS to ICS in test env
[nonrtric.git] / dmaap-mediator-producer / internal / server / server_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 server
22
23 import (
24         "bytes"
25         "encoding/json"
26         "errors"
27         "io"
28         "io/ioutil"
29         "net/http"
30         "net/http/httptest"
31         "testing"
32
33         "github.com/gorilla/mux"
34         "github.com/stretchr/testify/mock"
35         "github.com/stretchr/testify/require"
36         "oransc.org/nonrtric/dmaapmediatorproducer/internal/jobs"
37         "oransc.org/nonrtric/dmaapmediatorproducer/mocks/jobhandler"
38 )
39
40 func TestNewRouter(t *testing.T) {
41         assertions := require.New(t)
42
43         r := NewRouter(nil)
44         statusRoute := r.Get("status")
45         assertions.NotNil(statusRoute)
46         supportedMethods, err := statusRoute.GetMethods()
47         assertions.Equal([]string{http.MethodGet}, supportedMethods)
48         assertions.Nil(err)
49         path, _ := statusRoute.GetPathTemplate()
50         assertions.Equal("/status", path)
51
52         addJobRoute := r.Get("add")
53         assertions.NotNil(addJobRoute)
54         supportedMethods, err = addJobRoute.GetMethods()
55         assertions.Equal([]string{http.MethodPost}, supportedMethods)
56         assertions.Nil(err)
57         path, _ = addJobRoute.GetPathTemplate()
58         assertions.Equal("/jobs", path)
59
60         deleteJobRoute := r.Get("delete")
61         assertions.NotNil(deleteJobRoute)
62         supportedMethods, err = deleteJobRoute.GetMethods()
63         assertions.Equal([]string{http.MethodDelete}, supportedMethods)
64         assertions.Nil(err)
65         path, _ = deleteJobRoute.GetPathTemplate()
66         assertions.Equal("/jobs/{infoJobId}", path)
67
68         notFoundHandler := r.NotFoundHandler
69         handler := http.HandlerFunc(notFoundHandler.ServeHTTP)
70         responseRecorder := httptest.NewRecorder()
71         handler.ServeHTTP(responseRecorder, newRequest("GET", "/wrong", nil, t))
72         assertions.Equal(http.StatusNotFound, responseRecorder.Code)
73         assertions.Contains(responseRecorder.Body.String(), "404 not found.")
74
75         methodNotAllowedHandler := r.MethodNotAllowedHandler
76         handler = http.HandlerFunc(methodNotAllowedHandler.ServeHTTP)
77         responseRecorder = httptest.NewRecorder()
78         handler.ServeHTTP(responseRecorder, newRequest(http.MethodPut, "/status", nil, t))
79         assertions.Equal(http.StatusMethodNotAllowed, responseRecorder.Code)
80         assertions.Contains(responseRecorder.Body.String(), "Method is not supported.")
81 }
82
83 func TestStatusHandler(t *testing.T) {
84         assertions := require.New(t)
85
86         handler := http.HandlerFunc(statusHandler)
87         responseRecorder := httptest.NewRecorder()
88         r := newRequest(http.MethodGet, "/status", nil, t)
89
90         handler.ServeHTTP(responseRecorder, r)
91
92         assertions.Equal(http.StatusOK, responseRecorder.Code)
93         assertions.Equal("", responseRecorder.Body.String())
94 }
95
96 func TestAddInfoJobHandler(t *testing.T) {
97         assertions := require.New(t)
98
99         type args struct {
100                 job        jobs.JobInfo
101                 mockReturn error
102         }
103         tests := []struct {
104                 name         string
105                 args         args
106                 wantedStatus int
107                 wantedBody   string
108         }{
109                 {
110                         name: "AddInfoJobHandler with correct job, should return OK",
111                         args: args{
112                                 job: jobs.JobInfo{
113                                         Owner:            "owner",
114                                         LastUpdated:      "now",
115                                         InfoJobIdentity:  "jobId",
116                                         TargetUri:        "target",
117                                         InfoJobData:      "{}",
118                                         InfoTypeIdentity: "type",
119                                 },
120                         },
121                         wantedStatus: http.StatusOK,
122                         wantedBody:   "",
123                 },
124                 {
125                         name: "AddInfoJobHandler with incorrect job info, should return BadRequest",
126                         args: args{
127                                 job: jobs.JobInfo{
128                                         Owner: "bad",
129                                 },
130                                 mockReturn: errors.New("error"),
131                         },
132                         wantedStatus: http.StatusBadRequest,
133                         wantedBody:   "Invalid job info. Cause: error",
134                 },
135         }
136         for _, tt := range tests {
137                 t.Run(tt.name, func(t *testing.T) {
138                         jobHandlerMock := jobhandler.JobHandler{}
139                         jobHandlerMock.On("AddJobFromRESTCall", tt.args.job).Return(tt.args.mockReturn)
140
141                         callbackHandlerUnderTest := NewProducerCallbackHandler(&jobHandlerMock)
142
143                         handler := http.HandlerFunc(callbackHandlerUnderTest.addInfoJobHandler)
144                         responseRecorder := httptest.NewRecorder()
145                         r := newRequest(http.MethodPost, "/jobs", &tt.args.job, t)
146
147                         handler.ServeHTTP(responseRecorder, r)
148
149                         assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
150                         assertions.Contains(responseRecorder.Body.String(), tt.wantedBody, tt.name)
151                         jobHandlerMock.AssertCalled(t, "AddJobFromRESTCall", tt.args.job)
152                 })
153         }
154 }
155
156 func TestDeleteJob(t *testing.T) {
157         assertions := require.New(t)
158         jobHandlerMock := jobhandler.JobHandler{}
159         jobHandlerMock.On("DeleteJobFromRESTCall", mock.Anything).Return(nil)
160
161         callbackHandlerUnderTest := NewProducerCallbackHandler(&jobHandlerMock)
162
163         responseRecorder := httptest.NewRecorder()
164         r := mux.SetURLVars(newRequest(http.MethodDelete, "/jobs/", nil, t), map[string]string{"infoJobId": "job1"})
165         handler := http.HandlerFunc(callbackHandlerUnderTest.deleteInfoJobHandler)
166         handler.ServeHTTP(responseRecorder, r)
167         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
168
169         assertions.Equal("", responseRecorder.Body.String())
170
171         jobHandlerMock.AssertCalled(t, "DeleteJobFromRESTCall", "job1")
172 }
173
174 func newRequest(method string, url string, jobInfo *jobs.JobInfo, t *testing.T) *http.Request {
175         var body io.Reader
176         if jobInfo != nil {
177                 bodyAsBytes, _ := json.Marshal(jobInfo)
178                 body = ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
179         }
180         if req, err := http.NewRequest(method, url, body); err == nil {
181                 return req
182         } else {
183                 t.Fatalf("Could not create request due to: %v", err)
184                 return nil
185         }
186 }