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 assert.True(t, serviceUnderTest.IsAPIPublished(aefId, apiName))
84 serviceRegisterMock.AssertCalled(t, "GetAefsForPublisher", apfId)
85 helmManagerMock.AssertCalled(t, "InstallHelmChart", namespace, repoName, chartName, releaseName)
86 assert.ElementsMatch(t, []string{aefId}, serviceUnderTest.getAllAefIds())
87 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
88 assert.Fail(t, "No event sent")
90 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
91 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIAVAILABLE, publishEvent.Events)
94 // Check that the service is published for the provider
95 result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
97 assert.Equal(t, http.StatusOK, result.Code())
98 err = result.UnmarshalBodyToObject(&resultService)
99 assert.NoError(t, err, "error unmarshaling response")
100 assert.Equal(t, *resultService.ApiId, newApiId)
102 // Publish the same service again should result in Forbidden
103 result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
105 assert.Equal(t, http.StatusForbidden, result.Code())
106 var resultError common29122.ProblemDetails
107 err = result.UnmarshalBodyToObject(&resultError)
108 assert.NoError(t, err, "error unmarshaling response")
109 assert.Contains(t, *resultError.Cause, "already published")
110 assert.Equal(t, http.StatusForbidden, *resultError.Status)
112 // Delete the service
113 helmManagerMock.On("UninstallHelmChart", mock.Anything, mock.Anything).Return(nil)
115 result = testutil.NewRequest().Delete("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
117 assert.Equal(t, http.StatusNoContent, result.Code())
118 helmManagerMock.AssertCalled(t, "UninstallHelmChart", namespace, chartName)
119 assert.Empty(t, serviceUnderTest.getAllAefIds())
121 // Check no services published
122 result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
124 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
125 assert.Fail(t, "No event sent")
127 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
128 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIUNAVAILABLE, publishEvent.Events)
131 assert.Equal(t, http.StatusNotFound, result.Code())
134 func TestPostUnpublishedServiceWithUnregisteredFunction(t *testing.T) {
137 serviceRegisterMock := serviceMocks.ServiceRegister{}
138 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{"otherAefId"})
139 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
141 newServiceDescription := getServiceAPIDescription(aefId, "apiName", "description")
144 result := testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
146 assert.Equal(t, http.StatusNotFound, result.Code())
147 var resultError common29122.ProblemDetails
148 err := result.UnmarshalBodyToObject(&resultError)
149 assert.NoError(t, err, "error unmarshaling response")
150 assert.Contains(t, *resultError.Cause, aefId)
151 assert.Contains(t, *resultError.Cause, "not registered")
152 assert.Equal(t, http.StatusNotFound, *resultError.Status)
155 func TestGetServices(t *testing.T) {
158 serviceRegisterMock := serviceMocks.ServiceRegister{}
159 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId})
160 _, _, requestHandler := getEcho(&serviceRegisterMock, nil)
162 // Check no services published for provider
163 result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
165 assert.Equal(t, http.StatusNotFound, result.Code())
167 serviceDescription1 := getServiceAPIDescription(aefId, "api1", "Description")
168 serviceDescription2 := getServiceAPIDescription(aefId, "api2", "Description")
170 // Publish a service for provider
171 testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription1).Go(t, requestHandler)
172 testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription2).Go(t, requestHandler)
174 // Get all services for provider
175 result = testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
176 assert.Equal(t, http.StatusOK, result.Code())
177 var resultServices []publishapi.ServiceAPIDescription
178 err := result.UnmarshalBodyToObject(&resultServices)
179 assert.NoError(t, err, "error unmarshaling response")
180 assert.Len(t, resultServices, 2)
181 apiId1 := "api_id_api1"
182 serviceDescription1.ApiId = &apiId1
183 apiId2 := "api_id_api2"
184 serviceDescription2.ApiId = &apiId2
185 assert.Contains(t, resultServices, serviceDescription1)
186 assert.Contains(t, resultServices, serviceDescription2)
189 func TestGetPublishedServices(t *testing.T) {
190 serviceUnderTest := NewPublishService(nil, nil, nil)
192 profiles := make([]publishapi.AefProfile, 1)
193 serviceDescription := publishapi.ServiceAPIDescription{
194 AefProfiles: &profiles,
196 serviceUnderTest.publishedServices["publisher1"] = []publishapi.ServiceAPIDescription{
199 serviceUnderTest.publishedServices["publisher2"] = []publishapi.ServiceAPIDescription{
202 result := serviceUnderTest.GetAllPublishedServices()
203 assert.Len(t, result, 2)
206 func TestUpdateDescription(t *testing.T) {
208 serviceApiId := "serviceApiId"
211 description := "description"
213 serviceRegisterMock := serviceMocks.ServiceRegister{}
214 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
215 helmManagerMock := helmMocks.HelmManager{}
216 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
217 serviceUnderTest, eventChannel, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
218 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
219 serviceDescription.ApiId = &serviceApiId
220 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
221 (*serviceDescription.AefProfiles)[0].AefId = aefId
224 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
225 updatedServiceDescription.ApiId = &serviceApiId
226 (*updatedServiceDescription.AefProfiles)[0].AefId = aefId
227 newDescription := "new description"
228 updatedServiceDescription.Description = &newDescription
229 newDomainName := "new domainName"
230 (*updatedServiceDescription.AefProfiles)[0].DomainName = &newDomainName
232 newProfileDomain := "new profile Domain name"
233 var protocol publishapi.Protocol = "HTTP_1_1"
234 test := make([]publishapi.AefProfile, 1)
235 test = *updatedServiceDescription.AefProfiles
236 test = append(test, publishapi.AefProfile{
239 DomainName: &newProfileDomain,
241 Versions: []publishapi.Version{
244 Resources: &[]publishapi.Resource{
246 CommType: "REQUEST_RESPONSE",
247 Operations: &[]publishapi.Operation{
259 updatedServiceDescription.AefProfiles = &test
261 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
263 var resultService publishapi.ServiceAPIDescription
264 assert.Equal(t, http.StatusOK, result.Code())
265 err := result.UnmarshalBodyToObject(&resultService)
266 assert.NoError(t, err, "error unmarshaling response")
267 assert.Equal(t, newDescription, *resultService.Description)
268 assert.Equal(t, newDomainName, *(*resultService.AefProfiles)[0].DomainName)
269 assert.Equal(t, "aefIdNew", (*resultService.AefProfiles)[1].AefId)
270 assert.True(t, serviceUnderTest.IsAPIPublished("aefIdNew", "path"))
272 if publishEvent, ok := waitForEvent(eventChannel, 1*time.Second); ok {
273 assert.Fail(t, "No event sent")
275 assert.Equal(t, *resultService.ApiId, (*publishEvent.EventDetail.ApiIds)[0])
276 assert.Equal(t, eventsapi.CAPIFEventSERVICEAPIUPDATE, publishEvent.Events)
280 func TestUpdateValidServiceWithDeletedFunction(t *testing.T) {
282 serviceApiId := "serviceApiId"
285 description := "description"
287 serviceRegisterMock := serviceMocks.ServiceRegister{}
288 serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId", "aefIdNew"})
289 helmManagerMock := helmMocks.HelmManager{}
290 helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
291 serviceUnderTest, _, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
293 serviceDescription := getServiceAPIDescription(aefId, apiName, description)
294 serviceDescription.ApiId = &serviceApiId
295 (*serviceDescription.AefProfiles)[0].AefId = aefId
297 newProfileDomain := "new profile Domain name"
298 var protocol publishapi.Protocol = "HTTP_1_1"
299 test := make([]publishapi.AefProfile, 1)
300 test = *serviceDescription.AefProfiles
301 test = append(test, publishapi.AefProfile{
304 DomainName: &newProfileDomain,
306 Versions: []publishapi.Version{
309 Resources: &[]publishapi.Resource{
311 CommType: "REQUEST_RESPONSE",
312 Operations: &[]publishapi.Operation{
323 serviceDescription.AefProfiles = &test
324 serviceUnderTest.publishedServices[apfId] = []publishapi.ServiceAPIDescription{serviceDescription}
327 updatedServiceDescription := getServiceAPIDescription(aefId, apiName, description)
328 updatedServiceDescription.ApiId = &serviceApiId
329 test1 := make([]publishapi.AefProfile, 1)
330 test1 = *updatedServiceDescription.AefProfiles
331 test1 = append(test1, publishapi.AefProfile{
334 DomainName: &newProfileDomain,
336 Versions: []publishapi.Version{
339 Resources: &[]publishapi.Resource{
341 CommType: "REQUEST_RESPONSE",
342 Operations: &[]publishapi.Operation{
353 updatedServiceDescription.AefProfiles = &test1
354 testFunc := []publishapi.AefProfile{
355 (*updatedServiceDescription.AefProfiles)[1],
358 updatedServiceDescription.AefProfiles = &testFunc
359 result := testutil.NewRequest().Put("/"+apfId+"/service-apis/"+serviceApiId).WithJsonBody(updatedServiceDescription).Go(t, requestHandler)
360 var resultService publishapi.ServiceAPIDescription
361 assert.Equal(t, http.StatusOK, result.Code())
362 err := result.UnmarshalBodyToObject(&resultService)
363 assert.NoError(t, err, "error unmarshaling response")
364 assert.Len(t, (*resultService.AefProfiles), 1)
365 assert.False(t, serviceUnderTest.IsAPIPublished("aefId", "path"))
369 func TestPublishInvalidService(t *testing.T) {
370 _, _, requestHandler := getEcho(nil, nil)
371 newServiceDescription := getServiceAPIDescription("aefId", " ", "description")
374 result := testutil.NewRequest().Post("/apfId/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
376 assert.Equal(t, http.StatusBadRequest, result.Code())
377 var resultError common29122.ProblemDetails
378 err := result.UnmarshalBodyToObject(&resultError)
379 assert.NoError(t, err, "error unmarshaling response")
380 assert.Contains(t, *resultError.Cause, "missing")
381 assert.Contains(t, *resultError.Cause, "apiName")
382 assert.Equal(t, http.StatusBadRequest, *resultError.Status)
385 func getEcho(serviceRegister providermanagement.ServiceRegister, helmManager helmmanagement.HelmManager) (*PublishService, chan eventsapi.EventNotification, *echo.Echo) {
386 swagger, err := publishapi.GetSwagger()
388 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
392 swagger.Servers = nil
394 eventChannel := make(chan eventsapi.EventNotification)
395 ps := NewPublishService(serviceRegister, helmManager, eventChannel)
398 e.Use(echomiddleware.Logger())
399 e.Use(middleware.OapiRequestValidator(swagger))
401 publishapi.RegisterHandlers(e, ps)
402 return ps, eventChannel, e
405 func getServiceAPIDescription(aefId, apiName, description string) publishapi.ServiceAPIDescription {
406 domainName := "domainName"
407 var protocol publishapi.Protocol = "HTTP_1_1"
408 return publishapi.ServiceAPIDescription{
409 AefProfiles: &[]publishapi.AefProfile{
412 DomainName: &domainName,
414 Versions: []publishapi.Version{
417 Resources: &[]publishapi.Resource{
419 CommType: "REQUEST_RESPONSE",
420 Operations: &[]publishapi.Operation{
432 Description: &description,
436 // waitForEvent waits for the channel to receive an event for the specified max timeout.
437 // Returns true if waiting timed out.
438 func waitForEvent(ch chan eventsapi.EventNotification, timeout time.Duration) (*eventsapi.EventNotification, bool) {
441 return &event, false // completed normally
442 case <-time.After(timeout):
443 return nil, true // timed out