2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022-2023: Nordix Foundation
6 // Copyright (C) 2024: OpenInfra Foundation Europe
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 // ========================LICENSE_END===================================
22 package publishservice
31 "oransc.org/nonrtric/capifcore/internal/common29122"
32 "oransc.org/nonrtric/capifcore/internal/eventsapi"
33 "oransc.org/nonrtric/capifcore/internal/providermanagement"
35 "github.com/labstack/echo/v4"
37 publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
39 "oransc.org/nonrtric/capifcore/internal/helmmanagement"
40 helmMocks "oransc.org/nonrtric/capifcore/internal/helmmanagement/mocks"
41 serviceMocks "oransc.org/nonrtric/capifcore/internal/providermanagement/mocks"
43 "github.com/deepmap/oapi-codegen/pkg/middleware"
44 "github.com/deepmap/oapi-codegen/pkg/testutil"
45 echomiddleware "github.com/labstack/echo/v4/middleware"
46 "github.com/stretchr/testify/assert"
47 "github.com/stretchr/testify/mock"
50 func TestUnregisteredService(t *testing.T) {
52 serviceRegisterMock := serviceMocks.ServiceRegister{}
53 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(false)
55 helmManagerMock := helmMocks.HelmManager{}
56 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
57 _, _, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
59 // Check no services published
60 result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
61 assert.Equal(t, http.StatusNotFound, result.Code())
63 var resultError common29122.ProblemDetails
64 err := result.UnmarshalJsonToObject(&resultError)
65 assert.NoError(t, err, "error unmarshaling response")
67 assert.Contains(t, *resultError.Cause, "api is only available for publishers")
68 assert.Equal(t, http.StatusNotFound, *resultError.Status)
72 func TestPublishUnpublishService(t *testing.T) {
76 serviceRegisterMock := serviceMocks.ServiceRegister{}
77 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId"})
78 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
79 helmManagerMock := helmMocks.HelmManager{}
80 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
81 serviceUnderTest, eventChannel, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
83 // Check no services published
84 var resultServices []publishapi.ServiceAPIDescription
85 result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
86 assert.Equal(t, http.StatusOK, result.Code())
88 // Parse JSON from the response body
89 err := result.UnmarshalJsonToObject(&resultServices)
90 assert.NoError(t, err, "error unmarshaling response")
92 // Check if the parsed array is empty
93 assert.Zero(t, len(resultServices))
95 apiName := "app-management"
96 namespace := "namespace"
97 repoName := "repoName"
98 chartName := "chartName"
99 releaseName := "releaseName"
100 description := fmt.Sprintf("Description,%s,%s,%s,%s", namespace, repoName, chartName, releaseName)
101 newServiceDescription := getServiceAPIDescription(aefId, apiName, description)
103 // Publish a service for provider
104 result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
105 assert.Equal(t, http.StatusCreated, result.Code())
107 var resultService publishapi.ServiceAPIDescription
109 err = result.UnmarshalJsonToObject(&resultService)
110 assert.NoError(t, err, "error unmarshaling response")
111 newApiId := "api_id_" + apiName
112 assert.Equal(t, newApiId, *resultService.ApiId)
113 assert.Equal(t, "http://example.com/"+apfId+"/service-apis/"+*resultService.ApiId, result.Recorder.Header().Get(echo.HeaderLocation))
114 newServiceDescription.ApiId = &newApiId
115 assert.True(t, serviceUnderTest.IsAPIPublished(aefId, apiName))
116 serviceRegisterMock.AssertCalled(t, "GetAefsForPublisher", apfId)
117 helmManagerMock.AssertCalled(t, "InstallHelmChart", namespace, repoName, chartName, releaseName)
118 assert.ElementsMatch(t, []string{aefId}, serviceUnderTest.getAllAefIds())
119 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
120 assert.Fail(t, "No event sent")
122 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
123 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIAVAILABLE, publishEvent.Events)
126 // Check that the service is published for the provider
127 result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
129 assert.Equal(t, http.StatusOK, result.Code())
130 err = result.UnmarshalJsonToObject(&resultService)
131 assert.NoError(t, err, "error unmarshaling response")
132 assert.Equal(t, *resultService.ApiId, newApiId)
134 // Publish the same service again should result in Forbidden
135 result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
137 assert.Equal(t, http.StatusForbidden, result.Code())
138 var resultError common29122.ProblemDetails
139 err = result.UnmarshalJsonToObject(&resultError)
140 assert.NoError(t, err, "error unmarshaling response")
141 assert.Contains(t, *resultError.Cause, "already published")
142 assert.Equal(t, http.StatusForbidden, *resultError.Status)
144 // Delete the service
145 helmManagerMock.On("UninstallHelmChart", mock.Anything, mock.Anything).Return(nil)
147 result = testutil.NewRequest().Delete("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
149 assert.Equal(t, http.StatusNoContent, result.Code())
150 helmManagerMock.AssertCalled(t, "UninstallHelmChart", namespace, chartName)
151 assert.Empty(t, serviceUnderTest.getAllAefIds())
153 // Check no services published for a provider
154 result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
156 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
157 assert.Fail(t, "No event sent")
159 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
160 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE, publishEvent.Events)
163 assert.Equal(t, http.StatusNotFound, result.Code())
165 // Check no services published
166 result = testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
167 assert.Equal(t, http.StatusOK, result.Code())
169 // Parse JSON from the response body
170 var responseArray []publishapi.ServiceAPIDescription
171 err = result.UnmarshalJsonToObject(&responseArray)
172 assert.NoError(t, err, "error unmarshaling response")
174 // Check if the parsed array is empty
175 assert.Zero(t, len(responseArray))
178 func TestPostUnpublishedServiceWithUnregisteredFunction(t *testing.T) {
181 serviceRegisterMock := serviceMocks.ServiceRegister{}
182 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{"otherAefId"})
183 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
184 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
186 newServiceDescription := getServiceAPIDescription(aefId, "apiName", "description")
189 result := testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
191 assert.Equal(t, http.StatusNotFound, result.Code())
192 var resultError common29122.ProblemDetails
193 err := result.UnmarshalJsonToObject(&resultError)
194 assert.NoError(t, err, "error unmarshaling response")
195 assert.Contains(t, *resultError.Cause, aefId)
196 assert.Contains(t, *resultError.Cause, "not registered")
197 assert.Equal(t, http.StatusNotFound, *resultError.Status)
200 func TestGetServices(t *testing.T) {
203 serviceRegisterMock := serviceMocks.ServiceRegister{}
204 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId})
205 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
206 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
208 // Check no services published
209 var resultServices []publishapi.ServiceAPIDescription
211 result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
212 assert.Equal(t, http.StatusOK, result.Code())
214 // Parse JSON from the response body
215 err := result.UnmarshalJsonToObject(&resultServices)
216 assert.NoError(t, err, "error unmarshaling response")
218 // Check if the parsed array is empty
219 assert.Zero(t, len(resultServices))
221 serviceDescription1 := getServiceAPIDescription(aefId, "api1", "Description")
222 serviceDescription2 := getServiceAPIDescription(aefId, "api2", "Description")
224 // Publish a service for provider
225 testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription1).Go(t, requestHandler)
226 testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription2).Go(t, requestHandler)
228 // Get all services for provider
229 result = testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
230 assert.Equal(t, http.StatusOK, result.Code())
232 err = result.UnmarshalJsonToObject(&resultServices)
233 assert.NoError(t, err, "error unmarshaling response")
235 assert.Len(t, resultServices, 2)
236 apiId1 := "api_id_api1"
237 serviceDescription1.ApiId = &apiId1
238 apiId2 := "api_id_api2"
239 serviceDescription2.ApiId = &apiId2
241 assert.Contains(t, resultServices, serviceDescription1)
242 assert.Contains(t, resultServices, serviceDescription2)
245 func TestGetPublishedServices(t *testing.T) {
246 serviceUnderTest := NewPublishService(nil, nil, nil)
248 profiles := make([]publishapi.AefProfile, 1)
249 serviceDescription := publishapi.ServiceAPIDescription{
250 AefProfiles: &profiles,
252 serviceUnderTest.publishedServices["publisher1"] = []publishapi.ServiceAPIDescription{
255 serviceUnderTest.publishedServices["publisher2"] = []publishapi.ServiceAPIDescription{
258 result := serviceUnderTest.GetAllPublishedServices()
259 assert.Len(t, result, 2)
262 func TestUpdateDescription(t *testing.T) {
264 serviceApiId := "serviceApiId"
267 description := "description"
269 serviceRegisterMock := serviceMocks.ServiceRegister{}
270 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
271 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
272 helmManagerMock := helmMocks.HelmManager{}
273 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
274 serviceUnderTest, eventChannel, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
275 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
276 serviceDescription.ApiId = &serviceApiId
277 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
278 (*serviceDescription.AefProfiles)[0].AefId = aefId
281 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
282 updatedServiceDescription.ApiId = &serviceApiId
283 (*updatedServiceDescription.AefProfiles)[0].AefId = aefId
284 newDescription := "new description"
285 updatedServiceDescription.Description = &newDescription
286 newDomainName := "new domainName"
287 (*updatedServiceDescription.AefProfiles)[0].DomainName = &newDomainName
289 newProfileDomain := "new profile Domain name"
290 var protocol publishapi.Protocol = "HTTP_1_1"
292 test := append(*updatedServiceDescription.AefProfiles, publishapi.AefProfile{
294 DomainName: &newProfileDomain,
296 Versions: []publishapi.Version{
299 Resources: &[]publishapi.Resource{
301 CommType: "REQUEST_RESPONSE",
302 Operations: &[]publishapi.Operation{
314 updatedServiceDescription.AefProfiles = &test
316 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
318 var resultService publishapi.ServiceAPIDescription
319 assert.Equal(t, http.StatusOK, result.Code())
320 err := result.UnmarshalJsonToObject(&resultService)
321 assert.NoError(t, err, "error unmarshaling response")
322 assert.Equal(t, newDescription, *resultService.Description)
323 assert.Equal(t, newDomainName, *(*resultService.AefProfiles)[0].DomainName)
324 assert.Equal(t, "aefIdNew", (*resultService.AefProfiles)[1].AefId)
325 assert.True(t, serviceUnderTest.IsAPIPublished("aefIdNew", "path"))
327 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
328 assert.Fail(t, "No event sent")
330 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
331 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIUPDATE, publishEvent.Events)
335 func TestFailedUpdateDescription(t *testing.T) {
337 serviceApiId := "serviceApiId"
338 // Trying to update a different serviceApiId will cause a 400 error
339 updatedServiceApiId := "updatedServiceApiId"
342 description := "description"
344 serviceRegisterMock := serviceMocks.ServiceRegister{}
345 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
346 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
347 helmManagerMock := helmMocks.HelmManager{}
348 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
349 serviceUnderTest, _, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
350 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
351 serviceDescription.ApiId = &serviceApiId
352 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
353 (*serviceDescription.AefProfiles)[0].AefId = aefId
355 // Modify the service
356 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
357 updatedServiceDescription.ApiId = &updatedServiceApiId
358 (*updatedServiceDescription.AefProfiles)[0].AefId = aefId
359 newDescription := "new description"
360 updatedServiceDescription.Description = &newDescription
361 newDomainName := "new domainName"
362 (*updatedServiceDescription.AefProfiles)[0].DomainName = &newDomainName
364 newProfileDomain := "new profile Domain name"
365 var protocol publishapi.Protocol = "HTTP_1_1"
367 test := append(*updatedServiceDescription.AefProfiles, publishapi.AefProfile{
369 DomainName: &newProfileDomain,
371 Versions: []publishapi.Version{
374 Resources: &[]publishapi.Resource{
376 CommType: "REQUEST_RESPONSE",
377 Operations: &[]publishapi.Operation{
388 updatedServiceDescription.AefProfiles = &test
390 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
391 assert.Equal(t, http.StatusBadRequest, result.Code())
393 var resultError common29122.ProblemDetails
394 err := result.UnmarshalJsonToObject(&resultError)
395 assert.NoError(t, err, "error unmarshaling response")
397 assert.Contains(t, *resultError.Cause, "ServiceAPIDescription ApiId doesn't match path parameter")
398 assert.Equal(t, http.StatusBadRequest, *resultError.Status)
401 func TestUpdateValidServiceWithDeletedFunction(t *testing.T) {
403 serviceApiId := "serviceApiId"
406 description := "description"
408 serviceRegisterMock := serviceMocks.ServiceRegister{}
409 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
410 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
411 helmManagerMock := helmMocks.HelmManager{}
412 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
413 serviceUnderTest, _, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
415 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
416 serviceDescription.ApiId = &serviceApiId
417 (*serviceDescription.AefProfiles)[0].AefId = aefId
419 newProfileDomain := "new profile Domain name"
420 var protocol publishapi.Protocol = "HTTP_1_1"
421 test := append(*serviceDescription.AefProfiles, publishapi.AefProfile{
423 DomainName: &newProfileDomain,
425 Versions: []publishapi.Version{
428 Resources: &[]publishapi.Resource{
430 CommType: "REQUEST_RESPONSE",
431 Operations: &[]publishapi.Operation{
442 serviceDescription.AefProfiles = &test
443 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
446 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
447 updatedServiceDescription.ApiId = &serviceApiId
448 test1 := append(*updatedServiceDescription.AefProfiles, publishapi.AefProfile{
450 DomainName: &newProfileDomain,
452 Versions: []publishapi.Version{
455 Resources: &[]publishapi.Resource{
457 CommType: "REQUEST_RESPONSE",
458 Operations: &[]publishapi.Operation{
469 updatedServiceDescription.AefProfiles = &test1
470 testFunc := []publishapi.AefProfile{
471 (*updatedServiceDescription.AefProfiles)[1],
474 updatedServiceDescription.AefProfiles = &testFunc
475 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
476 var resultService publishapi.ServiceAPIDescription
477 assert.Equal(t, http.StatusOK, result.Code())
478 err := result.UnmarshalJsonToObject(&resultService)
479 assert.NoError(t, err, "error unmarshaling response")
480 assert.Len(t, (*resultService.AefProfiles), 1)
481 assert.False(t, serviceUnderTest.IsAPIPublished("aefId", "path"))
485 func TestPublishInvalidService(t *testing.T) {
487 serviceRegisterMock := serviceMocks.ServiceRegister{}
488 serviceRegisterMock.On("IsPublishingFunctionRegistered", apfId).Return(true)
490 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
491 newServiceDescription := getServiceAPIDescription("aefId", " ", "description")
494 result := testutil.NewRequest().Post("/apfId/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
496 assert.Equal(t, http.StatusBadRequest, result.Code())
497 var resultError common29122.ProblemDetails
498 err := result.UnmarshalJsonToObject(&resultError)
499 assert.NoError(t, err, "error unmarshaling response")
500 assert.Contains(t, *resultError.Cause, "missing")
501 assert.Contains(t, *resultError.Cause, "apiName")
502 assert.Equal(t, http.StatusBadRequest, *resultError.Status)
505 func getEcho(serviceRegister providermanagement.ServiceRegister, helmManager helmmanagement.HelmManager) (*PublishService, chan eventsapi.EventNotification, *echo.Echo) {
506 swagger, err := publishapi.GetSwagger()
508 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
512 swagger.Servers = nil
514 eventChannel := make(chan eventsapi.EventNotification)
515 ps := NewPublishService(serviceRegister, helmManager, eventChannel)
518 e.Use(echomiddleware.Logger())
519 e.Use(middleware.OapiRequestValidator(swagger))
521 publishapi.RegisterHandlers(e, ps)
522 return ps, eventChannel, e
525 func getServiceAPIDescription(aefId, apiName, description string) publishapi.ServiceAPIDescription {
526 domainName := "domainName"
527 var protocol publishapi.Protocol = "HTTP_1_1"
528 return publishapi.ServiceAPIDescription{
529 AefProfiles: &[]publishapi.AefProfile{
532 DomainName: &domainName,
534 Versions: []publishapi.Version{
537 Resources: &[]publishapi.Resource{
539 CommType: "REQUEST_RESPONSE",
540 Operations: &[]publishapi.Operation{
552 Description: &description,
556 // waitForEvent waits for the channel to receive an event for the specified max timeout.
557 // Returns true if waiting timed out.
558 func waitForEvent(ch chan eventsapi.EventNotification, timeout time.Duration) (*eventsapi.EventNotification, bool) {
561 return &event, false // completed normally
562 case <-time.After(timeout):
563 return nil, true // timed out