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