2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: 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===================================
21 package publishservice
30 "oransc.org/nonrtric/capifcore/internal/common29122"
31 "oransc.org/nonrtric/capifcore/internal/eventsapi"
32 "oransc.org/nonrtric/capifcore/internal/providermanagement"
34 "github.com/labstack/echo/v4"
36 publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
38 "oransc.org/nonrtric/capifcore/internal/helmmanagement"
39 helmMocks "oransc.org/nonrtric/capifcore/internal/helmmanagement/mocks"
40 serviceMocks "oransc.org/nonrtric/capifcore/internal/providermanagement/mocks"
42 "github.com/deepmap/oapi-codegen/pkg/middleware"
43 "github.com/deepmap/oapi-codegen/pkg/testutil"
44 echomiddleware "github.com/labstack/echo/v4/middleware"
45 "github.com/stretchr/testify/assert"
46 "github.com/stretchr/testify/mock"
49 func TestPublishUnpublishService(t *testing.T) {
53 serviceRegisterMock := serviceMocks.ServiceRegister{}
54 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId"})
55 helmManagerMock := helmMocks.HelmManager{}
56 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
57 serviceUnderTest, eventChannel, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
59 // Check no services published for provider
60 result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
62 assert.Equal(t, http.StatusNotFound, result.Code())
64 apiName := "app-management"
65 namespace := "namespace"
66 repoName := "repoName"
67 chartName := "chartName"
68 releaseName := "releaseName"
69 description := fmt.Sprintf("Description,%s,%s,%s,%s", namespace, repoName, chartName, releaseName)
70 newServiceDescription := getServiceAPIDescription(aefId, apiName, description)
72 // Publish a service for provider
73 result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
75 assert.Equal(t, http.StatusCreated, result.Code())
76 var resultService publishapi.ServiceAPIDescription
77 err := result.UnmarshalBodyToObject(&resultService)
78 assert.NoError(t, err, "error unmarshaling response")
79 newApiId := "api_id_" + apiName
80 assert.Equal(t, newApiId, *resultService.ApiId)
81 assert.Equal(t, "http://example.com/"+apfId+"/service-apis/"+*resultService.ApiId, result.Recorder.Header().Get(echo.HeaderLocation))
82 newServiceDescription.ApiId = &newApiId
83 wantedAPILIst := []publishapi.ServiceAPIDescription{newServiceDescription}
84 assert.True(t, serviceUnderTest.AreAPIsPublished(&wantedAPILIst))
85 assert.True(t, serviceUnderTest.IsAPIPublished(aefId, apiName))
86 serviceRegisterMock.AssertCalled(t, "GetAefsForPublisher", apfId)
87 helmManagerMock.AssertCalled(t, "InstallHelmChart", namespace, repoName, chartName, releaseName)
88 assert.ElementsMatch(t, []string{aefId}, serviceUnderTest.getAllAefIds())
89 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
90 assert.Fail(t, "No event sent")
92 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
93 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIAVAILABLE, publishEvent.Events)
96 // Check that the service is published for the provider
97 result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
99 assert.Equal(t, http.StatusOK, result.Code())
100 err = result.UnmarshalBodyToObject(&resultService)
101 assert.NoError(t, err, "error unmarshaling response")
102 assert.Equal(t, *resultService.ApiId, newApiId)
104 // Publish the same service again should result in Forbidden
105 result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
107 assert.Equal(t, http.StatusForbidden, result.Code())
108 var resultError common29122.ProblemDetails
109 err = result.UnmarshalBodyToObject(&resultError)
110 assert.NoError(t, err, "error unmarshaling response")
111 assert.Contains(t, *resultError.Cause, "already published")
112 assert.Equal(t, http.StatusForbidden, *resultError.Status)
114 // Delete the service
115 helmManagerMock.On("UninstallHelmChart", mock.Anything, mock.Anything).Return(nil)
117 result = testutil.NewRequest().Delete("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
119 assert.Equal(t, http.StatusNoContent, result.Code())
120 helmManagerMock.AssertCalled(t, "UninstallHelmChart", namespace, chartName)
121 assert.Empty(t, serviceUnderTest.getAllAefIds())
123 // Check no services published
124 result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
126 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
127 assert.Fail(t, "No event sent")
129 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
130 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE, publishEvent.Events)
133 assert.Equal(t, http.StatusNotFound, result.Code())
136 func TestPostUnpublishedServiceWithUnregisteredFunction(t *testing.T) {
139 serviceRegisterMock := serviceMocks.ServiceRegister{}
140 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{"otherAefId"})
141 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
143 newServiceDescription := getServiceAPIDescription(aefId, "apiName", "description")
146 result := testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
148 assert.Equal(t, http.StatusNotFound, result.Code())
149 var resultError common29122.ProblemDetails
150 err := result.UnmarshalBodyToObject(&resultError)
151 assert.NoError(t, err, "error unmarshaling response")
152 assert.Contains(t, *resultError.Cause, aefId)
153 assert.Contains(t, *resultError.Cause, "not registered")
154 assert.Equal(t, http.StatusNotFound, *resultError.Status)
157 func TestGetServices(t *testing.T) {
160 serviceRegisterMock := serviceMocks.ServiceRegister{}
161 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId})
162 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
164 // Check no services published for provider
165 result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
167 assert.Equal(t, http.StatusNotFound, result.Code())
169 serviceDescription1 := getServiceAPIDescription(aefId, "api1", "Description")
170 serviceDescription2 := getServiceAPIDescription(aefId, "api2", "Description")
172 // Publish a service for provider
173 testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription1).Go(t, requestHandler)
174 testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription2).Go(t, requestHandler)
176 // Get all services for provider
177 result = testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
178 assert.Equal(t, http.StatusOK, result.Code())
179 var resultServices []publishapi.ServiceAPIDescription
180 err := result.UnmarshalBodyToObject(&resultServices)
181 assert.NoError(t, err, "error unmarshaling response")
182 assert.Len(t, resultServices, 2)
183 apiId1 := "api_id_api1"
184 serviceDescription1.ApiId = &apiId1
185 apiId2 := "api_id_api2"
186 serviceDescription2.ApiId = &apiId2
187 assert.Contains(t, resultServices, serviceDescription1)
188 assert.Contains(t, resultServices, serviceDescription2)
191 func TestGetPublishedServices(t *testing.T) {
192 serviceUnderTest := NewPublishService(nil, nil, nil)
194 profiles := make([]publishapi.AefProfile, 1)
195 serviceDescription := publishapi.ServiceAPIDescription{
196 AefProfiles: &profiles,
198 serviceUnderTest.publishedServices["publisher1"] = []publishapi.ServiceAPIDescription{
201 serviceUnderTest.publishedServices["publisher2"] = []publishapi.ServiceAPIDescription{
204 result := serviceUnderTest.GetAllPublishedServices()
205 assert.Len(t, result, 2)
208 func TestUpdateDescription(t *testing.T) {
210 serviceApiId := "serviceApiId"
213 description := "description"
215 serviceRegisterMock := serviceMocks.ServiceRegister{}
216 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
217 helmManagerMock := helmMocks.HelmManager{}
218 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
219 serviceUnderTest, eventChannel, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
220 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
221 serviceDescription.ApiId = &serviceApiId
222 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
223 (*serviceDescription.AefProfiles)[0].AefId = aefId
226 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
227 updatedServiceDescription.ApiId = &serviceApiId
228 (*updatedServiceDescription.AefProfiles)[0].AefId = aefId
229 newDescription := "new description"
230 updatedServiceDescription.Description = &newDescription
231 newDomainName := "new domainName"
232 (*updatedServiceDescription.AefProfiles)[0].DomainName = &newDomainName
234 newProfileDomain := "new profile Domain name"
235 var protocol publishapi.Protocol = "HTTP_1_1"
236 test := make([]publishapi.AefProfile, 1)
237 test = *updatedServiceDescription.AefProfiles
238 test = append(test, publishapi.AefProfile{
241 DomainName: &newProfileDomain,
243 Versions: []publishapi.Version{
246 Resources: &[]publishapi.Resource{
248 CommType: "REQUEST_RESPONSE",
249 Operations: &[]publishapi.Operation{
261 updatedServiceDescription.AefProfiles = &test
263 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
265 var resultService publishapi.ServiceAPIDescription
266 assert.Equal(t, http.StatusOK, result.Code())
267 err := result.UnmarshalBodyToObject(&resultService)
268 assert.NoError(t, err, "error unmarshaling response")
269 assert.Equal(t, newDescription, *resultService.Description)
270 assert.Equal(t, newDomainName, *(*resultService.AefProfiles)[0].DomainName)
271 assert.Equal(t, "aefIdNew", (*resultService.AefProfiles)[1].AefId)
272 assert.True(t, serviceUnderTest.IsAPIPublished("aefIdNew", "path"))
274 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
275 assert.Fail(t, "No event sent")
277 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
278 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIUPDATE, publishEvent.Events)
282 func TestUpdateValidServiceWithDeletedFunction(t *testing.T) {
284 serviceApiId := "serviceApiId"
287 description := "description"
289 serviceRegisterMock := serviceMocks.ServiceRegister{}
290 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
291 helmManagerMock := helmMocks.HelmManager{}
292 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
293 serviceUnderTest, _, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
295 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
296 serviceDescription.ApiId = &serviceApiId
297 (*serviceDescription.AefProfiles)[0].AefId = aefId
299 newProfileDomain := "new profile Domain name"
300 var protocol publishapi.Protocol = "HTTP_1_1"
301 test := make([]publishapi.AefProfile, 1)
302 test = *serviceDescription.AefProfiles
303 test = append(test, publishapi.AefProfile{
306 DomainName: &newProfileDomain,
308 Versions: []publishapi.Version{
311 Resources: &[]publishapi.Resource{
313 CommType: "REQUEST_RESPONSE",
314 Operations: &[]publishapi.Operation{
325 serviceDescription.AefProfiles = &test
326 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
329 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
330 updatedServiceDescription.ApiId = &serviceApiId
331 test1 := make([]publishapi.AefProfile, 1)
332 test1 = *updatedServiceDescription.AefProfiles
333 test1 = append(test1, publishapi.AefProfile{
336 DomainName: &newProfileDomain,
338 Versions: []publishapi.Version{
341 Resources: &[]publishapi.Resource{
343 CommType: "REQUEST_RESPONSE",
344 Operations: &[]publishapi.Operation{
355 updatedServiceDescription.AefProfiles = &test1
356 testFunc := []publishapi.AefProfile{
357 (*updatedServiceDescription.AefProfiles)[1],
360 updatedServiceDescription.AefProfiles = &testFunc
361 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
362 var resultService publishapi.ServiceAPIDescription
363 assert.Equal(t, http.StatusOK, result.Code())
364 err := result.UnmarshalBodyToObject(&resultService)
365 assert.NoError(t, err, "error unmarshaling response")
366 assert.Len(t, (*resultService.AefProfiles), 1)
367 assert.False(t, serviceUnderTest.IsAPIPublished("aefId", "path"))
371 func TestPublishInvalidService(t *testing.T) {
372 _, _, requestHandler := getEcho(nil, nil)
373 newServiceDescription := getServiceAPIDescription("aefId", " ", "description")
376 result := testutil.NewRequest().Post("/apfId/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
378 assert.Equal(t, http.StatusBadRequest, result.Code())
379 var resultError common29122.ProblemDetails
380 err := result.UnmarshalBodyToObject(&resultError)
381 assert.NoError(t, err, "error unmarshaling response")
382 assert.Contains(t, *resultError.Cause, "missing")
383 assert.Contains(t, *resultError.Cause, "apiName")
384 assert.Equal(t, http.StatusBadRequest, *resultError.Status)
387 func getEcho(serviceRegister providermanagement.ServiceRegister, helmManager helmmanagement.HelmManager) (*PublishService, chan eventsapi.EventNotification, *echo.Echo) {
388 swagger, err := publishapi.GetSwagger()
390 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
394 swagger.Servers = nil
396 eventChannel := make(chan eventsapi.EventNotification)
397 ps := NewPublishService(serviceRegister, helmManager, eventChannel)
400 e.Use(echomiddleware.Logger())
401 e.Use(middleware.OapiRequestValidator(swagger))
403 publishapi.RegisterHandlers(e, ps)
404 return ps, eventChannel, e
407 func getServiceAPIDescription(aefId, apiName, description string) publishapi.ServiceAPIDescription {
408 domainName := "domainName"
409 var protocol publishapi.Protocol = "HTTP_1_1"
410 return publishapi.ServiceAPIDescription{
411 AefProfiles: &[]publishapi.AefProfile{
414 DomainName: &domainName,
416 Versions: []publishapi.Version{
419 Resources: &[]publishapi.Resource{
421 CommType: "REQUEST_RESPONSE",
422 Operations: &[]publishapi.Operation{
434 Description: &description,
438 // waitForEvent waits for the channel to receive an event for the specified max timeout.
439 // Returns true if waiting timed out.
440 func waitForEvent(ch chan eventsapi.EventNotification, timeout time.Duration) (*eventsapi.EventNotification, bool) {
443 return &event, false // completed normally
444 case <-time.After(timeout):
445 return nil, true // timed out