Implement GetApfIdServiceApis for Publish service
[nonrtric/plt/sme.git] / capifcore / internal / publishservice / publishservice_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: 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 publishservice
22
23 import (
24         "fmt"
25         "net/http"
26         "os"
27         "testing"
28
29         "oransc.org/nonrtric/capifcore/internal/common29122"
30         "oransc.org/nonrtric/capifcore/internal/providermanagement"
31
32         "github.com/labstack/echo/v4"
33
34         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
35
36         "oransc.org/nonrtric/capifcore/internal/helmmanagement"
37         helmMocks "oransc.org/nonrtric/capifcore/internal/helmmanagement/mocks"
38         serviceMocks "oransc.org/nonrtric/capifcore/internal/providermanagement/mocks"
39
40         "github.com/deepmap/oapi-codegen/pkg/middleware"
41         "github.com/deepmap/oapi-codegen/pkg/testutil"
42         echomiddleware "github.com/labstack/echo/v4/middleware"
43         "github.com/stretchr/testify/assert"
44         "github.com/stretchr/testify/mock"
45 )
46
47 func TestPublishUnpublishService(t *testing.T) {
48         apfId := "apfId"
49         aefId := "aefId"
50         serviceRegisterMock := serviceMocks.ServiceRegister{}
51         serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId, "otherAefId"})
52         helmManagerMock := helmMocks.HelmManager{}
53         helmManagerMock.On("InstallHelmChart", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
54         serviceUnderTest, requestHandler := getEcho(&serviceRegisterMock, &helmManagerMock)
55
56         // Check no services published for provider
57         result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
58
59         assert.Equal(t, http.StatusNotFound, result.Code())
60
61         apiName := "app-management"
62         description := "Description,namespace,repoName,chartName,releaseName"
63         newServiceDescription := getServiceAPIDescription(aefId, apiName, description)
64
65         // Publish a service for provider
66         result = testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
67
68         assert.Equal(t, http.StatusCreated, result.Code())
69         var resultService publishapi.ServiceAPIDescription
70         err := result.UnmarshalBodyToObject(&resultService)
71         assert.NoError(t, err, "error unmarshaling response")
72         newApiId := "api_id_app-management"
73         assert.Equal(t, *resultService.ApiId, newApiId)
74         assert.Equal(t, "http://example.com/"+apfId+"/service-apis/"+*resultService.ApiId, result.Recorder.Header().Get(echo.HeaderLocation))
75         newServiceDescription.ApiId = &newApiId
76         wantedAPILIst := []publishapi.ServiceAPIDescription{newServiceDescription}
77         assert.True(t, serviceUnderTest.AreAPIsPublished(&wantedAPILIst))
78         assert.True(t, serviceUnderTest.IsAPIPublished("aefId", "app-management"))
79         serviceRegisterMock.AssertCalled(t, "GetAefsForPublisher", apfId)
80         helmManagerMock.AssertCalled(t, "InstallHelmChart", "namespace", "repoName", "chartName", "releaseName")
81         assert.ElementsMatch(t, []string{aefId}, serviceUnderTest.getAllAefIds())
82
83         // Check that the service is published for the provider
84         result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
85
86         assert.Equal(t, http.StatusOK, result.Code())
87         err = result.UnmarshalBodyToObject(&resultService)
88         assert.NoError(t, err, "error unmarshaling response")
89         assert.Equal(t, *resultService.ApiId, newApiId)
90
91         // Delete the service
92         helmManagerMock.On("UninstallHelmChart", mock.Anything, mock.Anything).Return(nil)
93         result = testutil.NewRequest().Delete("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
94
95         assert.Equal(t, http.StatusNoContent, result.Code())
96         helmManagerMock.AssertCalled(t, "UninstallHelmChart", "namespace", "chartName")
97         assert.Empty(t, serviceUnderTest.getAllAefIds())
98
99         // Check no services published
100         result = testutil.NewRequest().Get("/"+apfId+"/service-apis/"+newApiId).Go(t, requestHandler)
101
102         assert.Equal(t, http.StatusNotFound, result.Code())
103 }
104
105 func TestPostUnpublishedServiceWithUnregisteredFunction(t *testing.T) {
106         apfId := "apfId"
107         aefId := "aefId"
108         serviceRegisterMock := serviceMocks.ServiceRegister{}
109         serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{"otherAefId"})
110         _, requestHandler := getEcho(&serviceRegisterMock, nil)
111
112         newServiceDescription := getServiceAPIDescription(aefId, "apiname", "description")
113
114         // Publish a service
115         result := testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(newServiceDescription).Go(t, requestHandler)
116
117         assert.Equal(t, http.StatusNotFound, result.Code())
118         var resultError common29122.ProblemDetails
119         err := result.UnmarshalBodyToObject(&resultError)
120         assert.NoError(t, err, "error unmarshaling response")
121         errMsg := "Function not registered, aefId"
122         assert.Equal(t, &errMsg, resultError.Cause)
123         notFound := http.StatusNotFound
124         assert.Equal(t, &notFound, resultError.Status)
125 }
126
127 func TestGetServices(t *testing.T) {
128         apfId := "apfId"
129         aefId := "aefId"
130         serviceRegisterMock := serviceMocks.ServiceRegister{}
131         serviceRegisterMock.On("GetAefsForPublisher", apfId).Return([]string{aefId})
132         _, requestHandler := getEcho(&serviceRegisterMock, nil)
133
134         // Check no services published for provider
135         result := testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
136
137         assert.Equal(t, http.StatusNotFound, result.Code())
138
139         serviceDescription1 := getServiceAPIDescription(aefId, "api1", "Description")
140         serviceDescription2 := getServiceAPIDescription(aefId, "api2", "Description")
141
142         // Publish a service for provider
143         testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription1).Go(t, requestHandler)
144         testutil.NewRequest().Post("/"+apfId+"/service-apis").WithJsonBody(serviceDescription2).Go(t, requestHandler)
145
146         // Get all services for provider
147         result = testutil.NewRequest().Get("/"+apfId+"/service-apis").Go(t, requestHandler)
148         assert.Equal(t, http.StatusOK, result.Code())
149         var resultServices []publishapi.ServiceAPIDescription
150         err := result.UnmarshalBodyToObject(&resultServices)
151         assert.NoError(t, err, "error unmarshaling response")
152         assert.Len(t, resultServices, 2)
153         apiId1 := "api_id_api1"
154         serviceDescription1.ApiId = &apiId1
155         apiId2 := "api_id_api2"
156         serviceDescription2.ApiId = &apiId2
157         assert.Contains(t, resultServices, serviceDescription1)
158         assert.Contains(t, resultServices, serviceDescription2)
159 }
160
161 func getEcho(serviceRegister providermanagement.ServiceRegister, helmManager helmmanagement.HelmManager) (*PublishService, *echo.Echo) {
162         swagger, err := publishapi.GetSwagger()
163         if err != nil {
164                 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
165                 os.Exit(1)
166         }
167
168         swagger.Servers = nil
169
170         ps := NewPublishService(serviceRegister, helmManager)
171
172         e := echo.New()
173         e.Use(echomiddleware.Logger())
174         e.Use(middleware.OapiRequestValidator(swagger))
175
176         publishapi.RegisterHandlers(e, ps)
177         return ps, e
178 }
179
180 func getServiceAPIDescription(aefId, apiName, description string) publishapi.ServiceAPIDescription {
181         domainName := "domainName"
182         var protocol publishapi.Protocol = "HTTP_1_1"
183         return publishapi.ServiceAPIDescription{
184                 AefProfiles: &[]publishapi.AefProfile{
185                         {
186                                 AefId:      aefId,
187                                 DomainName: &domainName,
188                                 Protocol:   &protocol,
189                                 Versions: []publishapi.Version{
190                                         {
191                                                 ApiVersion: "v1",
192                                                 Resources: &[]publishapi.Resource{
193                                                         {
194                                                                 CommType: "REQUEST_RESPONSE",
195                                                                 Operations: &[]publishapi.Operation{
196                                                                         "POST",
197                                                                 },
198                                                                 ResourceName: "app",
199                                                                 Uri:          "app",
200                                                         },
201                                                 },
202                                         },
203                                 },
204                         },
205                 },
206                 ApiName:     apiName,
207                 Description: &description,
208         }
209 }